Skip to content

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

chore(legacy-webhook-service): remove unused group enrichment (#60972)

Daniel Marchuk75c9b4ec3338
diff --git a/nodejs/src/cdp/consumers/cdp-legacy-event.consumer.test.ts b/nodejs/src/cdp/consumers/cdp-legacy-event.consumer.test.ts
index 90ab7602ba7a..6d31d64d2ab3 100644
--- a/nodejs/src/cdp/consumers/cdp-legacy-event.consumer.test.ts
+++ b/nodejs/src/cdp/consumers/cdp-legacy-event.consumer.test.ts
@@ -2,7 +2,7 @@ import { mockFetch } from '~/tests/helpers/mocks/request.mock'
import { DateTime } from 'luxon'
-import { createCdpLegacyEventsConsumerDeps } from '~/tests/helpers/cdp'
+import { createCdpConsumerDeps } from '~/tests/helpers/cdp'
import { forSnapshot } from '~/tests/helpers/snapshots'
import { getFirstTeam, resetTestDatabase } from '~/tests/helpers/sql'
@@ -31,7 +31,7 @@ describe('CdpLegacyEventsConsumer', () => {
beforeEach(async () => {
hub = await createHub()
await resetTestDatabase()
- consumer = new CdpLegacyEventsConsumer(hub, createCdpLegacyEventsConsumerDeps(hub))
+ consumer = new CdpLegacyEventsConsumer(hub, createCdpConsumerDeps(hub))
legacyPluginExecutor = new LegacyPluginExecutorService(hub.postgres, hub.geoipService)
team = await getFirstTeam(hub.postgres)
diff --git a/nodejs/src/cdp/consumers/cdp-legacy-event.consumer.ts b/nodejs/src/cdp/consumers/cdp-legacy-event.consumer.ts
index b8ca175affde..ba65d63a7c0b 100644
--- a/nodejs/src/cdp/consumers/cdp-legacy-event.consumer.ts
+++ b/nodejs/src/cdp/consumers/cdp-legacy-event.consumer.ts
@@ -17,7 +17,6 @@ import { parseJSON } from '../../utils/json-parse'
import { LazyLoader } from '../../utils/lazy-loader'
import { logger } from '../../utils/logger'
import { PromiseScheduler } from '../../utils/promise-scheduler'
-import { GroupTypeManager } from '../../worker/ingestion/group-type-manager'
import { LegacyWebhookService } from '../legacy-webhooks/legacy-webhook-service'
import { LegacyPluginExecutorService } from '../services/legacy-plugin-executor.service'
import type {
@@ -59,10 +58,6 @@ const legacyPluginExecutionResultCounter = new Counter({
export type CdpLegacyEventsConsumerConfig = CdpConsumerBaseConfig &
Pick<PluginsServerConfig, 'CDP_LEGACY_EVENT_CONSUMER_TOPIC' | 'CDP_LEGACY_EVENT_CONSUMER_GROUP_ID' | 'SITE_URL'>
-export interface CdpLegacyEventsConsumerDeps extends CdpConsumerBaseDeps {
- groupTypeManager: GroupTypeManager
-}
-
/**
* This is a temporary consumer that hooks into the existing onevent consumer group
* It currently just runs the same logic as the old one but with noderdkafka as the consumer tech which should improve things
@@ -79,7 +74,7 @@ export class CdpLegacyEventsConsumer extends CdpConsumerBase<CdpLegacyEventsCons
constructor(
config: CdpLegacyEventsConsumerConfig,
- protected override deps: CdpLegacyEventsConsumerDeps
+ protected override deps: CdpConsumerBaseDeps
) {
super(config, deps)
@@ -89,13 +84,7 @@ export class CdpLegacyEventsConsumer extends CdpConsumerBase<CdpLegacyEventsCons
})
this.legacyPluginExecutor = new LegacyPluginExecutorService(deps.postgres, deps.geoipService)
- this.legacyWebhookService = new LegacyWebhookService(
- deps.postgres,
- deps.teamManager,
- deps.groupTypeManager,
- deps.groupRepository,
- deps.pubSub
- )
+ this.legacyWebhookService = new LegacyWebhookService(deps.postgres, deps.teamManager, deps.pubSub)
this.pluginConfigsLoader = new LazyLoader({
name: 'plugin_config_hog_functions',
diff --git a/nodejs/src/cdp/legacy-webhooks/legacy-webhook-service.test.ts b/nodejs/src/cdp/legacy-webhooks/legacy-webhook-service.test.ts
index 62dffb71480a..0b163916cda5 100644
--- a/nodejs/src/cdp/legacy-webhooks/legacy-webhook-service.test.ts
+++ b/nodejs/src/cdp/legacy-webhooks/legacy-webhook-service.test.ts
@@ -3,25 +3,14 @@ import { mockFetch } from '../../../tests/helpers/mocks/request.mock'
import { Message } from 'node-rdkafka'
import { createOrganization, createTeam, getFirstTeam, getTeam, resetTestDatabase } from '../../../tests/helpers/sql'
-import { PersonHogClient } from '../../ingestion/personhog/client'
-import { PersonHogGroupRepository } from '../../ingestion/personhog/personhog-group-repository'
-import { Action, Hook, Hub, ISOTimestamp, PostIngestionEvent, ProjectId, Team } from '../../types'
+import { Action, ClickHouseTimestamp, Hook, Hub, ISOTimestamp, PostIngestionEvent, ProjectId, Team } from '../../types'
import { closeHub, createHub } from '../../utils/db/hub'
import { PostgresUse } from '../../utils/db/postgres'
+import { parseJSON } from '../../utils/json-parse'
import { FetchResponse } from '../../utils/request'
import { createIncomingEvent, createKafkaMessage } from '../_tests/fixtures'
import { LegacyWebhookService } from './legacy-webhook-service'
-type MockPersonHogClient = {
- groups: jest.Mocked<
- Pick<
- PersonHogClient['groups'],
- 'fetchGroup' | 'fetchGroupsByKeys' | 'fetchGroupTypesByTeamIds' | 'fetchGroupTypesByProjectIds'
- >
- >
- persons: jest.Mocked<Pick<PersonHogClient['persons'], 'fetchPersonsByDistinctIds' | 'fetchPersonsByPersonIds'>>
-}
-
jest.setTimeout(10000)
describe('LegacyWebhookService', () => {
@@ -72,13 +61,7 @@ describe('LegacyWebhookService', () => {
const team2Id = await createTeam(hub.postgres, otherOrganizationId)
team2 = (await getTeam(hub.postgres, team2Id))!
- service = new LegacyWebhookService(
- hub.postgres,
- hub.teamManager,
- hub.groupTypeManager,
- hub.groupRepository,
- hub.pubSub
- )
+ service = new LegacyWebhookService(hub.postgres, hub.teamManager, hub.pubSub)
await service.start()
mockFetch.mockResolvedValue({
@@ -167,22 +150,13 @@ describe('LegacyWebhookService', () => {
expect(service.processEvent).toHaveBeenCalledTimes(1)
})
- it('should enrich events with group properties when available', async () => {
+ it('should not query the group repository when processing events with $groups', async () => {
service['actionMatcher'].hasWebhooks = jest.fn().mockReturnValue(true)
+ // Both zapier and group_analytics enabled — group_analytics used to trigger enrichment
hub.teamManager.hasAvailableFeature = jest.fn().mockResolvedValue(true)
- 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')
+ const fetchGroupsByKeysSpy = jest.spyOn(hub.groupRepository, 'fetchGroupsByKeys')
+ const fetchGroupSpy = jest.spyOn(hub.groupRepository, 'fetchGroup')
+ service.processEvent = jest.fn()
const messages: Message[] = [
createKafkaMessage(
@@ -196,72 +170,63 @@ describe('LegacyWebhookService', () => {
const result = await service.processBatch(messages)
await result.backgroundTask
- expect(processEventSpy).toHaveBeenCalledTimes(1)
- const processedEvent = processEventSpy.mock.calls[0][0]
- expect(processedEvent.groups).toBeDefined()
- expect(processedEvent.groups?.project).toEqual({
- index: 0,
- key: 'test-project-id',
- type: 'project',
- properties: { name: 'Test Project' },
- })
+ expect(fetchGroupsByKeysSpy).not.toHaveBeenCalled()
+ expect(fetchGroupSpy).not.toHaveBeenCalled()
})
- it('should process events without group properties when batch enrichment fails', async () => {
+ it('posts an identical payload regardless of group_analytics and never adds a groups key', 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 hook = createMockHook(team.id)
+ const action = createMockAction(team.id, { hooks: [hook] })
+ service['actionMatcher'].match = jest.fn().mockReturnValue([action])
- const processEventSpy = jest.spyOn(service, 'processEvent').mockResolvedValue(undefined)
+ const fetchGroupsByKeysSpy = jest.spyOn(hub.groupRepository, 'fetchGroupsByKeys')
+ const fetchGroupSpy = jest.spyOn(hub.groupRepository, 'fetchGroup')
- const messages: Message[] = [
+ // Pin volatile fields so the two events are byte-for-byte identical
+ const fixedTimestamp = '2024-01-01 00:00:00.000' as ClickHouseTimestamp
+ const makeMessage = (): Message =>
createKafkaMessage(
createIncomingEvent(team.id, {
+ uuid: 'fixed-event-uuid',
event: '$pageview',
- properties: JSON.stringify({ $groups: { project: 'test-project-id' } }),
+ properties: JSON.stringify({ $groups: { project: 'test-project-id' }, foo: 'bar' }),
+ timestamp: fixedTimestamp,
+ created_at: fixedTimestamp,
+ person_created_at: fixedTimestamp,
})
- ),
- ]
-
- 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)
+ // group_analytics ON (and zapier ON)
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'))
+ let result = await service.processBatch([makeMessage()])
+ await result.backgroundTask
+ const bodyWithGroupAnalytics = parseJSON(mockFetch.mock.calls[0][1].body)
- const processEventSpy = jest.spyOn(service, 'processEvent').mockResolvedValue(undefined)
+ mockFetch.mockClear()
- 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)
+ // group_analytics OFF (zapier still ON) — the non-group case
+ hub.teamManager.hasAvailableFeature = jest
+ .fn()
+ .mockImplementation((_teamId, feature) => Promise.resolve(feature === 'zapier'))
+ result = await service.processBatch([makeMessage()])
await result.backgroundTask
-
- expect(processEventSpy).toHaveBeenCalledTimes(2)
- expect(processEventSpy.mock.calls[0][0].groups).toBeUndefined()
- expect(processEventSpy.mock.calls[1][0].groups).toBeUndefined()
+ const bodyWithoutGroupAnalytics = parseJSON(mockFetch.mock.calls[0][1].body)
+
+ // The payload is byte-for-byte identical whether or not group_analytics is enabled
+ expect(bodyWithGroupAnalytics).toEqual(bodyWithoutGroupAnalytics)
+ // ...and crucially never carries a top-level groups key
+ expect(bodyWithGroupAnalytics.data).not.toHaveProperty('groups')
+ // ...while the fields that consumers actually read remain intact
+ expect(bodyWithGroupAnalytics.data.properties).toMatchObject({
+ $groups: { project: 'test-project-id' },
+ foo: 'bar',
+ })
+ expect(bodyWithGroupAnalytics.data).toHaveProperty('person')
+ expect(bodyWithGroupAnalytics.data).toHaveProperty('elementsList')
+ // ...and we never reach into the group repository
+ expect(fetchGroupsByKeysSpy).not.toHaveBeenCalled()
+ expect(fetchGroupSpy).not.toHaveBeenCalled()
})
})
@@ -453,79 +418,4 @@ describe('LegacyWebhookService', () => {
await expect(service['postWebhook'](event, team, hook)).rejects.toThrow('Network error')
})
})
-
- describe('PersonHogGroupRepository compatibility', () => {
- it('should enrich events with group properties when groupRepository is wrapped with PersonHogGroupRepository', async () => {
- const mockGrpcClient: MockPersonHogClient = {
- groups: {
- 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(),
- },
- persons: {
- fetchPersonsByDistinctIds: jest.fn(),
- fetchPersonsByPersonIds: jest.fn(),
- },
- }
-
- const personhogRepo = new PersonHogGroupRepository(
- hub.groupRepository,
- mockGrpcClient as unknown as PersonHogClient,
- 100,
- new Set(),
- 'test'
- )
-
- const personhogService = new LegacyWebhookService(
- hub.postgres,
- hub.teamManager,
- hub.groupTypeManager,
- personhogRepo,
- hub.pubSub
- )
- await personhogService.start()
-
- personhogService['actionMatcher'].hasWebhooks = jest.fn().mockReturnValue(true)
- hub.teamManager.hasAvailableFeature = jest.fn().mockResolvedValue(true)
- hub.groupTypeManager.fetchGroupTypesForProjects = jest.fn().mockResolvedValue({
- [team.id]: { project: 0 },
- })
-
- const processEventSpy = jest.spyOn(personhogService, 'processEvent')
-
- const messages: Message[] = [
- createKafkaMessage(
- createIncomingEvent(team.id, {
- event: '$pageview',
- properties: JSON.stringify({ $groups: { project: 'test-project-id' } }),
- })
- ),
- ]
-
- const result = await personhogService.processBatch(messages)
- await result.backgroundTask
-
- expect(processEventSpy).toHaveBeenCalledTimes(1)
- const processedEvent = processEventSpy.mock.calls[0][0]
- expect(processedEvent.groups).toBeDefined()
- expect(processedEvent.groups?.project).toEqual({
- index: 0,
- key: 'test-project-id',
- type: 'project',
- properties: { name: 'Test Project' },
- })
-
- 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.ts
index e37078fff6cd..c2b1681b451a 100644
--- a/nodejs/src/cdp/legacy-webhooks/legacy-webhook-service.ts
+++ b/nodejs/src/cdp/legacy-webhooks/legacy-webhook-service.ts
@@ -9,12 +9,9 @@ import { parseJSON } from '../../utils/json-parse'
import { logger } from '../../utils/logger'
import { PubSub } from '../../utils/pubsub'
import { TeamManager } from '../../utils/team-manager'
-import { GroupTypeManager } from '../../worker/ingestion/group-type-manager'
-import { GroupRepository } from '../../worker/ingestion/groups/repositories/group-repository.interface'
import { counterParseError } from '../consumers/metrics'
import { ActionManager } from '../legacy-webhooks/action-manager'
import { ActionMatcher } from '../legacy-webhooks/action-matcher'
-import { addGroupPropertiesToPostIngestionEventsBatch } from '../legacy-webhooks/utils'
import { cdpTrackedFetch } from '../services/hog-executor.service'
export class LegacyWebhookService {
@@ -24,8 +21,6 @@ export class LegacyWebhookService {
constructor(
private postgres: PostgresRouter,
private teamManager: TeamManager,
- private groupTypeManager: GroupTypeManager,
- private groupRepository: GroupRepository,
pubSub: PubSub
) {
this.actionManager = new ActionManager(postgres, pubSub)
@@ -99,7 +94,7 @@ export class LegacyWebhookService {
}
public async processBatch(messages: Message[]): Promise<{ backgroundTask: Promise<any> }> {
- const eventsWithoutGroups: PostIngestionEvent[] = []
+ const events: PostIngestionEvent[] = []
await Promise.all(
messages.map(async (message) => {
@@ -113,7 +108,7 @@ export class LegacyWebhookService {
return
}
- eventsWithoutGroups.push(convertToPostIngestionEvent(clickHouseEvent))
+ events.push(convertToPostIngestionEvent(clickHouseEvent))
} catch (e) {
logger.error('Error parsing message', e)
counterParseError.labels({ error: e.message }).inc()
@@ -121,19 +116,6 @@ 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.ts
deleted file mode 100644
index 28e91128b3ab..000000000000
--- a/nodejs/src/cdp/legacy-webhooks/utils.test.ts
+++ /dev/null
@@ -1,524 +0,0 @@
-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'],
- 'cdp/legacy-webhooks-group-enrichment'
- )
-
- 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'],
- 'cdp/legacy-webhooks-group-enrichment'
- )
- })
-
- 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'],
- 'cdp/legacy-webhooks-group-enrichment'
- )
- 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'],
- 'cdp/legacy-webhooks-group-enrichment'
- )
- 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.ts
deleted file mode 100644
index 87f791e9a303..000000000000
--- a/nodejs/src/cdp/legacy-webhooks/utils.ts
+++ /dev/null
@@ -1,170 +0,0 @@
-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'
-
-export async function addGroupPropertiesToPostIngestionEvent(
- event: PostIngestionEvent,
- groupTypeManager: GroupTypeManager,
- teamManager: TeamManager,
- groupRepository: GroupRepository
-): Promise<PostIngestionEvent> {
- let groupTypes: GroupTypeToColumnIndex | null = null
- if (await teamManager.hasAvailableFeature(event.teamId, 'group_analytics')) {
- // If the organization has group analytics enabled then we enrich the event with group data
- groupTypes = await groupTypeManager.fetchGroupTypes(event.projectId)
- }
-
- let groups: PostIngestionEvent['groups'] = undefined
- if (groupTypes) {
- groups = {}
-
- for (const [groupType, columnIndex] of Object.entries(groupTypes)) {
- const groupKey = (event.properties[`$groups`] || {})[groupType]
- if (!groupKey) {
- continue
- }
-
- const group = await groupRepository.fetchGroup(
- event.teamId as TeamId,
- columnIndex as GroupTypeIndex,
- groupKey,
- { useReadReplica: true, callerTag: 'cdp/legacy-webhooks-group-enrichment' }
- )
-
- const groupProperties = group ? group.group_properties : {}
-
- if (groupKey && groupProperties) {
- groups[groupType] = {
- index: columnIndex,
- key: groupKey,
- type: groupType,
- properties: groupProperties,
- }
- }
- }
- }
-
- return {
- ...event,
- 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,
- 'cdp/legacy-webhooks-group-enrichment'
- )
- : []
-
- 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 }
- })
-}
diff --git a/nodejs/src/server.ts b/nodejs/src/server.ts
index f00bf795e980..e21e5c46002a 100644
--- a/nodejs/src/server.ts
+++ b/nodejs/src/server.ts
@@ -13,7 +13,7 @@ import { CdpCyclotronWorker } from './cdp/consumers/cdp-cyclotron-worker.consume
import { CdpDatawarehouseEventsConsumer } from './cdp/consumers/cdp-data-warehouse-events.consumer'
import { CdpEventsConsumer } from './cdp/consumers/cdp-events.consumer'
import { CdpInternalEventsConsumer } from './cdp/consumers/cdp-internal-event.consumer'
-import { CdpLegacyEventsConsumer, CdpLegacyEventsConsumerDeps } from './cdp/consumers/cdp-legacy-event.consumer'
+import { CdpLegacyEventsConsumer } from './cdp/consumers/cdp-legacy-event.consumer'
import { CdpPersonUpdatesConsumer } from './cdp/consumers/cdp-person-updates-consumer'
import { CdpPrecalculatedFiltersConsumer } from './cdp/consumers/cdp-precalculated-filters.consumer'
import { CdpRerunWorkerConsumer } from './cdp/consumers/cdp-rerun-worker.consumer'
@@ -39,7 +39,6 @@ import { GeoIPService } from './utils/geoip'
import { logger } from './utils/logger'
import { PubSub } from './utils/pubsub'
import { TeamManager } from './utils/team-manager'
-import { GroupTypeManager } from './worker/ingestion/group-type-manager'
import { GroupRepository } from './worker/ingestion/groups/repositories/group-repository.interface'
import { PostgresGroupRepository } from './worker/ingestion/groups/repositories/postgres-group-repository'
import { PersonRepository } from './worker/ingestion/persons/repositories/person-repository'
@@ -184,12 +183,8 @@ export class PluginServer implements NodeServer {
}
if (capabilities.cdpLegacyOnEvent) {
- const legacyDeps: CdpLegacyEventsConsumerDeps = {
- ...cdpDeps!,
- groupTypeManager: new GroupTypeManager(cdpServices!.groupRepository, teamManager),
- }
serviceLoaders.push(async () => {
- const consumer = new CdpLegacyEventsConsumer(this.config, legacyDeps)
+ const consumer = new CdpLegacyEventsConsumer(this.config, cdpDeps!)
await consumer.start()
return consumer.service
})
diff --git a/nodejs/tests/helpers/cdp.ts b/nodejs/tests/helpers/cdp.ts
index 93b47dfd9402..b4f810648db7 100644
--- a/nodejs/tests/helpers/cdp.ts
+++ b/nodejs/tests/helpers/cdp.ts
@@ -1,7 +1,6 @@
import { mockProducer } from './mocks/producer.mock'
import { CdpConsumerBaseDeps } from '../../src/cdp/consumers/cdp-base.consumer'
-import { CdpLegacyEventsConsumerDeps } from '../../src/cdp/consumers/cdp-legacy-event.consumer'
import {
CdpProducerName,
WAREHOUSE_PRODUCER,
@@ -46,13 +45,3 @@ export function createCdpConsumerDeps(hub: Hub, kafkaProducer?: KafkaProducerWra
quotaLimiting: hub.quotaLimiting,
}
}
-
-export function createCdpLegacyEventsConsumerDeps(
- hub: Hub,
- kafkaProducer?: KafkaProducerWrapper
-): CdpLegacyEventsConsumerDeps {
- return {
- ...createCdpConsumerDeps(hub, kafkaProducer),
- groupTypeManager: hub.groupTypeManager,
- }
-}