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(personhog): create read only personhog group repository (#61258)

Zach Brown6317291921ed
diff --git a/nodejs/src/cdp/consumers/cdp-base.consumer.ts b/nodejs/src/cdp/consumers/cdp-base.consumer.ts
index e8b1a4ecb27b..3fc5834561d1 100644
--- a/nodejs/src/cdp/consumers/cdp-base.consumer.ts
+++ b/nodejs/src/cdp/consumers/cdp-base.consumer.ts
@@ -5,7 +5,7 @@ import type { CommonConfig } from '../../common/config'
import { HealthCheckResult, PluginServerService, TeamId } from '../../types'
import { GeoIPService } from '../../utils/geoip'
import { logger } from '../../utils/logger'
-import { GroupRepository } from '../../worker/ingestion/groups/repositories/group-repository.interface'
+import { GroupReadRepository } from '../../worker/ingestion/groups/repositories/group-repository.interface'
import { PersonReadRepository } from '../../worker/ingestion/persons/repositories/person-repository'
import {
CdpCoreServicesConfig,
@@ -41,7 +41,7 @@ export type CdpConsumerBaseConfig = CdpCoreServicesConfig &
export interface CdpConsumerBaseDeps extends CdpCoreServicesDeps {
personRepository: PersonReadRepository
geoipService: GeoIPService
- groupRepository: GroupRepository
+ groupRepository: GroupReadRepository
quotaLimiting: QuotaLimiting
}
diff --git a/nodejs/src/cdp/consumers/cdp-events-consumer.test.ts b/nodejs/src/cdp/consumers/cdp-events-consumer.test.ts
index 5222a3651c94..6f425df9a85c 100644
--- a/nodejs/src/cdp/consumers/cdp-events-consumer.test.ts
+++ b/nodejs/src/cdp/consumers/cdp-events-consumer.test.ts
@@ -1,8 +1,6 @@
import { createMockJobQueue } from '../../../tests/helpers/mocks/job-queue.mock'
import { mockProducerObserver } from '../../../tests/helpers/mocks/producer.mock'
-import { DateTime } from 'luxon'
-
import { HogFlow } from '~/schema/hogflow'
import { createCdpConsumerDeps } from '../../../tests/helpers/cdp'
@@ -16,6 +14,7 @@ import {
} from '../../../tests/helpers/sql'
import { Hub, Team } from '../../types'
import { closeHub, createHub } from '../../utils/db/hub'
+import { GroupReadRepository } from '../../worker/ingestion/groups/repositories/group-repository.interface'
import { FixtureHogFlowBuilder } from '../_tests/builders/hogflow.builder'
import { HOG_EXAMPLES, HOG_FILTERS_EXAMPLES, HOG_INPUTS_EXAMPLES } from '../_tests/examples'
import {
@@ -25,6 +24,7 @@ import {
createKafkaMessage,
} from '../_tests/fixtures'
import { insertHogFlow as _insertHogFlow } from '../_tests/fixtures-hogflows'
+import { GroupsManagerService } from '../services/managers/groups-manager.service'
import { HogWatcherState } from '../services/monitoring/hog-watcher.service'
import { HogFunctionInvocationGlobals, HogFunctionType } from '../types'
import { CdpEventsConsumer } from './cdp-events.consumer'
@@ -988,31 +988,36 @@ describe('hog flow processing', () => {
{ key: 'data_pipelines', name: 'Data Pipelines' },
{ key: 'group_analytics', name: 'Group Analytics' },
])
- // Clear cached team data so the new features are picked up
hub.teamManager['lazyLoader'].clear()
- processor['groupsManager'].clear()
- await hub.groupRepository.insertGroupType(team.id, team.id as any, 'company', 0)
- await hub.groupRepository.insertGroupType(team.id, team.id as any, 'project', 1)
+ const mockGroupRepo: GroupReadRepository = {
+ fetchGroupsByKeys: jest.fn().mockResolvedValue([
+ {
+ team_id: team.id,
+ group_type_index: 0,
+ group_key: 'acme-inc',
+ group_properties: { name: 'Acme Inc', industry: 'Tech' },
+ },
+ {
+ team_id: team.id,
+ group_type_index: 1,
+ group_key: 'project-alpha',
+ group_properties: { name: 'Project Alpha', status: 'active' },
+ },
+ ]),
+ fetchGroupTypesByTeamIds: jest.fn().mockImplementation((teamIds: number[]) => {
+ const result: Record<string, { group_type: string; group_type_index: number }[]> = {}
+ for (const id of teamIds) {
+ result[id.toString()] = [
+ { group_type: 'company', group_type_index: 0 },
+ { group_type: 'project', group_type_index: 1 },
+ ]
+ }
+ return Promise.resolve(result)
+ }),
+ }
- await hub.groupRepository.insertGroup(
- team.id,
- 0 as any,
- 'acme-inc',
- { name: 'Acme Inc', industry: 'Tech' },
- DateTime.now(),
- {},
- {}
- )
- await hub.groupRepository.insertGroup(
- team.id,
- 1 as any,
- 'project-alpha',
- { name: 'Project Alpha', status: 'active' },
- DateTime.now(),
- {},
- {}
- )
+ processor['groupsManager'] = new GroupsManagerService(hub.teamManager, mockGroupRepo)
}
beforeEach(() => {
diff --git a/nodejs/src/cdp/services/batch-export-hog-function.service.test.ts b/nodejs/src/cdp/services/batch-export-hog-function.service.test.ts
index 8223893a0cba..7f428e2a2750 100644
--- a/nodejs/src/cdp/services/batch-export-hog-function.service.test.ts
+++ b/nodejs/src/cdp/services/batch-export-hog-function.service.test.ts
@@ -3,7 +3,6 @@ import { mockProducerObserver } from '~/tests/helpers/mocks/producer.mock'
import { mockFetch } from '~/tests/helpers/mocks/request.mock'
import { Server } from 'http'
-import { DateTime } from 'luxon'
import supertest from 'supertest'
import express from 'ultimate-express'
@@ -18,22 +17,11 @@ import { Hub, Team } from '~/types'
import { closeHub, createHub } from '~/utils/db/hub'
import { UUIDT } from '~/utils/utils'
-import { PersonHogClient } from '../../ingestion/personhog/client'
-import { PersonHogGroupRepository } from '../../ingestion/personhog/personhog-group-repository'
import { GroupTypeIndex, TeamId } from '../../types'
import { parseJSON } from '../../utils/json-parse'
+import { GroupReadRepository } from '../../worker/ingestion/groups/repositories/group-repository.interface'
import { GroupsManagerService } from './managers/groups-manager.service'
-type MockPersonHogClient = {
- groups: jest.Mocked<
- Pick<
- PersonHogClient['groups'],
- 'fetchGroup' | 'fetchGroupsByKeys' | 'fetchGroupTypesByTeamIds' | 'fetchGroupTypesByProjectIds'
- >
- >
- persons: jest.Mocked<Pick<PersonHogClient['persons'], 'fetchPersonsByDistinctIds' | 'fetchPersonsByPersonIds'>>
-}
-
describe('BatchExportHogFunctionService', () => {
let hub: Hub
let team: Team
@@ -305,9 +293,14 @@ describe('BatchExportHogFunctionService', () => {
})
describe('groups enrichment', () => {
+ let originalGroupsManager: GroupsManagerService
+
beforeEach(() => {
- // Clear cached group data between tests
- api['batchExportHogFunctionService']['groupsManager'].clear()
+ originalGroupsManager = api['batchExportHogFunctionService']['groupsManager']
+ })
+
+ afterEach(() => {
+ api['batchExportHogFunctionService']['groupsManager'] = originalGroupsManager
})
const setupGroups = async () => {
@@ -315,19 +308,29 @@ describe('BatchExportHogFunctionService', () => {
{ key: 'data_pipelines', name: 'Data Pipelines' },
{ key: 'group_analytics', name: 'Group Analytics' },
])
- // Clear cached team data so the new features are picked up
hub.teamManager['lazyLoader'].clear()
- await hub.groupRepository.insertGroupType(team.id, team.id as any, 'company', 0)
+ const mockGroupRepo: GroupReadRepository = {
+ fetchGroupsByKeys: jest.fn().mockResolvedValue([
+ {
+ team_id: team.id as TeamId,
+ group_type_index: 0 as GroupTypeIndex,
+ group_key: 'acme-inc',
+ group_properties: { name: 'Acme Inc', industry: 'Tech' },
+ },
+ ]),
+ fetchGroupTypesByTeamIds: jest.fn().mockImplementation((teamIds: number[]) => {
+ const result: Record<string, { group_type: string; group_type_index: GroupTypeIndex }[]> = {}
+ for (const id of teamIds) {
+ result[id.toString()] = [{ group_type: 'company', group_type_index: 0 as GroupTypeIndex }]
+ }
+ return Promise.resolve(result)
+ }),
+ }
- await hub.groupRepository.insertGroup(
- team.id,
- 0 as any,
- 'acme-inc',
- { name: 'Acme Inc', industry: 'Tech' },
- DateTime.now(),
- {},
- {}
+ api['batchExportHogFunctionService']['groupsManager'] = new GroupsManagerService(
+ hub.teamManager,
+ mockGroupRepo
)
}
@@ -409,109 +412,4 @@ describe('BatchExportHogFunctionService', () => {
expect(fetchBody.groups).toEqual({})
})
})
-
- describe('groups enrichment via PersonHogGroupRepository', () => {
- let originalGroupsManager: GroupsManagerService
-
- const setupGroups = async () => {
- await updateOrganizationAvailableFeatures(hub.postgres, team.organization_id, [
- { key: 'data_pipelines', name: 'Data Pipelines' },
- { key: 'group_analytics', name: 'Group Analytics' },
- ])
- hub.teamManager['lazyLoader'].clear()
-
- await hub.groupRepository.insertGroupType(team.id, team.id as any, 'company', 0)
- await hub.groupRepository.insertGroup(
- team.id,
- 0 as any,
- 'acme-inc',
- { name: 'Acme Inc', industry: 'Tech' },
- DateTime.now(),
- {},
- {}
- )
- }
-
- beforeEach(() => {
- originalGroupsManager = api['batchExportHogFunctionService']['groupsManager']
- })
-
- afterEach(() => {
- api['batchExportHogFunctionService']['groupsManager'] = originalGroupsManager
- })
-
- it('enriches globals identically when routed through gRPC mock', async () => {
- await setupGroups()
-
- // Build a mock gRPC client that returns the same data postgres holds
- const mockGrpc: MockPersonHogClient = {
- groups: {
- fetchGroup: jest.fn(),
- fetchGroupsByKeys: jest.fn().mockResolvedValue([
- {
- team_id: team.id as TeamId,
- group_type_index: 0 as GroupTypeIndex,
- group_key: 'acme-inc',
- group_properties: { name: 'Acme Inc', industry: 'Tech' },
- },
- ]),
- fetchGroupTypesByTeamIds: jest.fn().mockImplementation((teamIds: number[]) => {
- const result: Record<string, { group_type: string; group_type_index: GroupTypeIndex }[]> = {}
- for (const id of teamIds) {
- result[id.toString()] = [{ group_type: 'company', group_type_index: 0 as GroupTypeIndex }]
- }
- return Promise.resolve(result)
- }),
- fetchGroupTypesByProjectIds: jest.fn(),
- },
- persons: {
- fetchPersonsByDistinctIds: jest.fn(),
- fetchPersonsByPersonIds: jest.fn(),
- },
- }
-
- const personhogRepo = new PersonHogGroupRepository(
- hub.groupRepository,
- mockGrpc as unknown as PersonHogClient,
- 100,
- new Set(),
- 'test'
- )
- const personhogGroupsManager = new GroupsManagerService(hub.teamManager, personhogRepo)
- api['batchExportHogFunctionService']['groupsManager'] = personhogGroupsManager
-
- clickhouseEvent.properties = JSON.stringify({
- $lib_version: '1.0.0',
- $groups: { company: 'acme-inc' },
- })
-
- mockFetch.mockImplementationOnce(() =>
- Promise.resolve({
- status: 200,
- headers: { 'Content-Type': 'application/json' },
- json: () => Promise.resolve({ ok: true }),
- text: () => Promise.resolve(JSON.stringify({ ok: true })),
- dump: () => Promise.resolve(),
- })
- )
-
- const res = await postInvocation({ clickhouse_event: clickhouseEvent })
-
- expect(res.status).toEqual(200)
- expect(res.body.status).toEqual('success')
-
- const fetchBody = parseJSON(mockFetch.mock.calls[0][1].body)
- expect(fetchBody.groups).toMatchObject({
- company: expect.objectContaining({
- id: 'acme-inc',
- type: 'company',
- properties: { name: 'Acme Inc', industry: 'Tech' },
- }),
- })
-
- // Verify gRPC was the path used (not postgres)
- expect(mockGrpc.groups.fetchGroupTypesByTeamIds).toHaveBeenCalled()
- expect(mockGrpc.groups.fetchGroupsByKeys).toHaveBeenCalled()
- })
- })
})
diff --git a/nodejs/src/cdp/services/managers/groups-manager-personhog.test.ts b/nodejs/src/cdp/services/managers/groups-manager-personhog.test.ts
deleted file mode 100644
index 0665ce924cc0..000000000000
--- a/nodejs/src/cdp/services/managers/groups-manager-personhog.test.ts
+++ /dev/null
@@ -1,469 +0,0 @@
-import { TeamManager } from '~/utils/team-manager'
-import { GroupRepository } from '~/worker/ingestion/groups/repositories/group-repository.interface'
-
-import { PersonHogClient } from '../../../ingestion/personhog/client'
-import { PersonHogGroupRepository } from '../../../ingestion/personhog/personhog-group-repository'
-import { GroupTypeIndex, TeamId } from '../../../types'
-import { createHogExecutionGlobals } from '../../_tests/fixtures'
-import { GroupsManagerService } from './groups-manager.service'
-
-jest.mock('../../../utils/logger')
-
-const TEAM_1 = 1 as TeamId
-const TEAM_2 = 2 as TeamId
-
-const MOCK_GROUP_TYPES = [
- { team_id: TEAM_1, group_type: 'GroupA', group_type_index: 0 as GroupTypeIndex },
- { team_id: TEAM_1, group_type: 'GroupB', group_type_index: 1 as GroupTypeIndex },
- { team_id: TEAM_2, group_type: 'GroupA', group_type_index: 1 as GroupTypeIndex },
-]
-
-const MOCK_GROUPS = [
- {
- team_id: TEAM_1,
- group_type_index: 0 as GroupTypeIndex,
- group_key: 'id-1',
- group_properties: { prop: 'value-1' },
- },
- {
- team_id: TEAM_1,
- group_type_index: 1 as GroupTypeIndex,
- group_key: 'id-2',
- group_properties: { prop: 'value-2' },
- },
- {
- team_id: TEAM_2,
- group_type_index: 1 as GroupTypeIndex,
- group_key: 'id-1',
- group_properties: { prop: 'value-team-2' },
- },
-]
-
-function createMockPostgres(
- groupTypes: typeof MOCK_GROUP_TYPES,
- groups: typeof MOCK_GROUPS
-): jest.Mocked<GroupRepository> {
- const mock: jest.Mocked<GroupRepository> = {
- fetchGroup: jest.fn(),
- fetchGroupsByKeys: jest.fn(),
- fetchGroupTypesByTeamIds: jest.fn(),
- fetchGroupTypesByProjectIds: jest.fn(),
- insertGroup: jest.fn(),
- updateGroup: jest.fn(),
- updateGroupOptimistically: jest.fn(),
- insertGroupType: jest.fn(),
- inTransaction: jest.fn(),
- }
-
- mock.fetchGroupTypesByTeamIds.mockImplementation((teamIds: TeamId[]) => {
- const result: Record<string, { group_type: string; group_type_index: GroupTypeIndex }[]> = {}
- for (const teamId of teamIds) {
- result[teamId.toString()] = []
- }
- for (const gt of groupTypes) {
- if (teamIds.includes(gt.team_id)) {
- result[gt.team_id.toString()].push({
- group_type: gt.group_type,
- group_type_index: gt.group_type_index,
- })
- }
- }
- return Promise.resolve(result)
- })
-
- mock.fetchGroupsByKeys.mockImplementation(
- (teamIds: TeamId[], groupIndexes: GroupTypeIndex[], groupKeys: string[]) => {
- const results = groups.filter((group) => {
- for (let i = 0; i < teamIds.length; i++) {
- if (
- teamIds[i] === group.team_id &&
- groupIndexes[i] === group.group_type_index &&
- groupKeys[i] === group.group_key
- ) {
- return true
- }
- }
- return false
- })
- return Promise.resolve(results)
- }
- )
-
- return mock
-}
-
-type MockPersonHogClient = {
- groups: jest.Mocked<
- Pick<
- PersonHogClient['groups'],
- 'fetchGroup' | 'fetchGroupsByKeys' | 'fetchGroupTypesByTeamIds' | 'fetchGroupTypesByProjectIds'
- >
- >
- persons: jest.Mocked<Pick<PersonHogClient['persons'], 'fetchPersonsByDistinctIds' | 'fetchPersonsByPersonIds'>>
-}
-
-function createMockGrpcClient(groupTypes: typeof MOCK_GROUP_TYPES, groups: typeof MOCK_GROUPS): MockPersonHogClient {
- const mock: MockPersonHogClient = {
- groups: {
- fetchGroup: jest.fn(),
- fetchGroupsByKeys: jest.fn(),
- fetchGroupTypesByTeamIds: jest.fn(),
- fetchGroupTypesByProjectIds: jest.fn(),
- },
- persons: {
- fetchPersonsByDistinctIds: jest.fn(),
- fetchPersonsByPersonIds: jest.fn(),
- },
- }
-
- mock.groups.fetchGroupTypesByTeamIds.mockImplementation((teamIds: number[]) => {
- const result: Record<string, { group_type: string; group_type_index: GroupTypeIndex }[]> = {}
- for (const teamId of teamIds) {
- result[teamId.toString()] = []
- }
- for (const gt of groupTypes) {
- if (teamIds.includes(gt.team_id)) {
- result[gt.team_id.toString()].push({
- group_type: gt.group_type,
- group_type_index: gt.group_type_index,
- })
- }
- }
- return Promise.resolve(result)
- })
-
- mock.groups.fetchGroupsByKeys.mockImplementation(
- (teamIds: number[], groupIndexes: number[], groupKeys: string[]) => {
- const results = groups.filter((group) => {
- for (let i = 0; i < teamIds.length; i++) {
- if (
- teamIds[i] === group.team_id &&
- groupIndexes[i] === group.group_type_index &&
- groupKeys[i] === group.group_key
- ) {
- return true
- }
- }
- return false
- })
- return Promise.resolve(results)
- }
- )
-
- return mock
-}
-
-describe('GroupsManagerService + PersonHogGroupRepository integration', () => {
- jest.setTimeout(1000)
-
- const mockHasAvailableFeature = jest.fn(() => Promise.resolve(true))
- const mockTeamManager = {
- hasAvailableFeature: mockHasAvailableFeature,
- } as unknown as TeamManager
-
- describe.each([
- ['postgres (rollout 0%)', 0],
- ['grpc (rollout 100%)', 100],
- ])('%s', (_label, rolloutPercentage) => {
- let mockPostgres: jest.Mocked<GroupRepository>
- let mockGrpc: ReturnType<typeof createMockGrpcClient>
- let groupsManager: GroupsManagerService
-
- beforeEach(() => {
- jest.restoreAllMocks()
- mockHasAvailableFeature.mockReturnValue(Promise.resolve(true))
- mockPostgres = createMockPostgres(MOCK_GROUP_TYPES, MOCK_GROUPS)
- mockGrpc = createMockGrpcClient(MOCK_GROUP_TYPES, MOCK_GROUPS)
-
- const personhogRepo = new PersonHogGroupRepository(
- mockPostgres,
- mockGrpc as unknown as PersonHogClient,
- rolloutPercentage,
- new Set(),
- 'test'
- )
- groupsManager = new GroupsManagerService(mockTeamManager, personhogRepo)
- })
-
- it('enriches simple groups', async () => {
- const globals = createHogExecutionGlobals({
- groups: undefined,
- event: {
- properties: { $groups: { GroupA: 'id-1', GroupB: 'id-2' } },
- } as any,
- })
-
- await groupsManager.addGroupsToGlobals(globals)
-
- expect(globals.groups).toEqual({
- GroupA: {
- id: 'id-1',
- index: 0,
- properties: { prop: 'value-1' },
- type: 'GroupA',
- url: 'http://localhost:8000/projects/1/groups/0/id-1',
- },
- GroupB: {
- id: 'id-2',
- index: 1,
- properties: { prop: 'value-2' },
- type: 'GroupB',
- url: 'http://localhost:8000/projects/1/groups/1/id-2',
- },
- })
-
- if (rolloutPercentage === 100) {
- expect(mockGrpc.groups.fetchGroupTypesByTeamIds).toHaveBeenCalledWith(
- [TEAM_1],
- 'cdp/hogflow-group-type-resolution'
- )
- expect(mockGrpc.groups.fetchGroupsByKeys).toHaveBeenCalled()
- expect(mockPostgres.fetchGroupTypesByTeamIds).not.toHaveBeenCalled()
- expect(mockPostgres.fetchGroupsByKeys).not.toHaveBeenCalled()
- } else {
- expect(mockPostgres.fetchGroupTypesByTeamIds).toHaveBeenCalledWith(
- [TEAM_1],
- 'cdp/hogflow-group-type-resolution'
- )
- expect(mockPostgres.fetchGroupsByKeys).toHaveBeenCalled()
- expect(mockGrpc.groups.fetchGroupTypesByTeamIds).not.toHaveBeenCalled()
- expect(mockGrpc.groups.fetchGroupsByKeys).not.toHaveBeenCalled()
- }
- })
-
- it('enriches multiple globals from different teams concurrently', async () => {
- const items = [
- createHogExecutionGlobals({
- groups: undefined,
- event: { properties: { $groups: { GroupA: 'id-1', GroupB: 'id-2' } } } as any,
- }),
- createHogExecutionGlobals({
- groups: undefined,
- project: { id: 2 } as any,
- event: { properties: { $groups: { GroupA: 'id-1' } } } as any,
- }),
- ]
-
- await Promise.all(items.map((item) => groupsManager.addGroupsToGlobals(item)))
-
- expect(items[0].groups).toEqual({
- GroupA: {
- id: 'id-1',
- index: 0,
- properties: { prop: 'value-1' },
- type: 'GroupA',
- url: 'http://localhost:8000/projects/1/groups/0/id-1',
- },
- GroupB: {
- id: 'id-2',
- index: 1,
- properties: { prop: 'value-2' },
- type: 'GroupB',
- url: 'http://localhost:8000/projects/1/groups/1/id-2',
- },
- })
-
- expect(items[1].groups).toEqual({
- GroupA: {
- id: 'id-1',
- index: 1,
- properties: { prop: 'value-team-2' },
- type: 'GroupA',
- url: 'http://localhost:8000/projects/1/groups/1/id-1',
- },
- })
- })
-
- it('returns empty properties when group type exists but no matching group row', async () => {
- const globals = createHogExecutionGlobals({
- groups: undefined,
- event: {
- properties: { $groups: { GroupA: 'nonexistent-key' } },
- } as any,
- })
-
- await groupsManager.addGroupsToGlobals(globals)
-
- expect(globals.groups).toEqual({
- GroupA: {
- id: 'nonexistent-key',
- index: 0,
- properties: {},
- type: 'GroupA',
- url: 'http://localhost:8000/projects/1/groups/0/nonexistent-key',
- },
- })
- })
- })
-
- describe('gRPC empty group type mapping key omission', () => {
- it('event with unknown group type is silently skipped when gRPC omits the mapping key', async () => {
- // The real PersonHogClient does NOT pre-initialize empty arrays for
- // requested team IDs that have no group type mappings — the key is
- // simply absent from the response. This differs from Postgres which
- // returns { "teamId": [] }. Verify that GroupsManagerService handles
- // the missing key via its ?? [] fallback and produces the correct result.
- const TEAM_3 = 3 as TeamId
-
- const mockPostgres = createMockPostgres([], [])
- const mockGrpc: MockPersonHogClient = {
- groups: {
- fetchGroup: jest.fn(),
- fetchGroupsByKeys: jest.fn().mockResolvedValue([]),
- fetchGroupTypesByTeamIds: jest.fn().mockImplementation((_teamIds: number[]) => {
- // Mimic real gRPC behavior: return empty object (no key for team 3)
- return Promise.resolve({})
- }),
- fetchGroupTypesByProjectIds: jest.fn(),
- },
- persons: {
- fetchPersonsByDistinctIds: jest.fn(),
- fetchPersonsByPersonIds: jest.fn(),
- },
- }
-
- const personhogRepo = new PersonHogGroupRepository(
- mockPostgres,
- mockGrpc as unknown as PersonHogClient,
- 100,
- new Set(),
- 'test'
- )
- const manager = new GroupsManagerService(
- { hasAvailableFeature: jest.fn().mockResolvedValue(true) } as unknown as TeamManager,
- personhogRepo
- )
-
- const globals = createHogExecutionGlobals({
- groups: undefined,
- project: { id: TEAM_3 } as any,
- event: {
- properties: { $groups: { UnknownType: 'some-key' } },
- } as any,
- })
-
- await manager.addGroupsToGlobals(globals)
-
- // UnknownType has no mapping → skipped entirely → empty groups
- expect(globals.groups).toEqual({})
- expect(mockGrpc.groups.fetchGroupTypesByTeamIds).toHaveBeenCalledWith(
- [TEAM_3],
- 'cdp/hogflow-group-type-resolution'
- )
- // fetchGroupsByKeys should NOT be called since there are no valid group type mappings
- expect(mockGrpc.groups.fetchGroupsByKeys).not.toHaveBeenCalled()
- })
- })
-
- describe('grpc fallback to postgres on error', () => {
- let mockPostgres: jest.Mocked<GroupRepository>
- let mockGrpc: ReturnType<typeof createMockGrpcClient>
- let groupsManager: GroupsManagerService
-
- beforeEach(() => {
- jest.restoreAllMocks()
- mockHasAvailableFeature.mockReturnValue(Promise.resolve(true))
- mockPostgres = createMockPostgres(MOCK_GROUP_TYPES, MOCK_GROUPS)
- mockGrpc = createMockGrpcClient(MOCK_GROUP_TYPES, MOCK_GROUPS)
-
- const personhogRepo = new PersonHogGroupRepository(
- mockPostgres,
- mockGrpc as unknown as PersonHogClient,
- 100,
- new Set(),
- 'test'
- )
- groupsManager = new GroupsManagerService(mockTeamManager, personhogRepo)
- })
-
- it('falls back to postgres when gRPC fetchGroupTypesByTeamIds fails', async () => {
- mockGrpc.groups.fetchGroupTypesByTeamIds.mockRejectedValue(new Error('connection refused'))
-
- const globals = createHogExecutionGlobals({
- groups: undefined,
- event: {
- properties: { $groups: { GroupA: 'id-1' } },
- } as any,
- })
-
- await groupsManager.addGroupsToGlobals(globals)
-
- expect(globals.groups).toEqual({
- GroupA: {
- id: 'id-1',
- index: 0,
- properties: { prop: 'value-1' },
- type: 'GroupA',
- url: 'http://localhost:8000/projects/1/groups/0/id-1',
- },
- })
-
- // gRPC was called and failed
- expect(mockGrpc.groups.fetchGroupTypesByTeamIds).toHaveBeenCalled()
- // Postgres was called as fallback
- expect(mockPostgres.fetchGroupTypesByTeamIds).toHaveBeenCalled()
- })
-
- it('falls back to postgres when gRPC fetchGroupsByKeys fails', async () => {
- mockGrpc.groups.fetchGroupsByKeys.mockRejectedValue(new Error('timeout'))
-
- const globals = createHogExecutionGlobals({
- groups: undefined,
- event: {
- properties: { $groups: { GroupA: 'id-1' } },
- } as any,
- })
-
- await groupsManager.addGroupsToGlobals(globals)
-
- expect(globals.groups).toEqual({
- GroupA: {
- id: 'id-1',
- index: 0,
- properties: { prop: 'value-1' },
- type: 'GroupA',
- url: 'http://localhost:8000/projects/1/groups/0/id-1',
- },
- })
-
- // gRPC fetchGroupsByKeys was called and failed
- expect(mockGrpc.groups.fetchGroupsByKeys).toHaveBeenCalled()
- // Postgres fetchGroupsByKeys was called as fallback
- expect(mockPostgres.fetchGroupsByKeys).toHaveBeenCalled()
- })
-
- it('produces identical output on fallback as on direct postgres path', async () => {
- // First: get the postgres-only result
- const postgresRepo = new PersonHogGroupRepository(
- mockPostgres,
- mockGrpc as unknown as PersonHogClient,
- 0,
- new Set(),
- 'test'
- )
- const postgresManager = new GroupsManagerService(mockTeamManager, postgresRepo)
-
- const postgresGlobals = createHogExecutionGlobals({
- groups: undefined,
- event: {
- properties: { $groups: { GroupA: 'id-1', GroupB: 'id-2' } },
- } as any,
- })
- await postgresManager.addGroupsToGlobals(postgresGlobals)
-
- // Second: get the fallback result (gRPC fails for everything)
- mockGrpc.groups.fetchGroupTypesByTeamIds.mockRejectedValue(new Error('down'))
- mockGrpc.groups.fetchGroupsByKeys.mockRejectedValue(new Error('down'))
-
- const fallbackGlobals = createHogExecutionGlobals({
- groups: undefined,
- event: {
- properties: { $groups: { GroupA: 'id-1', GroupB: 'id-2' } },
- } as any,
- })
- await groupsManager.addGroupsToGlobals(fallbackGlobals)
-
- expect(fallbackGlobals.groups).toEqual(postgresGlobals.groups)
- })
- })
-})
diff --git a/nodejs/src/cdp/services/managers/groups-manager.service.test.ts b/nodejs/src/cdp/services/managers/groups-manager.service.test.ts
index 1cb0074e46a4..6d624461ba2e 100644
--- a/nodejs/src/cdp/services/managers/groups-manager.service.test.ts
+++ b/nodejs/src/cdp/services/managers/groups-manager.service.test.ts
@@ -1,5 +1,5 @@
import { TeamManager } from '~/utils/team-manager'
-import { GroupRepository } from '~/worker/ingestion/groups/repositories/group-repository.interface'
+import { GroupReadRepository } from '~/worker/ingestion/groups/repositories/group-repository.interface'
import { createHogExecutionGlobals } from '../../_tests/fixtures'
import { GroupsManagerService } from './groups-manager.service'
@@ -22,7 +22,7 @@ describe('Groups Manager', () => {
const mockGroupRepository = {
fetchGroupTypesByTeamIds: mockFetchGroupTypesByTeamIds,
fetchGroupsByKeys: mockFetchGroupsByKeys,
- } as unknown as GroupRepository
+ } as unknown as GroupReadRepository
beforeEach(() => {
jest.restoreAllMocks()
@@ -303,6 +303,25 @@ describe('Groups Manager', () => {
expect(mockFetchGroupsByKeys).toHaveBeenCalledTimes(0)
})
+ it('handles absent team key in group type response gracefully', async () => {
+ // When personhog returns no mapping for a team, the key is absent from
+ // the response (not present as an empty array). Verify the code handles
+ // this via its ?? [] fallback.
+ mockFetchGroupTypesByTeamIds.mockResolvedValue({})
+
+ const globals = createHogExecutionGlobals({
+ groups: undefined,
+ project: { id: 99 } as any,
+ event: { properties: { $groups: { UnknownType: 'some-key' } } } as any,
+ })
+
+ await groupsManager.addGroupsToGlobals(globals)
+
+ expect(globals.groups).toEqual({})
+ expect(mockFetchGroupTypesByTeamIds).toHaveBeenCalledWith([99], 'cdp/hogflow-group-type-resolution')
+ expect(mockFetchGroupsByKeys).not.toHaveBeenCalled()
+ })
+
it('respects clear() to reset all caches', async () => {
const globals1 = createHogExecutionGlobals({
groups: undefined,
diff --git a/nodejs/src/cdp/services/managers/groups-manager.service.ts b/nodejs/src/cdp/services/managers/groups-manager.service.ts
index 4426f9b3577c..93457129f12c 100644
--- a/nodejs/src/cdp/services/managers/groups-manager.service.ts
+++ b/nodejs/src/cdp/services/managers/groups-manager.service.ts
@@ -2,7 +2,7 @@ import { sanitizeString } from '~/utils/db/utils'
import { LazyLoader } from '~/utils/lazy-loader'
import { logger } from '~/utils/logger'
import { TeamManager } from '~/utils/team-manager'
-import { GroupRepository } from '~/worker/ingestion/groups/repositories/group-repository.interface'
+import { GroupReadRepository } from '~/worker/ingestion/groups/repositories/group-repository.interface'
import { GroupTypeIndex, Team } from '../../../types'
import { GroupType, HogFunctionInvocationGlobals } from '../../types'
@@ -31,7 +31,7 @@ export class GroupsManagerService {
constructor(
private teamManager: TeamManager,
- private groupRepository: GroupRepository
+ private groupRepository: GroupReadRepository
) {
this.groupTypesLoader = new LazyLoader({
name: 'groups_manager_types',
diff --git a/nodejs/src/ingestion/personhog/grpc-retry.test.ts b/nodejs/src/ingestion/personhog/grpc-retry.test.ts
new file mode 100644
index 000000000000..cd39d9bd044e
--- /dev/null
+++ b/nodejs/src/ingestion/personhog/grpc-retry.test.ts
@@ -0,0 +1,106 @@
+import { Code, ConnectError } from '@connectrpc/connect'
+
+import { withRetry } from './grpc-retry'
+
+jest.mock('../../utils/logger')
+
+describe('withRetry', () => {
+ it('returns the result on first success', async () => {
+ const result = await withRetry('test', () => Promise.resolve('ok'))
+ expect(result).toBe('ok')
+ })
+
+ it('retries on transient error and returns result on success', async () => {
+ let callCount = 0
+ const result = await withRetry('test', () => {
+ callCount++
+ if (callCount === 1) {
+ throw new ConnectError('transient', Code.Unavailable)
+ }
+ return Promise.resolve('recovered')
+ })
+
+ expect(result).toBe('recovered')
+ expect(callCount).toBe(2)
+ })
+
+ it.each([
+ ['Unavailable', Code.Unavailable],
+ ['DeadlineExceeded', Code.DeadlineExceeded],
+ ['ResourceExhausted', Code.ResourceExhausted],
+ ['Aborted', Code.Aborted],
+ ['Internal', Code.Internal],
+ ['Unknown', Code.Unknown],
+ ])('retries on %s', async (_name, code) => {
+ let callCount = 0
+ await withRetry('test', () => {
+ callCount++
+ if (callCount <= 1) {
+ throw new ConnectError('transient', code)
+ }
+ return Promise.resolve('ok')
+ })
+ expect(callCount).toBe(2)
+ })
+
+ it.each([
+ ['InvalidArgument', Code.InvalidArgument],
+ ['NotFound', Code.NotFound],
+ ['AlreadyExists', Code.AlreadyExists],
+ ['PermissionDenied', Code.PermissionDenied],
+ ['Unauthenticated', Code.Unauthenticated],
+ ['Unimplemented', Code.Unimplemented],
+ ['FailedPrecondition', Code.FailedPrecondition],
+ ['OutOfRange', Code.OutOfRange],
+ ['DataLoss', Code.DataLoss],
+ ['Canceled', Code.Canceled],
+ ])('does not retry on %s', async (_name, code) => {
+ let callCount = 0
+ await expect(
+ withRetry('test', () => {
+ callCount++
+ throw new ConnectError('non-retryable', code)
+ })
+ ).rejects.toThrow(ConnectError)
+ expect(callCount).toBe(1)
+ })
+
+ it('does not retry non-ConnectError errors', async () => {
+ let callCount = 0
+ await expect(
+ withRetry('test', () => {
+ callCount++
+ throw new Error('plain error')
+ })
+ ).rejects.toThrow('plain error')
+ expect(callCount).toBe(1)
+ })
+
+ it('throws after max retries exhausted', async () => {
+ let callCount = 0
+ await expect(
+ withRetry('test', () => {
+ callCount++
+ throw new ConnectError('unavailable', Code.Unavailable)
+ })
+ ).rejects.toThrow(ConnectError)
+ // 1 initial + 2 retries = 3 total (default maxRetries=2)
+ expect(callCount).toBe(3)
+ })
+
+ it('respects custom maxRetries', async () => {
+ let callCount = 0
+ await expect(
+ withRetry(
+ 'test',
+ () => {
+ callCount++
+ throw new ConnectError('unavailable', Code.Unavailable)
+ },
+ 4
+ )
+ ).rejects.toThrow(ConnectError)
+ // 1 initial + 4 retries = 5 total
+ expect(callCount).toBe(5)
+ })
+})
diff --git a/nodejs/src/ingestion/personhog/grpc-retry.ts b/nodejs/src/ingestion/personhog/grpc-retry.ts
new file mode 100644
index 000000000000..434b50a1c4cd
--- /dev/null
+++ b/nodejs/src/ingestion/personhog/grpc-retry.ts
@@ -0,0 +1,50 @@
+import { Code, ConnectError } from '@connectrpc/connect'
+
+import { logger } from '../../utils/logger'
+
+const RETRYABLE_CODES = new Set([
+ Code.Unavailable,
+ Code.DeadlineExceeded,
+ Code.ResourceExhausted,
+ Code.Aborted,
+ Code.Internal,
+ Code.Unknown,
+])
+
+function isRetryable(error: unknown): boolean {
+ return error instanceof ConnectError && RETRYABLE_CODES.has(error.code)
+}
+
+function sleep(ms: number): Promise<void> {
+ return new Promise((resolve) => setTimeout(resolve, ms))
+}
+
+/**
+ * Retry a function with exponential backoff on transient gRPC errors.
+ * Non-transient errors are thrown immediately.
+ */
+export async function withRetry<T>(
+ label: string,
+ fn: () => Promise<T>,
+ maxRetries: number = 2,
+ initialDelayMs: number = 50
+): Promise<T> {
+ let lastError: unknown
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
+ try {
+ return await fn()
+ } catch (error) {
+ lastError = error
+ if (!isRetryable(error) || attempt === maxRetries) {
+ throw error
+ }
+ logger.warn(`[${label}] Retryable gRPC error, retrying`, {
+ attempt: attempt + 1,
+ maxRetries,
+ error: String(error),
+ })
+ await sleep(initialDelayMs * Math.pow(2, attempt))
+ }
+ }
+ throw lastError
+}
diff --git a/nodejs/src/ingestion/personhog/personhog-group-read-repository.test.ts b/nodejs/src/ingestion/personhog/personhog-group-read-repository.test.ts
new file mode 100644
index 000000000000..61589ee6f02a
--- /dev/null
+++ b/nodejs/src/ingestion/personhog/personhog-group-read-repository.test.ts
@@ -0,0 +1,178 @@
+import { Code, ConnectError, createRouterTransport } from '@connectrpc/connect'
+
+import { PersonHogService } from '../../generated/personhog/personhog/service/v1/service_pb'
+import { TeamId } from '../../types'
+import { PersonHogClient } from './client'
+import { PersonHogGroupReadRepository } from './personhog-group-read-repository'
+
+jest.mock('../../utils/logger')
+
+const TEAM_ID = 1 as TeamId
+
+type ServiceHandlers = {
+ getGroupsBatch: jest.Mock
+ getGroupTypeMappingsByTeamIds: jest.Mock
+}
+
+function createMockClientAndHandlers(): { client: PersonHogClient; handlers: ServiceHandlers } {
+ const handlers: ServiceHandlers = {
+ getGroupsBatch: jest.fn().mockReturnValue({ results: [] }),
+ getGroupTypeMappingsByTeamIds: jest.fn().mockReturnValue({ results: [] }),
+ }
+
+ const transport = createRouterTransport(({ service }) => {
+ service(PersonHogService, {
+ getGroupsBatch: handlers.getGroupsBatch,
+ getGroupTypeMappingsByTeamIds: handlers.getGroupTypeMappingsByTeamIds,
+ })
+ })
+
+ const client = PersonHogClient.fromTransport(transport)
+ return { client, handlers }
+}
+
+const textEncoder = new TextEncoder()
+
+function jsonBytes(obj: unknown): Uint8Array {
+ return textEncoder.encode(JSON.stringify(obj))
+}
+
+describe('PersonHogGroupReadRepository', () => {
+ describe('fetchGroupsByKeys', () => {
+ it('returns group properties for matching keys', async () => {
+ const { client, handlers } = createMockClientAndHandlers()
+ handlers.getGroupsBatch.mockReturnValue({
+ results: [
+ {
+ key: { teamId: BigInt(TEAM_ID), groupTypeIndex: 0, groupKey: 'company-1' },
+ group: {
+ id: 1n,
+ teamId: BigInt(TEAM_ID),
+ groupTypeIndex: 0,
+ groupKey: 'company-1',
+ groupProperties: jsonBytes({ name: 'Acme Inc' }),
+ propertiesLastUpdatedAt: jsonBytes({}),
+ propertiesLastOperation: jsonBytes({}),
+ createdAt: 1704067200000n,
+ version: 1n,
+ },
+ },
+ ],
+ })
+
+ const repo = new PersonHogGroupReadRepository(client)
+ const result = await repo.fetchGroupsByKeys([TEAM_ID], [0], ['company-1'])
+
+ expect(result).toHaveLength(1)
+ expect(result[0]).toEqual({
+ team_id: TEAM_ID,
+ group_type_index: 0,
+ group_key: 'company-1',
+ group_properties: { name: 'Acme Inc' },
+ })
+ })
+
+ it('returns empty array for empty input', async () => {
+ const { client, handlers } = createMockClientAndHandlers()
+ const repo = new PersonHogGroupReadRepository(client)
+ const result = await repo.fetchGroupsByKeys([], [], [])
+
+ expect(result).toEqual([])
+ expect(handlers.getGroupsBatch).not.toHaveBeenCalled()
+ })
+ })
+
+ describe('fetchGroupTypesByTeamIds', () => {
+ it('returns group type mappings keyed by team id', async () => {
+ const { client, handlers } = createMockClientAndHandlers()
+ handlers.getGroupTypeMappingsByTeamIds.mockReturnValue({
+ results: [
+ {
+ key: BigInt(TEAM_ID),
+ mappings: [
+ { groupType: 'company', groupTypeIndex: 0 },
+ { groupType: 'project', groupTypeIndex: 1 },
+ ],
+ },
+ ],
+ })
+
+ const repo = new PersonHogGroupReadRepository(client)
+ const result = await repo.fetchGroupTypesByTeamIds([TEAM_ID])
+
+ expect(result).toEqual({
+ [String(TEAM_ID)]: [
+ { group_type: 'company', group_type_index: 0 },
+ { group_type: 'project', group_type_index: 1 },
+ ],
+ })
+ })
+
+ it('returns empty record for empty input', async () => {
+ const { client, handlers } = createMockClientAndHandlers()
+ const repo = new PersonHogGroupReadRepository(client)
+ const result = await repo.fetchGroupTypesByTeamIds([])
+
+ expect(result).toEqual({})
+ expect(handlers.getGroupTypeMappingsByTeamIds).not.toHaveBeenCalled()
+ })
+ })
+
+ describe('retry behavior', () => {
+ it.each([
+ ['Unavailable', Code.Unavailable],
+ ['DeadlineExceeded', Code.DeadlineExceeded],
+ ['ResourceExhausted', Code.ResourceExhausted],
+ ['Aborted', Code.Aborted],
+ ['Internal', Code.Internal],
+ ['Unknown', Code.Unknown],
+ ])('retries on %s and succeeds', async (_name, code) => {
+ const { client, handlers } = createMockClientAndHandlers()
+ let callCount = 0
+ handlers.getGroupsBatch.mockImplementation(() => {
+ callCount++
+ if (callCount === 1) {
+ throw new ConnectError('transient', code)
+ }
+ return { results: [] }
+ })
+
+ const repo = new PersonHogGroupReadRepository(client)
+ const result = await repo.fetchGroupsByKeys([TEAM_ID], [0], ['key'])
+
+ expect(result).toEqual([])
+ expect(callCount).toBe(2)
+ })
+
+ it.each([
+ ['InvalidArgument', Code.InvalidArgument],
+ ['NotFound', Code.NotFound],
+ ['PermissionDenied', Code.PermissionDenied],
+ ['Unauthenticated', Code.Unauthenticated],
+ ['Unimplemented', Code.Unimplemented],
+ ])('does not retry on %s', async (_name, code) => {
+ const { client, handlers } = createMockClientAndHandlers()
+ handlers.getGroupsBatch.mockImplementation(() => {
+ throw new ConnectError('non-retryable', code)
+ })
+
+ const repo = new PersonHogGroupReadRepository(client)
+ await expect(repo.fetchGroupsByKeys([TEAM_ID], [0], ['key'])).rejects.toThrow(ConnectError)
+
+ expect(handlers.getGroupsBatch).toHaveBeenCalledTimes(1)
+ })
+
+ it('throws after max retries exhausted', async () => {
+ const { client, handlers } = createMockClientAndHandlers()
+ handlers.getGroupsBatch.mockImplementation(() => {
+ throw new ConnectError('unavailable', Code.Unavailable)
+ })
+
+ const repo = new PersonHogGroupReadRepository(client)
+ await expect(repo.fetchGroupsByKeys([TEAM_ID], [0], ['key'])).rejects.toThrow(ConnectError)
+
+ // 1 initial + 2 retries = 3 total
+ expect(handlers.getGroupsBatch).toHaveBeenCalledTimes(3)
+ })
+ })
+})
diff --git a/nodejs/src/ingestion/personhog/personhog-group-read-repository.ts b/nodejs/src/ingestion/personhog/personhog-group-read-repository.ts
new file mode 100644
index 000000000000..f211d0db4809
--- /dev/null
+++ b/nodejs/src/ingestion/personhog/personhog-group-read-repository.ts
@@ -0,0 +1,48 @@
+import { GroupTypeIndex, TeamId } from '../../types'
+import { GroupReadRepository } from '../../worker/ingestion/groups/repositories/group-repository.interface'
+import { PersonHogClient } from './client'
+import { withRetry } from './grpc-retry'
+import { timedGrpc } from './metrics'
+
+/**
+ * Read-only group repository backed by personhog gRPC. No Postgres
+ * dependency — all reads go through personhog with automatic retries
+ * on transient errors.
+ */
+export class PersonHogGroupReadRepository implements GroupReadRepository {
+ constructor(
+ private grpcClient: PersonHogClient,
+ private clientLabel: string = 'unknown'
+ ) {}
+
+ async fetchGroupsByKeys(
+ teamIds: TeamId[],
+ groupTypeIndexes: GroupTypeIndex[],
+ groupKeys: string[],
+ callerTag?: string
+ ): Promise<
+ {
+ team_id: TeamId
+ group_type_index: GroupTypeIndex
+ group_key: string
+ group_properties: Record<string, any>
+ }[]
+ > {
+ return withRetry('PersonHogGroupReadRepository', () =>
+ timedGrpc(this.clientLabel, 'fetchGroupsByKeys', () =>
+ this.grpcClient.groups.fetchGroupsByKeys(teamIds, groupTypeIndexes, groupKeys, callerTag)
+ )
+ )
+ }
+
+ async fetchGroupTypesByTeamIds(
+ teamIds: TeamId[],
+ callerTag?: string
+ ): Promise<Record<string, { group_type: string; group_type_index: GroupTypeIndex }[]>> {
+ return withRetry('PersonHogGroupReadRepository', () =>
+ timedGrpc(this.clientLabel, 'fetchGroupTypesByTeamIds', () =>
+ this.grpcClient.groups.fetchGroupTypesByTeamIds(teamIds, callerTag)
+ )
+ )
+ }
+}
diff --git a/nodejs/src/ingestion/personhog/personhog-person-read-repository.ts b/nodejs/src/ingestion/personhog/personhog-person-read-repository.ts
index bebc6ed94f66..a8cbbe93cb51 100644
--- a/nodejs/src/ingestion/personhog/personhog-person-read-repository.ts
+++ b/nodejs/src/ingestion/personhog/personhog-person-read-repository.ts
@@ -1,56 +1,12 @@
-import { Code, ConnectError } from '@connectrpc/connect'
-
import { InternalPerson, TeamId } from '../../types'
-import { logger } from '../../utils/logger'
import {
InternalPersonWithDistinctId,
PersonReadRepository,
} from '../../worker/ingestion/persons/repositories/person-repository'
import { PersonHogClient } from './client'
+import { withRetry } from './grpc-retry'
import { timedGrpc } from './metrics'
-const RETRYABLE_CODES = new Set([
- Code.Unavailable,
- Code.DeadlineExceeded,
- Code.ResourceExhausted,
- Code.Aborted,
- Code.Internal,
- Code.Unknown,
-])
-
-function isRetryable(error: unknown): boolean {
- return error instanceof ConnectError && RETRYABLE_CODES.has(error.code)
-}
-
-function sleep(ms: number): Promise<void> {
- return new Promise((resolve) => setTimeout(resolve, ms))
-}
-
-/**
- * Retry a function with exponential backoff on transient gRPC errors.
- * Non-transient errors are thrown immediately.
- */
-async function withRetry<T>(fn: () => Promise<T>, maxRetries: number = 2, initialDelayMs: number = 50): Promise<T> {
- let lastError: unknown
- for (let attempt = 0; attempt <= maxRetries; attempt++) {
- try {
- return await fn()
- } catch (error) {
- lastError = error
- if (!isRetryable(error) || attempt === maxRetries) {
- throw error
- }
- logger.warn('[PersonHogPersonReadRepository] Retryable gRPC error, retrying', {
- attempt: attempt + 1,
- maxRetries,
- error: String(error),
- })
- await sleep(initialDelayMs * Math.pow(2, attempt))
- }
- }
- throw lastError
-}
-
/**
* Read-only person repository backed by personhog gRPC. No Postgres
* dependency — all reads go through personhog with automatic retries
@@ -63,7 +19,7 @@ export class PersonHogPersonReadRepository implements PersonReadRepository {
) {}
async fetchPerson(teamId: number, distinctId: string, callerTag?: string): Promise<InternalPerson | undefined> {
- const results = await withRetry(() =>
+ const results = await withRetry('PersonHogPersonReadRepository', () =>
timedGrpc(this.clientLabel, 'fetchPerson', () =>
this.grpcClient.persons.fetchPersonsByDistinctIds([{ teamId, distinctId }], callerTag)
)
@@ -75,7 +31,7 @@ export class PersonHogPersonReadRepository implements PersonReadRepository {
teamPersons: { teamId: TeamId; distinctId: string }[],
callerTag?: string
): Promise<InternalPersonWithDistinctId[]> {
- return withRetry(() =>
+ return withRetry('PersonHogPersonReadRepository', () =>
timedGrpc(this.clientLabel, 'fetchPersonsByDistinctIds', () =>
this.grpcClient.persons.fetchPersonsByDistinctIds(teamPersons, callerTag)
)
@@ -86,7 +42,7 @@ export class PersonHogPersonReadRepository implements PersonReadRepository {
teamPersons: { teamId: TeamId; personId: string }[],
callerTag?: string
): Promise<InternalPerson[]> {
- return withRetry(() =>
+ return withRetry('PersonHogPersonReadRepository', () =>
timedGrpc(this.clientLabel, 'fetchPersonsByPersonIds', () =>
this.grpcClient.persons.fetchPersonsByPersonIds(teamPersons, callerTag)
)
@@ -99,7 +55,7 @@ export class PersonHogPersonReadRepository implements PersonReadRepository {
options?: { limitPerPerson?: number },
callerTag?: string
): Promise<Record<string, string[]>> {
- return withRetry(() =>
+ return withRetry('PersonHogPersonReadRepository', () =>
timedGrpc(this.clientLabel, 'fetchDistinctIdsForPersons', () =>
this.grpcClient.persons.getDistinctIdsForPersons(
teamId,
diff --git a/nodejs/src/server.ts b/nodejs/src/server.ts
index f7190e767e6a..984f07850877 100644
--- a/nodejs/src/server.ts
+++ b/nodejs/src/server.ts
@@ -30,7 +30,8 @@ import { defaultConfig } from './config/config'
import { createIngestionRedisConnectionConfig, createPosthogRedisConnectionConfig } from './config/redis-pools'
import { startEvaluationScheduler } from './evaluation-scheduler/evaluation-scheduler'
import { KafkaProducerRegistry } from './ingestion/outputs/kafka-producer-registry'
-import { buildGroupRepository, createPersonHogClient } from './ingestion/personhog'
+import { createPersonHogClient } from './ingestion/personhog'
+import { PersonHogGroupReadRepository } from './ingestion/personhog/personhog-group-read-repository'
import { PersonHogPersonReadRepository } from './ingestion/personhog/personhog-person-read-repository'
import { CleanupResources, NodeServer, ServerLifecycle } from './servers/base-server'
import { PluginServerService, PluginsServerConfig, RedisPool } from './types'
@@ -41,8 +42,7 @@ import { GeoIPService } from './utils/geoip'
import { logger } from './utils/logger'
import { PubSub } from './utils/pubsub'
import { TeamManager } from './utils/team-manager'
-import { GroupRepository } from './worker/ingestion/groups/repositories/group-repository.interface'
-import { PostgresGroupRepository } from './worker/ingestion/groups/repositories/postgres-group-repository'
+import { GroupReadRepository } from './worker/ingestion/groups/repositories/group-repository.interface'
import { PersonReadRepository } from './worker/ingestion/persons/repositories/person-repository'
/**
@@ -363,7 +363,7 @@ export class PluginServer implements NodeServer {
private async createCdpSharedServices(): Promise<{
geoipService: GeoIPService
personRepository: PersonReadRepository
- groupRepository: GroupRepository
+ groupRepository: GroupReadRepository
encryptedFields: EncryptedFields
integrationManager: IntegrationManagerService
internalCaptureService: InternalCaptureService
@@ -379,16 +379,7 @@ export class PluginServer implements NodeServer {
}
const personRepository = new PersonHogPersonReadRepository(personhogClient, clientLabel)
-
- // Groups still use the old rollout-based repository for now
- const postgresGroupRepository = new PostgresGroupRepository(this.postgres!)
- const groupRepository = buildGroupRepository(
- personhogClient,
- postgresGroupRepository,
- this.config.PERSONHOG_GROUPS_ROLLOUT_PERCENTAGE,
- this.config.PERSONHOG_GROUPS_ROLLOUT_TEAM_IDS,
- clientLabel
- )
+ const groupRepository = new PersonHogGroupReadRepository(personhogClient, clientLabel)
const encryptedFields = new EncryptedFields(this.config.ENCRYPTION_SALT_KEYS)
const integrationManager = new IntegrationManagerService(this.pubsub!, this.postgres!, encryptedFields)
diff --git a/nodejs/src/worker/ingestion/groups/repositories/group-repository.interface.ts b/nodejs/src/worker/ingestion/groups/repositories/group-repository.interface.ts
index a73104d6e848..951ac7ea4288 100644
--- a/nodejs/src/worker/ingestion/groups/repositories/group-repository.interface.ts
+++ b/nodejs/src/worker/ingestion/groups/repositories/group-repository.interface.ts
@@ -12,6 +12,38 @@ import {
} from '../../../../types'
import { GroupRepositoryTransaction } from './group-repository-transaction.interface'
+/**
+ * Read-only group lookups backed by personhog gRPC. Used by services that
+ * only need to fetch group data (CDP). Always uses eventual consistency.
+ * Independent of GroupRepository — the two interfaces have different
+ * parameter shapes reflecting their different backends and consumers.
+ */
+export interface GroupReadRepository {
+ fetchGroupsByKeys(
+ teamIds: TeamId[],
+ groupTypeIndexes: GroupTypeIndex[],
+ groupKeys: string[],
+ callerTag?: string
+ ): Promise<
+ {
+ team_id: TeamId
+ group_type_index: GroupTypeIndex
+ group_key: string
+ group_properties: Record<string, any>
+ }[]
+ >
+
+ fetchGroupTypesByTeamIds(
+ teamIds: TeamId[],
+ callerTag?: string
+ ): Promise<Record<string, { group_type: string; group_type_index: GroupTypeIndex }[]>>
+}
+
+/**
+ * Full group repository with read and write operations. Used by the
+ * ingestion pipeline which creates, updates, and manages groups.
+ * Postgres-backed with support for consistency control and row locking.
+ */
export interface GroupRepository {
fetchGroup(
teamId: TeamId,
diff --git a/nodejs/tests/helpers/cdp.ts b/nodejs/tests/helpers/cdp.ts
index 15ccbe1c992d..375b5b1c4c1d 100644
--- a/nodejs/tests/helpers/cdp.ts
+++ b/nodejs/tests/helpers/cdp.ts
@@ -12,6 +12,7 @@ import { InternalCaptureService } from '../../src/common/services/internal-captu
import { KafkaProducerRegistry } from '../../src/ingestion/outputs/kafka-producer-registry'
import { KafkaProducerWrapper } from '../../src/kafka/producer'
import { Hub } from '../../src/types'
+import { GroupReadRepository } from '../../src/worker/ingestion/groups/repositories/group-repository.interface'
import { PersonReadRepository } from '../../src/worker/ingestion/persons/repositories/person-repository'
/**
@@ -32,9 +33,14 @@ function buildTestCdpProducerRegistry(
}
/**
- * No-op PersonReadRepository for tests that don't exercise person lookups.
- * Tests that need person resolution should override via spread.
+ * No-op read repositories for tests that don't exercise person/group lookups.
+ * Tests that need real resolution should override via spread.
*/
+const noopGroupReadRepository: GroupReadRepository = {
+ fetchGroupsByKeys: () => Promise.resolve([]),
+ fetchGroupTypesByTeamIds: () => Promise.resolve({}),
+}
+
const noopPersonReadRepository: PersonReadRepository = {
fetchPerson: () => Promise.resolve(undefined),
fetchPersonsByDistinctIds: () => Promise.resolve([]),
@@ -53,7 +59,7 @@ export function createCdpConsumerDeps(hub: Hub, kafkaProducer?: KafkaProducerWra
internalCaptureService: new InternalCaptureService(hub),
personRepository: noopPersonReadRepository,
geoipService: hub.geoipService,
- groupRepository: hub.groupRepository,
+ groupRepository: noopGroupReadRepository,
quotaLimiting: hub.quotaLimiting,
}
}