: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
chore(cdp-legacy): group batch enrichment (#59546)
Nick Bestdf4e70a7dcd7
diff --git a/nodejs/src/cdp/legacy-webhooks/legacy-webhook-service.test.ts b/nodejs/src/cdp/legacy-webhooks/legacy-webhook-service.test.tsindex 5e7a53cfeb41..62dffb71480a 100644--- a/nodejs/src/cdp/legacy-webhooks/legacy-webhook-service.test.ts+++ b/nodejs/src/cdp/legacy-webhooks/legacy-webhook-service.test.ts@@ -170,12 +170,17 @@ describe('LegacyWebhookService', () => {it('should enrich events with group properties when available', async () => {service['actionMatcher'].hasWebhooks = jest.fn().mockReturnValue(true)hub.teamManager.hasAvailableFeature = jest.fn().mockResolvedValue(true)- hub.groupTypeManager.fetchGroupTypes = jest.fn().mockResolvedValue({- project: 0,- })- hub.groupRepository.fetchGroup = jest.fn().mockResolvedValue({- group_properties: { name: 'Test Project' },+ hub.groupTypeManager.fetchGroupTypesForProjects = jest.fn().mockResolvedValue({+ [team.id]: { project: 0 },})+ hub.groupRepository.fetchGroupsByKeys = jest.fn().mockResolvedValue([+ {+ team_id: team.id,+ group_type_index: 0,+ group_key: 'test-project-id',+ group_properties: { name: 'Test Project' },+ },+ ])const processEventSpy = jest.spyOn(service, 'processEvent')@@ -201,6 +206,63 @@ describe('LegacyWebhookService', () => {properties: { name: 'Test Project' },})})++ it('should process events without group properties when batch enrichment fails', async () => {+ service['actionMatcher'].hasWebhooks = jest.fn().mockReturnValue(true)+ hub.teamManager.hasAvailableFeature = jest.fn().mockResolvedValue(true)+ hub.groupTypeManager.fetchGroupTypesForProjects = jest.fn().mockRejectedValue(new Error('gRPC unavailable'))++ const processEventSpy = jest.spyOn(service, 'processEvent').mockResolvedValue(undefined)++ const messages: Message[] = [+ createKafkaMessage(+ createIncomingEvent(team.id, {+ event: '$pageview',+ properties: JSON.stringify({ $groups: { project: 'test-project-id' } }),+ })+ ),+ ]++ const result = await service.processBatch(messages)+ await result.backgroundTask++ expect(processEventSpy).toHaveBeenCalledTimes(1)+ const processedEvent = processEventSpy.mock.calls[0][0]+ expect(processedEvent.groups).toBeUndefined()+ })++ it('should process all events when fetchGroupsByKeys throws', async () => {+ service['actionMatcher'].hasWebhooks = jest.fn().mockReturnValue(true)+ hub.teamManager.hasAvailableFeature = jest.fn().mockResolvedValue(true)+ hub.groupTypeManager.fetchGroupTypesForProjects = jest.fn().mockResolvedValue({+ [team.id]: { project: 0 },+ })+ hub.groupRepository.fetchGroupsByKeys = jest.fn().mockRejectedValue(new Error('connection reset'))++ const processEventSpy = jest.spyOn(service, 'processEvent').mockResolvedValue(undefined)++ const messages: Message[] = [+ createKafkaMessage(+ createIncomingEvent(team.id, {+ event: '$pageview',+ properties: JSON.stringify({ $groups: { project: 'p1' } }),+ })+ ),+ createKafkaMessage(+ createIncomingEvent(team.id, {+ event: '$autocapture',+ properties: JSON.stringify({ $groups: { project: 'p2' } }),+ })+ ),+ ]++ const result = await service.processBatch(messages)+ await result.backgroundTask++ expect(processEventSpy).toHaveBeenCalledTimes(2)+ expect(processEventSpy.mock.calls[0][0].groups).toBeUndefined()+ expect(processEventSpy.mock.calls[1][0].groups).toBeUndefined()+ })})describe('processEvent', () => {@@ -394,14 +456,17 @@ describe('LegacyWebhookService', () => {describe('PersonHogGroupRepository compatibility', () => {it('should enrich events with group properties when groupRepository is wrapped with PersonHogGroupRepository', async () => {- // Wrap the real postgres groupRepository with PersonHogGroupRepository at 100% gRPC rollout- // with a mock gRPC client that returns the same data as the existing mockconst mockGrpcClient: MockPersonHogClient = {groups: {- fetchGroup: jest.fn().mockResolvedValue({- group_properties: { name: 'Test Project' },- } as any),- fetchGroupsByKeys: jest.fn(),+ fetchGroup: jest.fn(),+ fetchGroupsByKeys: jest.fn().mockResolvedValue([+ {+ team_id: team.id,+ group_type_index: 0,+ group_key: 'test-project-id',+ group_properties: { name: 'Test Project' },+ },+ ]),fetchGroupTypesByTeamIds: jest.fn(),fetchGroupTypesByProjectIds: jest.fn(),},@@ -430,8 +495,8 @@ describe('LegacyWebhookService', () => {personhogService['actionMatcher'].hasWebhooks = jest.fn().mockReturnValue(true)hub.teamManager.hasAvailableFeature = jest.fn().mockResolvedValue(true)- hub.groupTypeManager.fetchGroupTypes = jest.fn().mockResolvedValue({- project: 0,+ hub.groupTypeManager.fetchGroupTypesForProjects = jest.fn().mockResolvedValue({+ [team.id]: { project: 0 },})const processEventSpy = jest.spyOn(personhogService, 'processEvent')@@ -458,8 +523,7 @@ describe('LegacyWebhookService', () => {properties: { name: 'Test Project' },})- // fetchGroup with useReadReplica: true should route to gRPC at 100%- expect(mockGrpcClient.groups.fetchGroup).toHaveBeenCalled()+ expect(mockGrpcClient.groups.fetchGroupsByKeys).toHaveBeenCalled()await personhogService.stop()})diff --git a/nodejs/src/cdp/legacy-webhooks/legacy-webhook-service.ts b/nodejs/src/cdp/legacy-webhooks/legacy-webhook-service.tsindex 5b61088f6ed1..e37078fff6cd 100644--- a/nodejs/src/cdp/legacy-webhooks/legacy-webhook-service.ts+++ b/nodejs/src/cdp/legacy-webhooks/legacy-webhook-service.ts@@ -14,7 +14,7 @@ import { GroupRepository } from '../../worker/ingestion/groups/repositories/grouimport { counterParseError } from '../consumers/metrics'import { ActionManager } from '../legacy-webhooks/action-manager'import { ActionMatcher } from '../legacy-webhooks/action-matcher'-import { addGroupPropertiesToPostIngestionEvent } from '../legacy-webhooks/utils'+import { addGroupPropertiesToPostIngestionEventsBatch } from '../legacy-webhooks/utils'import { cdpTrackedFetch } from '../services/hog-executor.service'export class LegacyWebhookService {@@ -99,7 +99,7 @@ export class LegacyWebhookService {}public async processBatch(messages: Message[]): Promise<{ backgroundTask: Promise<any> }> {- const events: PostIngestionEvent[] = []+ const eventsWithoutGroups: PostIngestionEvent[] = []await Promise.all(messages.map(async (message) => {@@ -110,23 +110,10 @@ export class LegacyWebhookService {!this.actionMatcher.hasWebhooks(clickHouseEvent.team_id) ||!(await this.teamManager.hasAvailableFeature(clickHouseEvent.team_id, 'zapier'))) {- // exit early if no webhooks nor resthooksreturn}- const eventWithoutGroups = convertToPostIngestionEvent(clickHouseEvent)- // This is very inefficient, we always pull group properties for all groups (up to 5) for this event- // from PG if a webhook is defined for this team.- // Instead we should be lazily loading group properties only when needed, but this is the fastest way to fix this consumer- // that will be deprecated in the near future by CDP/Hog- const event = await addGroupPropertiesToPostIngestionEvent(- eventWithoutGroups,- this.groupTypeManager,- this.teamManager,- this.groupRepository- )-- events.push(event)+ eventsWithoutGroups.push(convertToPostIngestionEvent(clickHouseEvent))} catch (e) {logger.error('Error parsing message', e)counterParseError.labels({ error: e.message }).inc()@@ -134,6 +121,19 @@ export class LegacyWebhookService {}))+ let events: PostIngestionEvent[]+ try {+ events = await addGroupPropertiesToPostIngestionEventsBatch(+ eventsWithoutGroups,+ this.groupTypeManager,+ this.teamManager,+ this.groupRepository+ )+ } catch (e) {+ logger.error('Batch group enrichment failed, processing events without group properties', e)+ events = eventsWithoutGroups+ }+return { backgroundTask: Promise.all(events.map((event) => this.processEvent(event))) }}diff --git a/nodejs/src/cdp/legacy-webhooks/utils.test.ts b/nodejs/src/cdp/legacy-webhooks/utils.test.tsnew file mode 100644index 000000000000..68c3f90a9a20--- /dev/null+++ b/nodejs/src/cdp/legacy-webhooks/utils.test.ts@@ -0,0 +1,504 @@+import { GroupTypeIndex, ISOTimestamp, PostIngestionEvent, ProjectId, TeamId } from '~/types'+import { TeamManager } from '~/utils/team-manager'+import { GroupTypeManager, GroupTypesByProjectId } from '~/worker/ingestion/group-type-manager'+import { GroupRepository } from '~/worker/ingestion/groups/repositories/group-repository.interface'++import { addGroupPropertiesToPostIngestionEventsBatch } from './utils'++function makeEvent(teamId: number, overrides: Partial<PostIngestionEvent> = {}): PostIngestionEvent {+ return {+ eventUuid: `uuid-${Math.random()}`,+ event: '$pageview',+ teamId: teamId as TeamId,+ projectId: teamId as ProjectId,+ distinctId: 'user-1',+ properties: {},+ timestamp: '2024-01-01T00:00:00.000Z' as ISOTimestamp,+ person_created_at: null,+ person_properties: {},+ person_id: undefined,+ ...overrides,+ }+}++function makeEventWithGroups(+ teamId: number,+ groups: Record<string, string>,+ overrides: Partial<PostIngestionEvent> = {}+): PostIngestionEvent {+ return makeEvent(teamId, {+ properties: { $groups: groups },+ ...overrides,+ })+}++describe('addGroupPropertiesToPostIngestionEventsBatch', () => {+ let mockTeamManager: jest.Mocked<Pick<TeamManager, 'hasAvailableFeature'>>+ let mockGroupTypeManager: jest.Mocked<Pick<GroupTypeManager, 'fetchGroupTypesForProjects'>>+ let mockGroupRepository: jest.Mocked<Pick<GroupRepository, 'fetchGroupsByKeys'>>++ beforeEach(() => {+ mockTeamManager = {+ hasAvailableFeature: jest.fn().mockResolvedValue(false),+ }+ mockGroupTypeManager = {+ fetchGroupTypesForProjects: jest.fn().mockResolvedValue({}),+ }+ mockGroupRepository = {+ fetchGroupsByKeys: jest.fn().mockResolvedValue([]),+ }+ })++ it('returns empty array for empty input', async () => {+ const result = await addGroupPropertiesToPostIngestionEventsBatch(+ [],+ mockGroupTypeManager as unknown as GroupTypeManager,+ mockTeamManager as unknown as TeamManager,+ mockGroupRepository as unknown as GroupRepository+ )+ expect(result).toEqual([])+ expect(mockTeamManager.hasAvailableFeature).not.toHaveBeenCalled()+ })++ it('returns events unchanged when no team has group_analytics', async () => {+ mockTeamManager.hasAvailableFeature.mockResolvedValue(false)+ const events = [makeEventWithGroups(1, { project: 'p1' })]++ const result = await addGroupPropertiesToPostIngestionEventsBatch(+ events,+ mockGroupTypeManager as unknown as GroupTypeManager,+ mockTeamManager as unknown as TeamManager,+ mockGroupRepository as unknown as GroupRepository+ )++ expect(result).toEqual(events)+ expect(mockGroupTypeManager.fetchGroupTypesForProjects).not.toHaveBeenCalled()+ expect(mockGroupRepository.fetchGroupsByKeys).not.toHaveBeenCalled()+ })++ it('checks group_analytics once per unique team', async () => {+ mockTeamManager.hasAvailableFeature.mockResolvedValue(true)+ mockGroupTypeManager.fetchGroupTypesForProjects.mockResolvedValue({})++ const events = [makeEvent(1), makeEvent(1), makeEvent(2), makeEvent(1)]++ await addGroupPropertiesToPostIngestionEventsBatch(+ events,+ mockGroupTypeManager as unknown as GroupTypeManager,+ mockTeamManager as unknown as TeamManager,+ mockGroupRepository as unknown as GroupRepository+ )++ expect(mockTeamManager.hasAvailableFeature).toHaveBeenCalledTimes(2)+ expect(mockTeamManager.hasAvailableFeature).toHaveBeenCalledWith(1, 'group_analytics')+ expect(mockTeamManager.hasAvailableFeature).toHaveBeenCalledWith(2, 'group_analytics')+ })++ it('enriches a single event with group properties', async () => {+ mockTeamManager.hasAvailableFeature.mockResolvedValue(true)+ mockGroupTypeManager.fetchGroupTypesForProjects.mockResolvedValue({+ '1': { company: 0 as GroupTypeIndex },+ } as GroupTypesByProjectId)+ mockGroupRepository.fetchGroupsByKeys.mockResolvedValue([+ {+ team_id: 1 as TeamId,+ group_type_index: 0 as GroupTypeIndex,+ group_key: 'acme',+ group_properties: { name: 'Acme Inc' },+ },+ ])++ const events = [makeEventWithGroups(1, { company: 'acme' })]++ const result = await addGroupPropertiesToPostIngestionEventsBatch(+ events,+ mockGroupTypeManager as unknown as GroupTypeManager,+ mockTeamManager as unknown as TeamManager,+ mockGroupRepository as unknown as GroupRepository+ )++ expect(result[0].groups).toEqual({+ company: {+ index: 0,+ key: 'acme',+ type: 'company',+ properties: { name: 'Acme Inc' },+ },+ })+ })++ it('deduplicates identical group lookups across events', async () => {+ mockTeamManager.hasAvailableFeature.mockResolvedValue(true)+ mockGroupTypeManager.fetchGroupTypesForProjects.mockResolvedValue({+ '1': { company: 0 as GroupTypeIndex },+ } as GroupTypesByProjectId)+ mockGroupRepository.fetchGroupsByKeys.mockResolvedValue([+ {+ team_id: 1 as TeamId,+ group_type_index: 0 as GroupTypeIndex,+ group_key: 'acme',+ group_properties: { name: 'Acme Inc' },+ },+ ])++ const events = [+ makeEventWithGroups(1, { company: 'acme' }),+ makeEventWithGroups(1, { company: 'acme' }),+ makeEventWithGroups(1, { company: 'acme' }),+ ]++ const result = await addGroupPropertiesToPostIngestionEventsBatch(+ events,+ mockGroupTypeManager as unknown as GroupTypeManager,+ mockTeamManager as unknown as TeamManager,+ mockGroupRepository as unknown as GroupRepository+ )++ expect(mockGroupRepository.fetchGroupsByKeys).toHaveBeenCalledTimes(1)+ expect(mockGroupRepository.fetchGroupsByKeys).toHaveBeenCalledWith([1], [0], ['acme'])++ for (const event of result) {+ expect(event.groups?.company).toEqual({+ index: 0,+ key: 'acme',+ type: 'company',+ properties: { name: 'Acme Inc' },+ })+ }+ })++ it('handles multiple group types per event', async () => {+ mockTeamManager.hasAvailableFeature.mockResolvedValue(true)+ mockGroupTypeManager.fetchGroupTypesForProjects.mockResolvedValue({+ '1': {+ company: 0 as GroupTypeIndex,+ project: 1 as GroupTypeIndex,+ },+ } as GroupTypesByProjectId)+ mockGroupRepository.fetchGroupsByKeys.mockResolvedValue([+ {+ team_id: 1 as TeamId,+ group_type_index: 0 as GroupTypeIndex,+ group_key: 'acme',+ group_properties: { name: 'Acme Inc' },+ },+ {+ team_id: 1 as TeamId,+ group_type_index: 1 as GroupTypeIndex,+ group_key: 'proj-1',+ group_properties: { name: 'Project Alpha' },+ },+ ])++ const events = [makeEventWithGroups(1, { company: 'acme', project: 'proj-1' })]++ const result = await addGroupPropertiesToPostIngestionEventsBatch(+ events,+ mockGroupTypeManager as unknown as GroupTypeManager,+ mockTeamManager as unknown as TeamManager,+ mockGroupRepository as unknown as GroupRepository+ )++ expect(result[0].groups).toEqual({+ company: {+ index: 0,+ key: 'acme',+ type: 'company',+ properties: { name: 'Acme Inc' },+ },+ project: {+ index: 1,+ key: 'proj-1',+ type: 'project',+ properties: { name: 'Project Alpha' },+ },+ })+ })++ it('handles mixed teams where only some have group_analytics', async () => {+ mockTeamManager.hasAvailableFeature.mockImplementation((teamId) => {+ return Promise.resolve(teamId === 1)+ })+ mockGroupTypeManager.fetchGroupTypesForProjects.mockResolvedValue({+ '1': { company: 0 as GroupTypeIndex },+ } as GroupTypesByProjectId)+ mockGroupRepository.fetchGroupsByKeys.mockResolvedValue([+ {+ team_id: 1 as TeamId,+ group_type_index: 0 as GroupTypeIndex,+ group_key: 'acme',+ group_properties: { name: 'Acme Inc' },+ },+ ])++ const events = [makeEventWithGroups(1, { company: 'acme' }), makeEventWithGroups(2, { company: 'other-co' })]++ const result = await addGroupPropertiesToPostIngestionEventsBatch(+ events,+ mockGroupTypeManager as unknown as GroupTypeManager,+ mockTeamManager as unknown as TeamManager,+ mockGroupRepository as unknown as GroupRepository+ )++ expect(result[0].groups?.company).toEqual({+ index: 0,+ key: 'acme',+ type: 'company',+ properties: { name: 'Acme Inc' },+ })+ expect(result[1].groups).toBeUndefined()+ })++ it('returns empty properties when group is not found', async () => {+ mockTeamManager.hasAvailableFeature.mockResolvedValue(true)+ mockGroupTypeManager.fetchGroupTypesForProjects.mockResolvedValue({+ '1': { company: 0 as GroupTypeIndex },+ } as GroupTypesByProjectId)+ mockGroupRepository.fetchGroupsByKeys.mockResolvedValue([])++ const events = [makeEventWithGroups(1, { company: 'nonexistent' })]++ const result = await addGroupPropertiesToPostIngestionEventsBatch(+ events,+ mockGroupTypeManager as unknown as GroupTypeManager,+ mockTeamManager as unknown as TeamManager,+ mockGroupRepository as unknown as GroupRepository+ )++ expect(result[0].groups).toEqual({+ company: {+ index: 0,+ key: 'nonexistent',+ type: 'company',+ properties: {},+ },+ })+ })++ it('skips group types where event has no matching $groups key', async () => {+ mockTeamManager.hasAvailableFeature.mockResolvedValue(true)+ mockGroupTypeManager.fetchGroupTypesForProjects.mockResolvedValue({+ '1': {+ company: 0 as GroupTypeIndex,+ project: 1 as GroupTypeIndex,+ },+ } as GroupTypesByProjectId)+ mockGroupRepository.fetchGroupsByKeys.mockResolvedValue([+ {+ team_id: 1 as TeamId,+ group_type_index: 0 as GroupTypeIndex,+ group_key: 'acme',+ group_properties: { name: 'Acme Inc' },+ },+ ])++ const events = [makeEventWithGroups(1, { company: 'acme' })]++ const result = await addGroupPropertiesToPostIngestionEventsBatch(+ events,+ mockGroupTypeManager as unknown as GroupTypeManager,+ mockTeamManager as unknown as TeamManager,+ mockGroupRepository as unknown as GroupRepository+ )++ expect(result[0].groups).toEqual({+ company: {+ index: 0,+ key: 'acme',+ type: 'company',+ properties: { name: 'Acme Inc' },+ },+ })+ expect(result[0].groups?.project).toBeUndefined()+ })++ it('sets empty groups object when team has group_analytics but event has no $groups', async () => {+ mockTeamManager.hasAvailableFeature.mockResolvedValue(true)+ mockGroupTypeManager.fetchGroupTypesForProjects.mockResolvedValue({+ '1': { company: 0 as GroupTypeIndex },+ } as GroupTypesByProjectId)++ const events = [makeEvent(1)]++ const result = await addGroupPropertiesToPostIngestionEventsBatch(+ events,+ mockGroupTypeManager as unknown as GroupTypeManager,+ mockTeamManager as unknown as TeamManager,+ mockGroupRepository as unknown as GroupRepository+ )++ expect(result[0].groups).toEqual({})+ expect(mockGroupRepository.fetchGroupsByKeys).not.toHaveBeenCalled()+ })++ it('handles events with no group type mappings for their project', async () => {+ mockTeamManager.hasAvailableFeature.mockResolvedValue(true)+ mockGroupTypeManager.fetchGroupTypesForProjects.mockResolvedValue({})++ const events = [makeEventWithGroups(1, { company: 'acme' })]++ const result = await addGroupPropertiesToPostIngestionEventsBatch(+ events,+ mockGroupTypeManager as unknown as GroupTypeManager,+ mockTeamManager as unknown as TeamManager,+ mockGroupRepository as unknown as GroupRepository+ )++ expect(result[0].groups).toEqual({})+ expect(mockGroupRepository.fetchGroupsByKeys).not.toHaveBeenCalled()+ })++ it('handles batch with different teams and different groups', async () => {+ mockTeamManager.hasAvailableFeature.mockResolvedValue(true)+ mockGroupTypeManager.fetchGroupTypesForProjects.mockResolvedValue({+ '1': { company: 0 as GroupTypeIndex },+ '2': { organization: 0 as GroupTypeIndex },+ } as GroupTypesByProjectId)+ mockGroupRepository.fetchGroupsByKeys.mockResolvedValue([+ {+ team_id: 1 as TeamId,+ group_type_index: 0 as GroupTypeIndex,+ group_key: 'acme',+ group_properties: { name: 'Acme' },+ },+ {+ team_id: 2 as TeamId,+ group_type_index: 0 as GroupTypeIndex,+ group_key: 'globex',+ group_properties: { name: 'Globex' },+ },+ ])++ const events = [+ makeEventWithGroups(1, { company: 'acme' }),+ makeEventWithGroups(2, { organization: 'globex' }, { projectId: 2 as ProjectId }),+ ]++ const result = await addGroupPropertiesToPostIngestionEventsBatch(+ events,+ mockGroupTypeManager as unknown as GroupTypeManager,+ mockTeamManager as unknown as TeamManager,+ mockGroupRepository as unknown as GroupRepository+ )++ expect(result[0].groups?.company?.properties).toEqual({ name: 'Acme' })+ expect(result[1].groups?.organization?.properties).toEqual({ name: 'Globex' })++ expect(mockGroupRepository.fetchGroupsByKeys).toHaveBeenCalledWith([1, 2], [0, 0], ['acme', 'globex'])+ })++ it('does not deduplicate when same group type index has different keys', async () => {+ mockTeamManager.hasAvailableFeature.mockResolvedValue(true)+ mockGroupTypeManager.fetchGroupTypesForProjects.mockResolvedValue({+ '1': { company: 0 as GroupTypeIndex },+ } as GroupTypesByProjectId)+ mockGroupRepository.fetchGroupsByKeys.mockResolvedValue([+ {+ team_id: 1 as TeamId,+ group_type_index: 0 as GroupTypeIndex,+ group_key: 'acme',+ group_properties: { name: 'Acme' },+ },+ {+ team_id: 1 as TeamId,+ group_type_index: 0 as GroupTypeIndex,+ group_key: 'globex',+ group_properties: { name: 'Globex' },+ },+ ])++ const events = [makeEventWithGroups(1, { company: 'acme' }), makeEventWithGroups(1, { company: 'globex' })]++ const result = await addGroupPropertiesToPostIngestionEventsBatch(+ events,+ mockGroupTypeManager as unknown as GroupTypeManager,+ mockTeamManager as unknown as TeamManager,+ mockGroupRepository as unknown as GroupRepository+ )++ expect(mockGroupRepository.fetchGroupsByKeys).toHaveBeenCalledWith([1, 1], [0, 0], ['acme', 'globex'])+ expect(result[0].groups?.company?.properties).toEqual({ name: 'Acme' })+ expect(result[1].groups?.company?.properties).toEqual({ name: 'Globex' })+ })++ it('treats same group key under different teams as separate lookups', async () => {+ mockTeamManager.hasAvailableFeature.mockResolvedValue(true)+ mockGroupTypeManager.fetchGroupTypesForProjects.mockResolvedValue({+ '1': { company: 0 as GroupTypeIndex },+ '2': { company: 0 as GroupTypeIndex },+ } as GroupTypesByProjectId)+ mockGroupRepository.fetchGroupsByKeys.mockResolvedValue([+ {+ team_id: 1 as TeamId,+ group_type_index: 0 as GroupTypeIndex,+ group_key: 'acme',+ group_properties: { name: 'Acme Team 1' },+ },+ {+ team_id: 2 as TeamId,+ group_type_index: 0 as GroupTypeIndex,+ group_key: 'acme',+ group_properties: { name: 'Acme Team 2' },+ },+ ])++ const events = [+ makeEventWithGroups(1, { company: 'acme' }),+ makeEventWithGroups(2, { company: 'acme' }, { projectId: 2 as ProjectId }),+ ]++ const result = await addGroupPropertiesToPostIngestionEventsBatch(+ events,+ mockGroupTypeManager as unknown as GroupTypeManager,+ mockTeamManager as unknown as TeamManager,+ mockGroupRepository as unknown as GroupRepository+ )++ expect(mockGroupRepository.fetchGroupsByKeys).toHaveBeenCalledWith([1, 2], [0, 0], ['acme', 'acme'])+ expect(result[0].groups?.company?.properties).toEqual({ name: 'Acme Team 1' })+ expect(result[1].groups?.company?.properties).toEqual({ name: 'Acme Team 2' })+ })++ it('handles $groups set to empty object', async () => {+ mockTeamManager.hasAvailableFeature.mockResolvedValue(true)+ mockGroupTypeManager.fetchGroupTypesForProjects.mockResolvedValue({+ '1': { company: 0 as GroupTypeIndex },+ } as GroupTypesByProjectId)++ const events = [makeEventWithGroups(1, {})]++ const result = await addGroupPropertiesToPostIngestionEventsBatch(+ events,+ mockGroupTypeManager as unknown as GroupTypeManager,+ mockTeamManager as unknown as TeamManager,+ mockGroupRepository as unknown as GroupRepository+ )++ expect(result[0].groups).toEqual({})+ expect(mockGroupRepository.fetchGroupsByKeys).not.toHaveBeenCalled()+ })++ it('preserves event order and non-group fields', async () => {+ mockTeamManager.hasAvailableFeature.mockResolvedValue(true)+ mockGroupTypeManager.fetchGroupTypesForProjects.mockResolvedValue({+ '1': { company: 0 as GroupTypeIndex },+ } as GroupTypesByProjectId)+ mockGroupRepository.fetchGroupsByKeys.mockResolvedValue([])++ const events = [+ makeEventWithGroups(1, { company: 'a' }, { eventUuid: 'first', distinctId: 'user-a' }),+ makeEventWithGroups(1, { company: 'b' }, { eventUuid: 'second', distinctId: 'user-b' }),+ makeEventWithGroups(1, { company: 'c' }, { eventUuid: 'third', distinctId: 'user-c' }),+ ]++ const result = await addGroupPropertiesToPostIngestionEventsBatch(+ events,+ mockGroupTypeManager as unknown as GroupTypeManager,+ mockTeamManager as unknown as TeamManager,+ mockGroupRepository as unknown as GroupRepository+ )++ expect(result.map((e) => e.eventUuid)).toEqual(['first', 'second', 'third'])+ expect(result.map((e) => e.distinctId)).toEqual(['user-a', 'user-b', 'user-c'])+ })+})diff --git a/nodejs/src/cdp/legacy-webhooks/utils.ts b/nodejs/src/cdp/legacy-webhooks/utils.tsindex 02a6ce54f2f9..f9786fc735f6 100644--- a/nodejs/src/cdp/legacy-webhooks/utils.ts+++ b/nodejs/src/cdp/legacy-webhooks/utils.ts@@ -1,4 +1,4 @@-import { GroupTypeIndex, GroupTypeToColumnIndex, PostIngestionEvent, TeamId } from '~/types'+import { GroupTypeIndex, GroupTypeToColumnIndex, PostIngestionEvent, ProjectId, TeamId } from '~/types'import { TeamManager } from '~/utils/team-manager'import { GroupTypeManager } from '~/worker/ingestion/group-type-manager'import { GroupRepository } from '~/worker/ingestion/groups/repositories/group-repository.interface'@@ -50,3 +50,116 @@ export async function addGroupPropertiesToPostIngestionEvent(groups,}}++type GroupLookupKey = `${number}:${number}:${string}`++function makeGroupLookupKey(teamId: number, groupTypeIndex: number, groupKey: string): GroupLookupKey {+ return `${teamId}:${groupTypeIndex}:${groupKey}`+}++export async function addGroupPropertiesToPostIngestionEventsBatch(+ events: PostIngestionEvent[],+ groupTypeManager: GroupTypeManager,+ teamManager: TeamManager,+ groupRepository: GroupRepository+): Promise<PostIngestionEvent[]> {+ if (events.length === 0) {+ return []+ }++ const uniqueTeamIds = [...new Set(events.map((e) => e.teamId))]+ const teamHasGroupAnalytics = new Map<number, boolean>()+ await Promise.all(+ uniqueTeamIds.map(async (teamId) => {+ const has = await teamManager.hasAvailableFeature(teamId, 'group_analytics')+ teamHasGroupAnalytics.set(teamId, has)+ })+ )++ const projectIdsNeedingGroups = new Set<ProjectId>()+ for (const event of events) {+ if (teamHasGroupAnalytics.get(event.teamId)) {+ projectIdsNeedingGroups.add(event.projectId)+ }+ }++ if (projectIdsNeedingGroups.size === 0) {+ return events+ }++ const groupTypesByProject = await groupTypeManager.fetchGroupTypesForProjects(projectIdsNeedingGroups)++ const allTeamIds: TeamId[] = []+ const allGroupTypeIndexes: GroupTypeIndex[] = []+ const allGroupKeys: string[] = []+ const seenKeys = new Set<GroupLookupKey>()++ type EventGroupNeed = { groupType: string; columnIndex: GroupTypeIndex; groupKey: string }+ const eventGroupNeeds: (EventGroupNeed[] | null)[] = []++ for (const event of events) {+ if (!teamHasGroupAnalytics.get(event.teamId)) {+ eventGroupNeeds.push(null)+ continue+ }++ const groupTypes = groupTypesByProject[event.projectId]+ if (!groupTypes || Object.keys(groupTypes).length === 0) {+ eventGroupNeeds.push([])+ continue+ }++ const needs: EventGroupNeed[] = []+ for (const [groupType, columnIndex] of Object.entries(groupTypes)) {+ const groupKey = (event.properties['$groups'] || {})[groupType]+ if (!groupKey) {+ continue+ }++ needs.push({ groupType, columnIndex: columnIndex as GroupTypeIndex, groupKey })++ const lookupKey = makeGroupLookupKey(event.teamId, columnIndex, groupKey)+ if (!seenKeys.has(lookupKey)) {+ seenKeys.add(lookupKey)+ allTeamIds.push(event.teamId as TeamId)+ allGroupTypeIndexes.push(columnIndex as GroupTypeIndex)+ allGroupKeys.push(groupKey)+ }+ }++ eventGroupNeeds.push(needs)+ }++ const groupResults =+ allTeamIds.length > 0+ ? await groupRepository.fetchGroupsByKeys(allTeamIds, allGroupTypeIndexes, allGroupKeys)+ : []++ const groupPropertiesMap = new Map<GroupLookupKey, Record<string, any>>()+ for (const result of groupResults) {+ const key = makeGroupLookupKey(result.team_id, result.group_type_index, result.group_key)+ groupPropertiesMap.set(key, result.group_properties)+ }++ return events.map((event, i) => {+ const needs = eventGroupNeeds[i]++ if (needs === null) {+ return event+ }++ const groups: PostIngestionEvent['groups'] = {}+ for (const { groupType, columnIndex, groupKey } of needs) {+ const key = makeGroupLookupKey(event.teamId, columnIndex, groupKey)+ const properties = groupPropertiesMap.get(key) ?? {}+ groups[groupType] = {+ index: columnIndex,+ key: groupKey,+ type: groupType,+ properties,+ }+ }++ return { ...event, groups }+ })+}