: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(personhog): create read only personhog repository (#60990)
Zach Brownc9bb592af25a
diff --git a/nodejs/src/cdp/consumers/cdp-base.consumer.ts b/nodejs/src/cdp/consumers/cdp-base.consumer.tsindex d88de1b75bf3..e8b1a4ecb27b 100644--- a/nodejs/src/cdp/consumers/cdp-base.consumer.ts+++ b/nodejs/src/cdp/consumers/cdp-base.consumer.ts@@ -6,7 +6,7 @@ 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 { PersonRepository } from '../../worker/ingestion/persons/repositories/person-repository'+import { PersonReadRepository } from '../../worker/ingestion/persons/repositories/person-repository'import {CdpCoreServicesConfig,CdpCoreServicesDeps,@@ -39,7 +39,7 @@ export type CdpConsumerBaseConfig = CdpCoreServicesConfig &Pick<CdpConfig, 'CDP_OVERFLOW_QUEUE_ENABLED'>export interface CdpConsumerBaseDeps extends CdpCoreServicesDeps {- personRepository: PersonRepository+ personRepository: PersonReadRepositorygeoipService: GeoIPServicegroupRepository: GroupRepositoryquotaLimiting: QuotaLimitingdiff --git a/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow-personhog.test.ts b/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow-personhog.test.tsindex b283ed1c0c2d..511565710bba 100644--- a/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow-personhog.test.ts+++ b/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow-personhog.test.ts@@ -5,10 +5,8 @@ import { DateTime } from 'luxon'import { HogFlow } from '~/schema/hogflow'import { createCdpConsumerDeps } from '~/tests/helpers/cdp'import { getFirstTeam, resetTestDatabase } from '~/tests/helpers/sql'-import { PostgresPersonRepository } from '~/worker/ingestion/persons/repositories/postgres-person-repository'+import { PersonReadRepository } from '~/worker/ingestion/persons/repositories/person-repository'-import { PersonHogClient } from '../../ingestion/personhog/client'-import { PersonHogPersonRepository } from '../../ingestion/personhog/personhog-person-repository'import { Hub, InternalPerson, Team } from '../../types'import { closeHub, createHub } from '../../utils/db/hub'import { UUIDT } from '../../utils/utils'@@ -24,24 +22,38 @@ import { CdpCyclotronWorkerHogFlow } from './cdp-cyclotron-worker-hogflow.consumjest.setTimeout(1000)-type MockPersonHogClient = {- groups: jest.Mocked<- Pick<- PersonHogClient['groups'],- 'fetchGroup' | 'fetchGroupsByKeys' | 'fetchGroupTypesByTeamIds' | 'fetchGroupTypesByProjectIds'- >- >- persons: jest.Mocked<- Pick<- PersonHogClient['persons'],- 'fetchPersonsByDistinctIds' | 'fetchPersonsByPersonIds' | 'getDistinctIdsForPersons'- >- >+const TIMESTAMP = DateTime.fromISO('2000-10-14T11:42:06.502Z').toUTC()++function makePerson(teamId: number, uuid: string, distinctId: string, properties: Record<string, any>): InternalPerson {+ return {+ id: '42',+ uuid,+ team_id: teamId,+ properties,+ properties_last_updated_at: {},+ properties_last_operation: {},+ created_at: TIMESTAMP,+ version: 1,+ is_identified: true,+ is_user_id: null,+ last_seen_at: null,+ }+}++function createMockPersonReadRepository(+ overrides: Partial<jest.Mocked<PersonReadRepository>> = {}+): jest.Mocked<PersonReadRepository> {+ return {+ fetchPerson: jest.fn().mockResolvedValue(undefined),+ fetchPersonsByDistinctIds: jest.fn().mockResolvedValue([]),+ fetchPersonsByPersonIds: jest.fn().mockResolvedValue([]),+ fetchDistinctIdsForPersons: jest.fn().mockResolvedValue({}),+ ...overrides,+ }}describe('CdpCyclotronWorkerHogFlow with PersonHog', () => {let hub: Hub- let postgresPersonRepo: PostgresPersonRepositorylet team: Teamlet hogFlow: HogFlow@@ -60,26 +72,9 @@ describe('CdpCyclotronWorkerHogFlow with PersonHog', () => {}}- const createPerson = async (- teamId: number,- uuid: string,- distinctId: string,- properties: any- ): Promise<InternalPerson> => {- const TIMESTAMP = DateTime.fromISO('2000-10-14T11:42:06.502Z').toUTC()- const result = await postgresPersonRepo.createPerson(TIMESTAMP, properties, {}, {}, teamId, null, true, uuid, {- distinctId,- })- if (!result.success) {- throw new Error('Failed to create person')- }- return result.person- }-beforeEach(async () => {await resetTestDatabase()hub = await createHub()- postgresPersonRepo = new PostgresPersonRepository(hub.postgres)team = await getFirstTeam(hub.postgres)hogFlow = await insertHogFlow(@@ -98,36 +93,19 @@ describe('CdpCyclotronWorkerHogFlow with PersonHog', () => {await closeHub(hub)})- it('falls back to postgres and resolves person when gRPC is unavailable', async () => {- await createPerson(team.id, 'dd3d6f80-60ad-45c3-bd61-e2300f2ba7e1', 'distinct_A_1', {+ it('resolves person by distinct_id via personhog', async () => {+ const person = makePerson(team.id, 'dd3d6f80-60ad-45c3-bd61-e2300f2ba7e1', 'distinct_A_1', {name: 'Person A 1',})- const failingGrpc: MockPersonHogClient = {- groups: {- fetchGroup: jest.fn(),- fetchGroupsByKeys: jest.fn(),- fetchGroupTypesByTeamIds: jest.fn(),- fetchGroupTypesByProjectIds: jest.fn(),- },- persons: {- fetchPersonsByDistinctIds: jest.fn().mockRejectedValue(new Error('gRPC unavailable')),- fetchPersonsByPersonIds: jest.fn().mockRejectedValue(new Error('gRPC unavailable')),- getDistinctIdsForPersons: jest.fn().mockRejectedValue(new Error('gRPC unavailable')),- },- }+ const mockRepo = createMockPersonReadRepository({+ fetchPersonsByDistinctIds: jest.fn().mockResolvedValue([{ ...person, distinct_id: 'distinct_A_1' }]),+ })- const personhogRepo = new PersonHogPersonRepository(- postgresPersonRepo,- failingGrpc as unknown as PersonHogClient,- 100,- new Set(),- 'test'- )const mockJobQueue = createMockJobQueue()const processor = new CdpCyclotronWorkerHogFlow(hub,- { ...createCdpConsumerDeps(hub), personRepository: personhogRepo },+ { ...createCdpConsumerDeps(hub), personRepository: mockRepo },mockJobQueue)@@ -143,43 +121,27 @@ describe('CdpCyclotronWorkerHogFlow with PersonHog', () => {expect(results).toHaveLength(1)expect(results[0].invocation.person?.properties).toEqual({ name: 'Person A 1' })-- // gRPC was attempted and failed- expect(failingGrpc.persons.fetchPersonsByDistinctIds).toHaveBeenCalled()+ expect(mockRepo.fetchPersonsByDistinctIds).toHaveBeenCalled()})- it('falls back to postgres for personId lookups when gRPC fails', async () => {+ it('resolves person by personId via personhog', async () => {const personUuid = 'dd3d6f80-60ad-45c3-bd61-e2300f2ba7e1'- await createPerson(team.id, personUuid, 'distinct_A_1', {+ const person = makePerson(team.id, personUuid, 'distinct_A_1', {name: 'Batch Person',})- const failingGrpc: MockPersonHogClient = {- groups: {- fetchGroup: jest.fn(),- fetchGroupsByKeys: jest.fn(),- fetchGroupTypesByTeamIds: jest.fn(),- fetchGroupTypesByProjectIds: jest.fn(),- },- persons: {- fetchPersonsByDistinctIds: jest.fn().mockRejectedValue(new Error('gRPC unavailable')),- fetchPersonsByPersonIds: jest.fn().mockRejectedValue(new Error('gRPC unavailable')),- getDistinctIdsForPersons: jest.fn().mockRejectedValue(new Error('gRPC unavailable')),- },- }+ const mockRepo = createMockPersonReadRepository({+ fetchPersonsByPersonIds: jest.fn().mockResolvedValue([person]),+ fetchDistinctIdsForPersons: jest.fn().mockResolvedValue({+ [person.id]: ['distinct_A_1'],+ }),+ })- const personhogRepo = new PersonHogPersonRepository(- postgresPersonRepo,- failingGrpc as unknown as PersonHogClient,- 100,- new Set(),- 'test'- )- const mockJobQueue2 = createMockJobQueue()+ const mockJobQueue = createMockJobQueue()const processor = new CdpCyclotronWorkerHogFlow(hub,- { ...createCdpConsumerDeps(hub), personRepository: personhogRepo },- mockJobQueue2+ { ...createCdpConsumerDeps(hub), personRepository: mockRepo },+ mockJobQueue)const invocations = [@@ -195,14 +157,29 @@ describe('CdpCyclotronWorkerHogFlow with PersonHog', () => {expect(results).toHaveLength(1)expect(results[0].invocation.person?.properties).toEqual({ name: 'Batch Person' })-- // gRPC was attempted for personId lookup- expect(failingGrpc.persons.fetchPersonsByPersonIds).toHaveBeenCalled()-- // The resolved person carries a distinct_id, and the worker backfills it onto- // event.distinct_id so capture-based hog templates (defaulting to {event.distinct_id})- // route to the existing person instead of creating a new one.expect(results[0].invocation.person?.distinct_id).toBe('distinct_A_1')expect(results[0].invocation.state.event.distinct_id).toBe('distinct_A_1')+ expect(mockRepo.fetchPersonsByPersonIds).toHaveBeenCalled()+ })++ it('propagates error when personhog is unavailable', async () => {+ const mockRepo = createMockPersonReadRepository({+ fetchPersonsByDistinctIds: jest.fn().mockRejectedValue(new Error('gRPC unavailable')),+ })++ const mockJobQueue = createMockJobQueue()+ const processor = new CdpCyclotronWorkerHogFlow(+ hub,+ { ...createCdpConsumerDeps(hub), personRepository: mockRepo },+ mockJobQueue+ )++ const invocations = [+ createSerializedHogFlowInvocation(hogFlow, {+ event: { distinct_id: 'distinct_A_1', properties: { foo: 'bar' } } as any,+ }),+ ]++ await expect(processor.processInvocations(invocations)).rejects.toThrow('gRPC unavailable')})})diff --git a/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow.test.ts b/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow.test.tsindex cf4961950401..2c7d5c4b7a19 100644--- a/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow.test.ts+++ b/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow.test.ts@@ -7,7 +7,10 @@ import { createCdpConsumerDeps } from '~/tests/helpers/cdp'import { createTeam, getFirstTeam, getTeam, resetTestDatabase } from '~/tests/helpers/sql'import { PostgresUse } from '~/utils/db/postgres'import { UUIDT } from '~/utils/utils'-import { PostgresPersonRepository } from '~/worker/ingestion/persons/repositories/postgres-person-repository'+import {+ InternalPersonWithDistinctId,+ PersonReadRepository,+} from '~/worker/ingestion/persons/repositories/person-repository'import { Hub, InternalPerson, Team } from '../../types'import { closeHub, createHub } from '../../utils/db/hub'@@ -23,10 +26,68 @@ import { CdpCyclotronWorkerHogFlow } from './cdp-cyclotron-worker-hogflow.consumjest.setTimeout(1000)+const TIMESTAMP = DateTime.fromISO('2000-10-14T11:42:06.502Z').toUTC()++type TestPerson = {+ id: string+ uuid: string+ teamId: number+ distinctId: string+ properties: Record<string, any>+}++function toInternalPerson(p: TestPerson): InternalPerson {+ return {+ id: p.id,+ uuid: p.uuid,+ team_id: p.teamId,+ properties: p.properties,+ properties_last_updated_at: {},+ properties_last_operation: null,+ created_at: TIMESTAMP,+ version: 1,+ is_identified: true,+ is_user_id: null,+ last_seen_at: null,+ }+}++function createMockPersonReadRepository(persons: TestPerson[]): jest.Mocked<PersonReadRepository> {+ return {+ fetchPerson: jest.fn().mockImplementation((teamId: number, distinctId: string) => {+ const match = persons.find((p) => p.teamId === teamId && p.distinctId === distinctId)+ return Promise.resolve(match ? toInternalPerson(match) : undefined)+ }),+ fetchPersonsByDistinctIds: jest+ .fn()+ .mockImplementation((teamPersons: { teamId: number; distinctId: string }[]) => {+ const results: InternalPersonWithDistinctId[] = persons+ .filter((p) => teamPersons.some((tp) => tp.teamId === p.teamId && tp.distinctId === p.distinctId))+ .map((p) => ({ ...toInternalPerson(p), distinct_id: p.distinctId }))+ return Promise.resolve(results)+ }),+ fetchPersonsByPersonIds: jest.fn().mockImplementation((teamPersons: { teamId: number; personId: string }[]) => {+ const results: InternalPerson[] = persons+ .filter((p) => teamPersons.some((tp) => tp.teamId === p.teamId && tp.personId === p.uuid))+ .map(toInternalPerson)+ return Promise.resolve(results)+ }),+ fetchDistinctIdsForPersons: jest.fn().mockImplementation((teamId: number, personIntIds: string[]) => {+ const result: Record<string, string[]> = {}+ for (const intId of personIntIds) {+ const match = persons.find((p) => p.teamId === teamId && p.id === intId)+ if (match) {+ result[intId] = [match.distinctId]+ }+ }+ return Promise.resolve(result)+ }),+ }+}+describe('CdpCyclotronWorkerHogFlow', () => {let processor: CdpCyclotronWorkerHogFlowlet hub: Hub- let personRepository: PostgresPersonRepositorylet team: Teamlet team2: Teamlet hogFlows: HogFlow[]@@ -35,8 +96,6 @@ describe('CdpCyclotronWorkerHogFlow', () => {hogFlow: HogFlow,_context: Partial<HogFlowInvocationContext> = {}): CyclotronJobInvocation => {- // Add the source of the trigger to the globals-const context = createHogFlowInvocationContext(_context)return {@@ -51,32 +110,65 @@ describe('CdpCyclotronWorkerHogFlow', () => {}}- const createPerson = async (- teamId: number,- uuid: string,- distinctId: string,- properties: any- ): Promise<InternalPerson> => {- const TIMESTAMP = DateTime.fromISO('2000-10-14T11:42:06.502Z').toUTC()- const result = await personRepository.createPerson(TIMESTAMP, properties, {}, {}, teamId, null, true, uuid, {- distinctId,- })- if (!result.success) {- throw new Error('Failed to create person')- }- return result.person- }-beforeEach(async () => {await resetTestDatabase()hub = await createHub()- personRepository = new PostgresPersonRepository(hub.postgres)team = await getFirstTeam(hub.postgres)const team2Id = await createTeam(hub.postgres, team.organization_id)team2 = (await getTeam(hub.postgres, team2Id))!+ const testPersons: TestPerson[] = [+ {+ id: '1',+ uuid: 'dd3d6f80-60ad-45c3-bd61-e2300f2ba7e1',+ teamId: team.id,+ distinctId: 'distinct_A_1',+ properties: { name: 'Person A 1' },+ },+ {+ id: '2',+ uuid: 'dd3d6f80-60ad-45c3-bd61-e2300f2ba7e2',+ teamId: team.id,+ distinctId: 'distinct_A_2',+ properties: { name: 'Person A 2' },+ },+ {+ id: '3',+ uuid: 'dd3d6f80-60ad-45c3-bd61-e2300f2ba7e3',+ teamId: team2.id,+ distinctId: 'distinct_A_1',+ properties: { name: 'Person A 3' },+ },+ {+ id: '4',+ uuid: 'dd3d6f80-60ad-45c3-bd61-e2300f2ba7f0',+ teamId: team.id,+ distinctId: 'distinct_batch_1',+ properties: { name: 'Batch Person', email: '[email protected]' },+ },+ {+ id: '5',+ uuid: 'dd3d6f80-60ad-45c3-bd61-e2300f2ba7e4',+ teamId: team.id,+ distinctId: 'distinct_person_1',+ properties: { name: 'Person 1' },+ },+ {+ id: '6',+ uuid: 'dd3d6f80-60ad-45c3-bd61-e2300f2ba7e5',+ teamId: team.id,+ distinctId: 'distinct_person_2',+ properties: { name: 'Person 2' },+ },+ ]++ const mockRepo = createMockPersonReadRepository(testPersons)const mockJobQueue = createMockJobQueue()- processor = new CdpCyclotronWorkerHogFlow(hub, createCdpConsumerDeps(hub), mockJobQueue)+ processor = new CdpCyclotronWorkerHogFlow(+ hub,+ { ...createCdpConsumerDeps(hub), personRepository: mockRepo },+ mockJobQueue+ )hogFlows = []hogFlows.push(@@ -112,17 +204,7 @@ describe('CdpCyclotronWorkerHogFlow', () => {describe('loadHogFlows', () => {let invocations: CyclotronJobInvocation[]- beforeEach(async () => {- await createPerson(team.id, 'dd3d6f80-60ad-45c3-bd61-e2300f2ba7e1', 'distinct_A_1', {- name: 'Person A 1',- })- await createPerson(team.id, 'dd3d6f80-60ad-45c3-bd61-e2300f2ba7e2', 'distinct_A_2', {- name: 'Person A 2',- })- await createPerson(team2.id, 'dd3d6f80-60ad-45c3-bd61-e2300f2ba7e3', 'distinct_A_1', {- name: 'Person A 3',- })-+ beforeEach(() => {const invocation1 = createSerializedHogFlowInvocation(hogFlows[0], {event: {distinct_id: 'distinct_A_1',@@ -255,10 +337,6 @@ describe('CdpCyclotronWorkerHogFlow', () => {it('should resolve person by personId when distinct_id is empty (batch invocations)', async () => {const personUuid = 'dd3d6f80-60ad-45c3-bd61-e2300f2ba7f0'- await createPerson(team.id, personUuid, 'distinct_batch_1', {- name: 'Batch Person',- email: '[email protected]',- })// Batch invocations set distinct_id: '' and use personId insteadconst invocation = createSerializedHogFlowInvocation(hogFlows[0], {@@ -282,18 +360,8 @@ describe('CdpCyclotronWorkerHogFlow', () => {})it('should skip invocations when workflow is disabled after being queued', async () => {- // Scenario: workflow is active, invocations are queued, then workflow is disabled- // Remaining invocations should be skipped-const hogFlow = hogFlows[0]- await createPerson(team.id, 'dd3d6f80-60ad-45c3-bd61-e2300f2ba7e4', 'distinct_person_1', {- name: 'Person 1',- })- await createPerson(team.id, 'dd3d6f80-60ad-45c3-bd61-e2300f2ba7e5', 'distinct_person_2', {- name: 'Person 2',- })-const invocation1 = createSerializedHogFlowInvocation(hogFlow, {event: {distinct_id: 'distinct_person_1',diff --git a/nodejs/src/cdp/rerun/rerun-e2e.test.ts b/nodejs/src/cdp/rerun/rerun-e2e.test.tsindex 2ff3c1d6c0fc..16fe1894bced 100644--- a/nodejs/src/cdp/rerun/rerun-e2e.test.ts+++ b/nodejs/src/cdp/rerun/rerun-e2e.test.ts@@ -11,15 +11,15 @@ import { Clickhouse } from '~/tests/helpers/clickhouse'import { waitForExpect } from '~/tests/helpers/expectations'import { ensureKafkaTopics, resetKafka } from '~/tests/helpers/kafka'import { getFirstTeam, resetTestDatabase } from '~/tests/helpers/sql'-import { PostgresPersonRepository } from '~/worker/ingestion/persons/repositories/postgres-person-repository'+import { PersonReadRepository } from '~/worker/ingestion/persons/repositories/person-repository'import { KAFKA_HOG_INVOCATION_RESULTS, KAFKA_INGESTION_WARNINGS } from '../../config/kafka-topics'import { KafkaProducerWrapper } from '../../kafka/producer'import { Hub, Team } from '../../types'import { closeHub, createHub } from '../../utils/db/hub'-import { UUIDT } from '../../utils/utils'import { HOG_FILTERS_EXAMPLES, HOG_INPUTS_EXAMPLES } from '../_tests/examples'import { insertHogFunction as _insertHogFunction, createHogExecutionGlobals } from '../_tests/fixtures'+import { CdpConsumerBaseDeps } from '../consumers/cdp-base.consumer'import { CdpCyclotronWorker } from '../consumers/cdp-cyclotron-worker.consumer'import { CdpEventsConsumer } from '../consumers/cdp-events.consumer'import { CdpRerunWorkerConsumer } from '../consumers/cdp-rerun-worker.consumer'@@ -133,6 +133,7 @@ describe('CDP hog invocation rerun e2e', () => {let postgresV2Queue: CyclotronJobQueuePostgresV2let nodeAssertPool: Poollet clickhouse: Clickhouse+ let cdpDeps: CdpConsumerBaseDepsbeforeAll(() => {clickhouse = Clickhouse.create()@@ -164,19 +165,29 @@ describe('CDP hog invocation rerun e2e', () => {team = await getFirstTeam(hub.postgres)// The rerun strips `person` from invocation_globals — the cyclotron- // worker reloads it via getCyclotronPerson(distinct_id). Seed a real+ // worker reloads it via getCyclotronPerson(distinct_id). Provide a mock// person so the rerun can resolve `{person}` in the function's inputs.- await new PostgresPersonRepository(hub.postgres).createPerson(- DateTime.now(),- { email: '[email protected]' },- {},- {},- team.id,- null,- true,- new UUIDT().toString(),- { distinctId: 'distinct_id' }- )+ const mockPersonRepo: jest.Mocked<PersonReadRepository> = {+ fetchPerson: jest.fn().mockResolvedValue(undefined),+ fetchPersonsByDistinctIds: jest.fn().mockResolvedValue([+ {+ id: '1',+ uuid: 'dd3d6f80-60ad-45c3-bd61-e2300f2ba7e1',+ team_id: team.id,+ properties: { email: '[email protected]' },+ properties_last_updated_at: {},+ properties_last_operation: null,+ created_at: DateTime.utc(),+ version: 1,+ is_identified: true,+ is_user_id: null,+ last_seen_at: null,+ distinct_id: 'distinct_id',+ },+ ]),+ fetchPersonsByPersonIds: jest.fn().mockResolvedValue([]),+ fetchDistinctIdsForPersons: jest.fn().mockResolvedValue({}),+ }mockProducerObserver.resetKafkaProducer()@@ -212,7 +223,9 @@ describe('CDP hog invocation rerun e2e', () => {kafkaQueue = new CyclotronJobQueueKafka(hub.KAFKA_CLIENT_RACK, hub, hub.CONSUMER_BATCH_SIZE)postgresV2Queue = new CyclotronJobQueuePostgresV2(hub.CONSUMER_BATCH_SIZE, hub)- eventsConsumer = new CdpEventsConsumer(hub, createCdpConsumerDeps(hub, kafkaProducer), {+ cdpDeps = { ...createCdpConsumerDeps(hub, kafkaProducer), personRepository: mockPersonRepo }++ eventsConsumer = new CdpEventsConsumer(hub, cdpDeps, {hogQueue: kafkaQueue,hogflowQueue: postgresV2Queue,})@@ -226,7 +239,7 @@ describe('CDP hog invocation rerun e2e', () => {} as anyawait eventsConsumer.start()- cyclotronWorker = new CdpCyclotronWorker(hub, createCdpConsumerDeps(hub, kafkaProducer), kafkaQueue)+ cyclotronWorker = new CdpCyclotronWorker(hub, cdpDeps, kafkaQueue)await cyclotronWorker.start()rerunManager = new RerunJobManager({ dbUrl: NODE_DB_URL, maxCount: 10000 })@@ -327,7 +340,7 @@ describe('CDP hog invocation rerun e2e', () => {// ── 3. Rerun worker drains the wrapper job ────────────────────────────────rerunWorker = new CdpRerunWorkerConsumer({ ...hub, CDP_CYCLOTRON_JOB_QUEUE_CONSUMER_MODE: 'postgres' },- createCdpConsumerDeps(hub, kafkaProducer),+ cdpDeps,{ hog_function: kafkaQueue, hog_flow: postgresV2Queue })await rerunWorker.start()diff --git a/nodejs/src/cdp/services/managers/persons-manager-personhog.test.ts b/nodejs/src/cdp/services/managers/persons-manager-personhog.test.tsdeleted file mode 100644index d4f240dfacc4..000000000000--- a/nodejs/src/cdp/services/managers/persons-manager-personhog.test.ts+++ /dev/null@@ -1,364 +0,0 @@-import { DateTime } from 'luxon'--import {- InternalPersonWithDistinctId,- PersonRepository,-} from '~/worker/ingestion/persons/repositories/person-repository'--import { PersonHogClient } from '../../../ingestion/personhog/client'-import { PersonHogPersonRepository } from '../../../ingestion/personhog/personhog-person-repository'-import { InternalPerson, TeamId } from '../../../types'-import { PersonsManagerService } from './persons-manager.service'--jest.mock('../../../utils/logger')--const TEAM_1 = 1 as TeamId-const TEAM_2 = 2 as TeamId--type MockPersonHogClient = {- groups: jest.Mocked<- Pick<- PersonHogClient['groups'],- 'fetchGroup' | 'fetchGroupsByKeys' | 'fetchGroupTypesByTeamIds' | 'fetchGroupTypesByProjectIds'- >- >- persons: jest.Mocked<- Pick<- PersonHogClient['persons'],- 'fetchPersonsByDistinctIds' | 'fetchPersonsByPersonIds' | 'getDistinctIdsForPersons'- >- >-}--function createMockPostgres(persons: Record<string, any>[]): jest.Mocked<PersonRepository> {- const mock: jest.Mocked<PersonRepository> = {- fetchPerson: jest.fn(),- fetchPersonsByDistinctIds: jest.fn(),- fetchPersonsByPersonIds: jest.fn(),- fetchDistinctIdsForPersons: jest.fn(),- createPerson: jest.fn(),- updatePerson: jest.fn(),- updatePersonAssertVersion: jest.fn(),- updatePersonsBatch: jest.fn(),- deletePerson: jest.fn(),- addDistinctId: jest.fn(),- addPersonlessDistinctId: jest.fn(),- addPersonlessDistinctIdForMerge: jest.fn(),- addPersonlessDistinctIdsBatch: jest.fn(),- personPropertiesSize: jest.fn(),- updateCohortsAndFeatureFlagsForMerge: jest.fn(),- inTransaction: jest.fn(),- }-- mock.fetchDistinctIdsForPersons.mockImplementation((teamId, personIntIds) => {- const result: Record<string, string[]> = {}- for (const intId of personIntIds) {- const match = persons.find((p) => p.team_id === teamId && p.id === intId && p.distinct_id)- if (match) {- result[intId] = [match.distinct_id]- }- }- return Promise.resolve(result)- })-- mock.fetchPersonsByDistinctIds.mockImplementation((teamPersons) => {- const results = persons.filter((p) =>- teamPersons.some(- (tp: { teamId: number; distinctId: string }) =>- tp.teamId === p.team_id && tp.distinctId === p.distinct_id- )- )- return Promise.resolve(results as InternalPersonWithDistinctId[])- })-- mock.fetchPersonsByPersonIds.mockImplementation((teamPersons) => {- const results = persons.filter((p) =>- teamPersons.some(- (tp: { teamId: number; personId: string }) => tp.teamId === p.team_id && tp.personId === p.uuid- )- )- return Promise.resolve(results as InternalPerson[])- })-- return mock-}--function createMockGrpcClient(persons: Record<string, any>[]): MockPersonHogClient {- return {- groups: {- fetchGroup: jest.fn(),- fetchGroupsByKeys: jest.fn(),- fetchGroupTypesByTeamIds: jest.fn(),- fetchGroupTypesByProjectIds: jest.fn(),- },- persons: {- fetchPersonsByDistinctIds: jest- .fn()- .mockImplementation((teamPersons: { teamId: number; distinctId: string }[]) => {- const results = persons.filter((p) =>- teamPersons.some((tp) => tp.teamId === p.team_id && tp.distinctId === p.distinct_id)- )- return Promise.resolve(results as InternalPersonWithDistinctId[])- }),- fetchPersonsByPersonIds: jest- .fn()- .mockImplementation((teamPersons: { teamId: number; personId: string }[]) => {- const results = persons.filter((p) =>- teamPersons.some((tp) => tp.teamId === p.team_id && tp.personId === p.uuid)- )- return Promise.resolve(results as InternalPerson[])- }),- getDistinctIdsForPersons: jest.fn().mockImplementation((teamId: number, personIntIds: string[]) => {- const result: Record<string, string[]> = {}- for (const intId of personIntIds) {- const match = persons.find((p) => p.team_id === teamId && p.id === intId && p.distinct_id)- if (match) {- result[intId] = [match.distinct_id]- }- }- return Promise.resolve(result)- }),- },- }-}--const MOCK_PERSONS = [- {- id: '1',- uuid: 'aaaaaaaa-0000-0000-0000-000000000001',- team_id: TEAM_1,- properties: { name: 'Alice', email: '[email protected]' },- properties_last_updated_at: {},- properties_last_operation: null,- created_at: DateTime.fromISO('2024-01-01T00:00:00Z', { zone: 'utc' }),- version: 1,- is_identified: true,- is_user_id: null,- last_seen_at: null,- distinct_id: 'alice-distinct',- },- {- id: '2',- uuid: 'aaaaaaaa-0000-0000-0000-000000000002',- team_id: TEAM_1,- properties: { name: 'Bob' },- properties_last_updated_at: {},- properties_last_operation: null,- created_at: DateTime.fromISO('2024-01-01T00:00:00Z', { zone: 'utc' }),- version: 1,- is_identified: true,- is_user_id: null,- last_seen_at: null,- distinct_id: 'bob-distinct',- },- {- id: '3',- uuid: 'aaaaaaaa-0000-0000-0000-000000000003',- team_id: TEAM_2,- properties: { name: 'Alice Team 2' },- properties_last_updated_at: {},- properties_last_operation: null,- created_at: DateTime.fromISO('2024-01-01T00:00:00Z', { zone: 'utc' }),- version: 1,- is_identified: true,- is_user_id: null,- last_seen_at: null,- distinct_id: 'alice-distinct',- },-]--describe('PersonsManagerService + PersonHogPersonRepository integration', () => {- jest.setTimeout(1000)-- const mockTeamManager = {- getTeam: jest.fn().mockImplementation((teamId: number) =>- Promise.resolve({- id: teamId,- uuid: `team-uuid-${teamId}`,- organization_id: 'org-1',- person_display_name_properties: [],- })- ),- hasAvailableFeature: jest.fn().mockResolvedValue(true),- } as any-- describe.each([- ['postgres (rollout 0%)', 0],- ['grpc (rollout 100%)', 100],- ])('%s', (_label, rolloutPercentage) => {- let mockPostgres: jest.Mocked<PersonRepository>- let mockGrpc: MockPersonHogClient- let manager: PersonsManagerService-- beforeEach(() => {- jest.restoreAllMocks()- mockPostgres = createMockPostgres(MOCK_PERSONS)- mockGrpc = createMockGrpcClient(MOCK_PERSONS)-- const personhogRepo = new PersonHogPersonRepository(- mockPostgres,- mockGrpc as unknown as PersonHogClient,- rolloutPercentage,- new Set(),- 'test'- )- manager = new PersonsManagerService(mockTeamManager, personhogRepo, 'http://localhost:8000')- })-- it('looks up person by distinct_id', async () => {- const result = await manager.getCyclotronPerson(TEAM_1, 'alice-distinct', 'distinct_id')-- expect(result).toEqual({- id: MOCK_PERSONS[0].uuid,- properties: { name: 'Alice', email: '[email protected]' },- name: 'alice-distinct',- url: `http://localhost:8000/project/${TEAM_1}/person/alice-distinct`,- distinct_id: 'alice-distinct',- })-- if (rolloutPercentage === 100) {- expect(mockGrpc.persons.fetchPersonsByDistinctIds).toHaveBeenCalled()- } else {- expect(mockPostgres.fetchPersonsByDistinctIds).toHaveBeenCalled()- }- })-- it('looks up person by person_id and resolves a distinct_id', async () => {- const result = await manager.getCyclotronPerson(TEAM_1, MOCK_PERSONS[0].uuid, 'person_id')-- // The distinct_id field is what makes batch-triggered workflows able to use- // {event.distinct_id} downstream — without it, capture-based templates would- // create a new profile instead of updating the existing one.- expect(result).toEqual({- id: MOCK_PERSONS[0].uuid,- properties: { name: 'Alice', email: '[email protected]' },- name: MOCK_PERSONS[0].uuid,- url: `http://localhost:8000/project/${TEAM_1}/person/${MOCK_PERSONS[0].uuid}`,- distinct_id: 'alice-distinct',- })-- if (rolloutPercentage === 100) {- expect(mockGrpc.persons.fetchPersonsByPersonIds).toHaveBeenCalled()- expect(mockGrpc.persons.getDistinctIdsForPersons).toHaveBeenCalledWith(TEAM_1, ['1'], 1)- } else {- expect(mockPostgres.fetchPersonsByPersonIds).toHaveBeenCalled()- expect(mockPostgres.fetchDistinctIdsForPersons).toHaveBeenCalledWith(TEAM_1, ['1'], {- limitPerPerson: 1,- })- }- })-- it('returns null for nonexistent person', async () => {- const result = await manager.getCyclotronPerson(TEAM_1, 'nonexistent', 'distinct_id')-- expect(result).toBeNull()- })-- it('isolates persons by team', async () => {- const team1Result = await manager.getCyclotronPerson(TEAM_1, 'alice-distinct', 'distinct_id')- manager.clear()- const team2Result = await manager.getCyclotronPerson(TEAM_2, 'alice-distinct', 'distinct_id')-- expect(team1Result!.properties).toEqual({ name: 'Alice', email: '[email protected]' })- expect(team2Result!.properties).toEqual({ name: 'Alice Team 2' })- })- })-- describe('grpc fallback to postgres on error', () => {- let mockPostgres: jest.Mocked<PersonRepository>- let mockGrpc: MockPersonHogClient- let manager: PersonsManagerService-- beforeEach(() => {- jest.restoreAllMocks()- mockPostgres = createMockPostgres(MOCK_PERSONS)- mockGrpc = createMockGrpcClient(MOCK_PERSONS)-- const personhogRepo = new PersonHogPersonRepository(- mockPostgres,- mockGrpc as unknown as PersonHogClient,- 100,- new Set(),- 'test'- )- manager = new PersonsManagerService(mockTeamManager, personhogRepo, 'http://localhost:8000')- })-- it('falls back to postgres when gRPC fetchPersonsByDistinctIds fails', async () => {- mockGrpc.persons.fetchPersonsByDistinctIds.mockRejectedValue(new Error('connection refused'))-- const result = await manager.getCyclotronPerson(TEAM_1, 'alice-distinct', 'distinct_id')-- expect(result).toEqual({- id: MOCK_PERSONS[0].uuid,- properties: { name: 'Alice', email: '[email protected]' },- name: 'alice-distinct',- url: `http://localhost:8000/project/${TEAM_1}/person/alice-distinct`,- distinct_id: 'alice-distinct',- })-- expect(mockGrpc.persons.fetchPersonsByDistinctIds).toHaveBeenCalled()- expect(mockPostgres.fetchPersonsByDistinctIds).toHaveBeenCalled()- })-- it('falls back to postgres when gRPC fetchPersonsByPersonIds fails', async () => {- mockGrpc.persons.fetchPersonsByPersonIds.mockRejectedValue(new Error('timeout'))-- const result = await manager.getCyclotronPerson(TEAM_1, MOCK_PERSONS[0].uuid, 'person_id')-- expect(result).toBeDefined()- expect(result!.id).toBe(MOCK_PERSONS[0].uuid)-- expect(mockGrpc.persons.fetchPersonsByPersonIds).toHaveBeenCalled()- expect(mockPostgres.fetchPersonsByPersonIds).toHaveBeenCalled()- })-- it('produces identical output on fallback as on direct postgres path', async () => {- // First: get the postgres-only result- const postgresRepo = new PersonHogPersonRepository(- mockPostgres,- mockGrpc as unknown as PersonHogClient,- 0,- new Set(),- 'test'- )- const postgresManager = new PersonsManagerService(mockTeamManager, postgresRepo, 'http://localhost:8000')-- const postgresResult = await postgresManager.getCyclotronPerson(TEAM_1, 'alice-distinct', 'distinct_id')-- // Second: get the fallback result (gRPC fails)- mockGrpc.persons.fetchPersonsByDistinctIds.mockRejectedValue(new Error('down'))- mockGrpc.persons.fetchPersonsByPersonIds.mockRejectedValue(new Error('down'))-- const fallbackResult = await manager.getCyclotronPerson(TEAM_1, 'alice-distinct', 'distinct_id')-- expect(fallbackResult).toEqual(postgresResult)- })- })-- describe('concurrent multi-team lookup', () => {- it('resolves persons from multiple teams concurrently', async () => {- const mockPostgres = createMockPostgres(MOCK_PERSONS)- const mockGrpc = createMockGrpcClient(MOCK_PERSONS)-- const personhogRepo = new PersonHogPersonRepository(- mockPostgres,- mockGrpc as unknown as PersonHogClient,- 100,- new Set(),- 'test'- )- const manager = new PersonsManagerService(mockTeamManager, personhogRepo, 'http://localhost:8000')-- const [team1Result, team2Result] = await Promise.all([- manager.getCyclotronPerson(TEAM_1, 'alice-distinct', 'distinct_id'),- manager.getCyclotronPerson(TEAM_2, 'alice-distinct', 'distinct_id'),- ])-- expect(team1Result!.properties).toEqual({ name: 'Alice', email: '[email protected]' })- expect(team2Result!.properties).toEqual({ name: 'Alice Team 2' })-- expect(mockGrpc.persons.fetchPersonsByDistinctIds).toHaveBeenCalled()- })- })-})diff --git a/nodejs/src/cdp/services/managers/persons-manager.service.test.ts b/nodejs/src/cdp/services/managers/persons-manager.service.test.tsindex 6249dbfeafa9..b64b0fee3a50 100644--- a/nodejs/src/cdp/services/managers/persons-manager.service.test.ts+++ b/nodejs/src/cdp/services/managers/persons-manager.service.test.ts@@ -1,208 +1,319 @@+import { create } from '@bufbuild/protobuf'+import { Code, ConnectError, createRouterTransport } from '@connectrpc/connect'import { DateTime } from 'luxon'-import { createTeam, getFirstTeam, getTeam, resetTestDatabase } from '~/tests/helpers/sql'-import { Hub, Person, Team } from '~/types'-import { closeHub, createHub } from '~/utils/db/hub'-import { UUIDT } from '~/utils/utils'-import { PostgresPersonRepository } from '~/worker/ingestion/persons/repositories/postgres-person-repository'+import { PersonHogService } from '~/generated/personhog/personhog/service/v1/service_pb'+import { TeamDistinctIdSchema } from '~/generated/personhog/personhog/types/v1/common_pb'+import {+ GetDistinctIdsForPersonsResponseSchema,+ PersonDistinctIdsSchema,+ PersonSchema,+ PersonWithTeamDistinctIdSchema,+ PersonsByDistinctIdsResponseSchema,+ PersonsResponseSchema,+} from '~/generated/personhog/personhog/types/v1/person_pb'+import { PersonHogClient } from '../../../ingestion/personhog/client'+import { PersonHogPersonReadRepository } from '../../../ingestion/personhog/personhog-person-read-repository'import { PersonsManagerService } from './persons-manager.service'-describe('PersonsManager', () => {- let hub: Hub- let personRepository: PostgresPersonRepository- let manager: PersonsManagerService- let team: Team- let team2: Team- let persons: Person[] = []-- const createPerson = async (- teamId: number,- properties: Record<string, any>,- distinctId: string,- extraDistinctIds?: string[]- ): Promise<Person> => {- const result = await personRepository.createPerson(- DateTime.fromISO('2000-10-14T11:42:06.502Z').toUTC(),- properties,- {},- {},- teamId,- null,- true,- new UUIDT().toString(),- { distinctId },- extraDistinctIds?.map((id) => ({ distinctId: id }))- )- if (!result.success) {- throw new Error('Failed to create person')- }- return result.person- }-- beforeEach(async () => {- hub = await createHub()- personRepository = new PostgresPersonRepository(hub.postgres)- await resetTestDatabase()- manager = new PersonsManagerService(hub.teamManager, hub.personRepository, 'http://localhost:8000')- team = await getFirstTeam(hub.postgres)- const team2Id = await createTeam(hub.postgres, team.organization_id)- team2 = (await getTeam(hub.postgres, team2Id))!-- persons = [- await createPerson(team.id, { foo: '1' }, 'distinct_id_A_1', ['distinct_id_A_2', 'distinct_id_A_3']),- await createPerson(team.id, { foo: '2' }, 'distinct_id_B_1'),- await createPerson(team2.id, { foo: '3' }, 'distinct_id_A_1'),- ]+jest.mock('../../../utils/logger')++const textEncoder = new TextEncoder()++function jsonBytes(obj: unknown): Uint8Array {+ return textEncoder.encode(JSON.stringify(obj))+}++type TestPerson = {+ id: string+ uuid: string+ teamId: number+ properties: Record<string, any>+ distinctIds: string[]+}++function makeProtoPerson(p: TestPerson) {+ return create(PersonSchema, {+ id: BigInt(p.id),+ uuid: p.uuid,+ teamId: BigInt(p.teamId),+ properties: jsonBytes(p.properties),+ propertiesLastUpdatedAt: jsonBytes({}),+ propertiesLastOperation: jsonBytes({}),+ createdAt: BigInt(DateTime.fromISO('2024-01-01T00:00:00Z', { zone: 'utc' }).toMillis()),+ version: 1n,+ isIdentified: true,})+}++function createTestPersonHogPersonReadRepository(persons: TestPerson[]): PersonHogPersonReadRepository {+ const transport = createRouterTransport(({ service }) => {+ service(PersonHogService, {+ getPersonsByDistinctIds: (req) => {+ const results = []+ for (const td of req.teamDistinctIds) {+ const teamId = Number(td.teamId)+ const match = persons.find((p) => p.teamId === teamId && p.distinctIds.includes(td.distinctId))+ if (match) {+ results.push(+ create(PersonWithTeamDistinctIdSchema, {+ person: makeProtoPerson(match),+ key: create(TeamDistinctIdSchema, {+ teamId: td.teamId,+ distinctId: td.distinctId,+ }),+ })+ )+ }+ }+ return create(PersonsByDistinctIdsResponseSchema, { results })+ },+ getPersonsByUuids: (req) => {+ const teamId = Number(req.teamId)+ const matched = persons.filter((p) => p.teamId === teamId && req.uuids.includes(p.uuid))+ return create(PersonsResponseSchema, {+ persons: matched.map(makeProtoPerson),+ missingIds: [],+ })+ },+ getDistinctIdsForPersons: (req) => {+ const teamId = Number(req.teamId)+ const personDistinctIds = []+ for (const personId of req.personIds) {+ const match = persons.find((p) => p.teamId === teamId && p.id === String(personId))+ if (match && match.distinctIds.length > 0) {+ const limit = req.limitPerPerson ? Number(req.limitPerPerson) : undefined+ const ids = limit ? match.distinctIds.slice(0, limit) : match.distinctIds+ personDistinctIds.push(+ create(PersonDistinctIdsSchema, {+ personId,+ distinctIds: ids.map((d) => ({ distinctId: d })),+ })+ )+ }+ }+ return create(GetDistinctIdsForPersonsResponseSchema, { personDistinctIds })+ },+ })+ })++ const client = PersonHogClient.fromTransport(transport)+ return new PersonHogPersonReadRepository(client, 'test')+}++const TEAM_1 = 1+const TEAM_2 = 2++const TEST_PERSONS: TestPerson[] = [+ {+ id: '1',+ uuid: 'aaaaaaaa-0000-0000-0000-000000000001',+ teamId: TEAM_1,+ properties: { foo: '1' },+ distinctIds: ['distinct_id_A_1', 'distinct_id_A_2', 'distinct_id_A_3'],+ },+ {+ id: '2',+ uuid: 'aaaaaaaa-0000-0000-0000-000000000002',+ teamId: TEAM_1,+ properties: { foo: '2' },+ distinctIds: ['distinct_id_B_1'],+ },+ {+ id: '3',+ uuid: 'aaaaaaaa-0000-0000-0000-000000000003',+ teamId: TEAM_2,+ properties: { foo: '3' },+ distinctIds: ['distinct_id_A_1'],+ },+]++describe('PersonsManagerService', () => {+ jest.setTimeout(1000)- afterEach(async () => {- await closeHub(hub)+ const mockTeamManager = {+ getTeam: jest.fn().mockImplementation((teamId: number) => {+ if (teamId === TEAM_1 || teamId === TEAM_2) {+ return Promise.resolve({+ id: teamId,+ uuid: `team-uuid-${teamId}`,+ organization_id: 'org-1',+ person_display_name_properties: [],+ })+ }+ return Promise.resolve(null)+ }),+ hasAvailableFeature: jest.fn().mockResolvedValue(true),+ } as any++ let repo: PersonHogPersonReadRepository+ let manager: PersonsManagerService++ beforeEach(() => {jest.restoreAllMocks()+ repo = createTestPersonHogPersonReadRepository(TEST_PERSONS)+ manager = new PersonsManagerService(mockTeamManager, repo, 'http://localhost:8000')})describe('getCyclotronPerson with distinct_id', () => {it('returns the persons requested', async () => {const res = await Promise.all([- manager.getCyclotronPerson(team.id, 'distinct_id_A_1', 'distinct_id'),- manager.getCyclotronPerson(team.id, 'distinct_id_B_1', 'distinct_id'),+ manager.getCyclotronPerson(TEAM_1, 'distinct_id_A_1', 'distinct_id'),+ manager.getCyclotronPerson(TEAM_1, 'distinct_id_B_1', 'distinct_id'),])expect(res).toEqual([{- id: persons[0].uuid,+ id: TEST_PERSONS[0].uuid,properties: { foo: '1' },name: 'distinct_id_A_1',- url: `http://localhost:8000/project/${team.id}/person/distinct_id_A_1`,+ url: `http://localhost:8000/project/${TEAM_1}/person/distinct_id_A_1`,distinct_id: 'distinct_id_A_1',},{- id: persons[1].uuid,+ id: TEST_PERSONS[1].uuid,properties: { foo: '2' },name: 'distinct_id_B_1',- url: `http://localhost:8000/project/${team.id}/person/distinct_id_B_1`,+ url: `http://localhost:8000/project/${TEAM_1}/person/distinct_id_B_1`,distinct_id: 'distinct_id_B_1',},])})it('handles distinct IDs containing colons', async () => {- const person1 = await createPerson(team.id, { foo: '1' }, 'foo:distinct_id_A_1')- const person2 = await createPerson(team.id, { foo: '2' }, 'foo:bar:distinct_id_B_1')-- const res = await Promise.all([- manager.getCyclotronPerson(team.id, 'foo:distinct_id_A_1', 'distinct_id'),- manager.getCyclotronPerson(team.id, 'foo:bar:distinct_id_B_1', 'distinct_id'),- ])-- expect(res).toEqual([+ const personsWithColons: TestPerson[] = [+ ...TEST_PERSONS,{- id: person1.uuid,- properties: { foo: '1' },- name: 'foo:distinct_id_A_1',- url: `http://localhost:8000/project/${team.id}/person/foo%3Adistinct_id_A_1`,- distinct_id: 'foo:distinct_id_A_1',+ id: '10',+ uuid: 'bbbbbbbb-0000-0000-0000-000000000010',+ teamId: TEAM_1,+ properties: { foo: 'colon1' },+ distinctIds: ['foo:distinct_id_A_1'],},{- id: person2.uuid,- properties: { foo: '2' },- name: 'foo:bar:distinct_id_B_1',- url: `http://localhost:8000/project/${team.id}/person/foo%3Abar%3Adistinct_id_B_1`,- distinct_id: 'foo:bar:distinct_id_B_1',+ id: '11',+ uuid: 'bbbbbbbb-0000-0000-0000-000000000011',+ teamId: TEAM_1,+ properties: { foo: 'colon2' },+ distinctIds: ['foo:bar:distinct_id_B_1'],},+ ]+ const colonRepo = createTestPersonHogPersonReadRepository(personsWithColons)+ const colonManager = new PersonsManagerService(mockTeamManager, colonRepo, 'http://localhost:8000')++ const res = await Promise.all([+ colonManager.getCyclotronPerson(TEAM_1, 'foo:distinct_id_A_1', 'distinct_id'),+ colonManager.getCyclotronPerson(TEAM_1, 'foo:bar:distinct_id_B_1', 'distinct_id'),])++ expect(res[0]!.distinct_id).toBe('foo:distinct_id_A_1')+ expect(res[0]!.url).toBe(`http://localhost:8000/project/${TEAM_1}/person/foo%3Adistinct_id_A_1`)+ expect(res[1]!.distinct_id).toBe('foo:bar:distinct_id_B_1')+ expect(res[1]!.url).toBe(`http://localhost:8000/project/${TEAM_1}/person/foo%3Abar%3Adistinct_id_B_1`)})it('returns different persons for different teams', async () => {const res = await Promise.all([- manager.getCyclotronPerson(team.id, 'distinct_id_A_1', 'distinct_id'),- manager.getCyclotronPerson(team2.id, 'distinct_id_A_1', 'distinct_id'),+ manager.getCyclotronPerson(TEAM_1, 'distinct_id_A_1', 'distinct_id'),+ manager.getCyclotronPerson(TEAM_2, 'distinct_id_A_1', 'distinct_id'),])- expect(res).toEqual([- {- id: persons[0].uuid,- properties: { foo: '1' },- name: 'distinct_id_A_1',- url: `http://localhost:8000/project/${team.id}/person/distinct_id_A_1`,- distinct_id: 'distinct_id_A_1',- },- {- id: persons[2].uuid,- properties: { foo: '3' },- name: 'distinct_id_A_1',- url: `http://localhost:8000/project/${team2.id}/person/distinct_id_A_1`,- distinct_id: 'distinct_id_A_1',- },- ])+ expect(res[0]!.properties).toEqual({ foo: '1' })+ expect(res[1]!.properties).toEqual({ foo: '3' })})it('returns the same person for different distinct ids', async () => {const res = await Promise.all([- manager.getCyclotronPerson(team.id, 'distinct_id_A_1', 'distinct_id'),- manager.getCyclotronPerson(team.id, 'distinct_id_A_2', 'distinct_id'),+ manager.getCyclotronPerson(TEAM_1, 'distinct_id_A_1', 'distinct_id'),+ manager.getCyclotronPerson(TEAM_1, 'distinct_id_A_2', 'distinct_id'),])- expect(res![0]!.id).toEqual(res![1]!.id)- expect(res![0]!.properties).toEqual(res![1]!.properties)+ expect(res[0]!.id).toEqual(res[1]!.id)+ expect(res[0]!.properties).toEqual(res[1]!.properties)})- it('returns undefined when person does not exist', async () => {- const result = await manager.getCyclotronPerson(team.id, 'nonexistent', 'distinct_id')-+ it('returns null when person does not exist', async () => {+ const result = await manager.getCyclotronPerson(TEAM_1, 'nonexistent', 'distinct_id')expect(result).toBeNull()})- it('returns undefined when team does not exist', async () => {+ it('returns null when team does not exist', async () => {const result = await manager.getCyclotronPerson(99999, 'distinct_id_A_1', 'distinct_id')-expect(result).toBeNull()})it('encodes special characters in distinct_id for URL', async () => {- await createPerson(team.id, {}, '[email protected]')- manager.clear()- const result = await manager.getCyclotronPerson(team.id, '[email protected]', 'distinct_id')+ const personsWithEmail: TestPerson[] = [+ ...TEST_PERSONS,+ {+ id: '20',+ uuid: 'cccccccc-0000-0000-0000-000000000020',+ teamId: TEAM_1,+ properties: {},+ distinctIds: ['[email protected]'],+ },+ ]+ const emailRepo = createTestPersonHogPersonReadRepository(personsWithEmail)+ const emailManager = new PersonsManagerService(mockTeamManager, emailRepo, 'http://localhost:8000')++ const result = await emailManager.getCyclotronPerson(TEAM_1, '[email protected]', 'distinct_id')expect(result).toBeDefined()- expect(result!.url).toBe(`http://localhost:8000/project/${team.id}/person/user%40example.com`)+ expect(result!.url).toBe(`http://localhost:8000/project/${TEAM_1}/person/user%40example.com`)})})describe('getCyclotronPerson with person_id', () => {- it('returns a person by their UUID', async () => {- const result = await manager.getCyclotronPerson(team.id, persons[0].uuid, 'person_id')+ it('returns a person by UUID and resolves distinct_id', async () => {+ const result = await manager.getCyclotronPerson(TEAM_1, TEST_PERSONS[0].uuid, 'person_id')expect(result).toEqual(expect.objectContaining({- id: persons[0].uuid,+ id: TEST_PERSONS[0].uuid,properties: { foo: '1' },+ distinct_id: 'distinct_id_A_1',}))})- it('returns undefined for a UUID that does not exist', async () => {- const result = await manager.getCyclotronPerson(team.id, new UUIDT().toString(), 'person_id')-+ it('returns null for a UUID that does not exist', async () => {+ const result = await manager.getCyclotronPerson(TEAM_1, 'zzzzzzzz-0000-0000-0000-000000000000', 'person_id')expect(result).toBeNull()})it('returns the correct person for each team when UUIDs differ', async () => {const res = await Promise.all([- manager.getCyclotronPerson(team.id, persons[0].uuid, 'person_id'),- manager.getCyclotronPerson(team2.id, persons[2].uuid, 'person_id'),+ manager.getCyclotronPerson(TEAM_1, TEST_PERSONS[0].uuid, 'person_id'),+ manager.getCyclotronPerson(TEAM_2, TEST_PERSONS[2].uuid, 'person_id'),])expect(res).toEqual([- expect.objectContaining({ id: persons[0].uuid, properties: { foo: '1' } }),- expect.objectContaining({ id: persons[2].uuid, properties: { foo: '3' } }),+ expect.objectContaining({ id: TEST_PERSONS[0].uuid, properties: { foo: '1' } }),+ expect.objectContaining({ id: TEST_PERSONS[2].uuid, properties: { foo: '3' } }),])})- it('returns undefined when queried under the wrong team', async () => {- const result = await manager.getCyclotronPerson(team2.id, persons[0].uuid, 'person_id')-+ it('returns null when queried under the wrong team', async () => {+ const result = await manager.getCyclotronPerson(TEAM_2, TEST_PERSONS[0].uuid, 'person_id')expect(result).toBeNull()})})++ describe('error handling', () => {+ it('propagates errors when personhog is unavailable', async () => {+ const failingTransport = createRouterTransport(({ service }) => {+ service(PersonHogService, {+ getPersonsByDistinctIds: () => {+ throw new ConnectError('unavailable', Code.Unavailable)+ },+ })+ })+ const failingClient = PersonHogClient.fromTransport(failingTransport)+ const failingRepo = new PersonHogPersonReadRepository(failingClient, 'test')+ const failingManager = new PersonsManagerService(mockTeamManager, failingRepo, 'http://localhost:8000')++ await expect(failingManager.getCyclotronPerson(TEAM_1, 'distinct_id_A_1', 'distinct_id')).rejects.toThrow()+ })+ })})diff --git a/nodejs/src/cdp/services/managers/persons-manager.service.ts b/nodejs/src/cdp/services/managers/persons-manager.service.tsindex bbeaa519b858..a1b35bbcc3f8 100644--- a/nodejs/src/cdp/services/managers/persons-manager.service.ts+++ b/nodejs/src/cdp/services/managers/persons-manager.service.ts@@ -1,7 +1,7 @@import { LazyLoader } from '../../../utils/lazy-loader'import { logger } from '../../../utils/logger'import { TeamManager } from '../../../utils/team-manager'-import { PersonRepository } from '../../../worker/ingestion/persons/repositories/person-repository'+import { PersonReadRepository } from '../../../worker/ingestion/persons/repositories/person-repository'import { CyclotronPerson } from '../../types'import { getPersonDisplayName } from '../../utils'@@ -35,7 +35,7 @@ export class PersonsManagerService {constructor(private teamManager: TeamManager,- private personRepository: PersonRepository,+ private personRepository: PersonReadRepository,private siteUrl: string) {this.lazyLoaderByPersonId = new LazyLoader({@@ -89,7 +89,6 @@ export class PersonsManagerService {const personRows = await this.personRepository.fetchPersonsByDistinctIds(teamPersons.map(({ teamId, id }) => ({ teamId, distinctId: id })),- undefined,'cdp/hogflow-person-enrichment')@@ -117,7 +116,6 @@ export class PersonsManagerService {const personRows = await this.personRepository.fetchPersonsByPersonIds(teamPersons.map(({ teamId, id }) => ({ teamId, personId: id })),- undefined,'cdp/hogflow-person-enrichment')@@ -133,9 +131,12 @@ export class PersonsManagerService {const distinctIdLookups = await Promise.all([...intIdsByTeam].map(async ([teamId, intIds]) => {- const map = await this.personRepository.fetchDistinctIdsForPersons(teamId, intIds, {- limitPerPerson: 1,- })+ const map = await this.personRepository.fetchDistinctIdsForPersons(+ teamId,+ intIds,+ { limitPerPerson: 1 },+ 'cdp/hogflow-person-enrichment'+ )return { teamId, map }}))diff --git a/nodejs/src/cdp/workflows-e2e.test.ts b/nodejs/src/cdp/workflows-e2e.test.tsindex 1539070807aa..401c4bdf336e 100644--- a/nodejs/src/cdp/workflows-e2e.test.ts+++ b/nodejs/src/cdp/workflows-e2e.test.ts@@ -30,7 +30,10 @@ import { Hub, Team } from '../../src/types'import { closeHub, createHub } from '../../src/utils/db/hub'import { PostgresUse } from '../../src/utils/db/postgres'import { UUIDT } from '../../src/utils/utils'-import { PostgresPersonRepository } from '../../src/worker/ingestion/persons/repositories/postgres-person-repository'+import {+ InternalPersonWithDistinctId,+ PersonReadRepository,+} from '../../src/worker/ingestion/persons/repositories/person-repository'import { FixtureHogFlowBuilder } from './_tests/builders/hogflow.builder'import { HOG_FILTERS_EXAMPLES } from './_tests/examples'import { createHogExecutionGlobals, insertHogFunctionTemplate } from './_tests/fixtures'@@ -66,6 +69,7 @@ describe.each(['postgres-v2' as const, 'postgres' as const])('Workflows E2E (%s)let mockProducerObserver: KafkaProducerObserverlet team: Teamlet globals: HogFunctionInvocationGlobals+ let mockPersonRepo: jest.Mocked<PersonReadRepository>let cyclotronPool: Poollet deps: ReturnType<typeof createCdpConsumerDeps>@@ -115,7 +119,14 @@ describe.each(['postgres-v2' as const, 'postgres' as const])('Workflows E2E (%s)],})- deps = createCdpConsumerDeps(hub, kafkaProducer)+ mockPersonRepo = {+ fetchPerson: jest.fn().mockResolvedValue(undefined),+ fetchPersonsByDistinctIds: jest.fn().mockResolvedValue([]),+ fetchPersonsByPersonIds: jest.fn().mockResolvedValue([]),+ fetchDistinctIdsForPersons: jest.fn().mockResolvedValue({}),+ }++ deps = { ...createCdpConsumerDeps(hub, kafkaProducer), personRepository: mockPersonRepo }const kafkaQueue = new CyclotronJobQueueKafka(hub.KAFKA_CLIENT_RACK, hub, hub.CONSUMER_BATCH_SIZE)@@ -816,18 +827,21 @@ describe.each(['postgres-v2' as const, 'postgres' as const])('Workflows E2E (%s)describe('person data survives v2 round-trip', () => {beforeEach(async () => {- const personRepository = new PostgresPersonRepository(hub.postgres)- await personRepository.createPerson(- DateTime.utc(),- { email: '[email protected]', name: 'Test User', plan: 'enterprise' },- {},- {},- team.id,- null,- true,- 'dd3d6f80-60ad-45c3-bd61-e2300f2ba7e1',- { distinctId: 'test-distinct-id' }- )+ const person: InternalPersonWithDistinctId = {+ id: '1',+ uuid: 'dd3d6f80-60ad-45c3-bd61-e2300f2ba7e1',+ team_id: team.id,+ properties: { email: '[email protected]', name: 'Test User', plan: 'enterprise' },+ properties_last_updated_at: {},+ properties_last_operation: null,+ created_at: DateTime.utc(),+ version: 1,+ is_identified: true,+ is_user_id: null,+ last_seen_at: null,+ distinct_id: 'test-distinct-id',+ }+ mockPersonRepo.fetchPersonsByDistinctIds.mockResolvedValue([person])await insertHogFunctionTemplate(hub.postgres, {id: 'template-workflows-e2e-person',@@ -896,18 +910,24 @@ describe.each(['postgres-v2' as const, 'postgres' as const])('Workflows E2E (%s)let hogFlow: HogFlowbeforeEach(async () => {- const personRepository = new PostgresPersonRepository(hub.postgres)- await personRepository.createPerson(- DateTime.utc(),- { email: '[email protected]', plan: 'enterprise' },- {},- {},- team.id,- null,- true,- personUuid,- { distinctId: personDistinctId }- )+ const person = {+ id: '2',+ uuid: personUuid,+ team_id: team.id,+ properties: { email: '[email protected]', plan: 'enterprise' },+ properties_last_updated_at: {},+ properties_last_operation: null,+ created_at: DateTime.utc(),+ version: 1,+ is_identified: true,+ is_user_id: null,+ last_seen_at: null,+ }+ mockPersonRepo.fetchPersonsByDistinctIds.mockResolvedValue([{ ...person, distinct_id: personDistinctId }])+ mockPersonRepo.fetchPersonsByPersonIds.mockResolvedValue([person])+ mockPersonRepo.fetchDistinctIdsForPersons.mockResolvedValue({+ [person.id]: [personDistinctId],+ })await insertHogFunctionTemplate(hub.postgres, {id: 'template-workflows-e2e-batch-distinct-id',@@ -995,7 +1015,7 @@ describe.each(['postgres-v2' as const, 'postgres' as const])('Workflows E2E (%s)],})- const distinctIdSpy = jest.spyOn(hub.personRepository, 'fetchDistinctIdsForPersons')+ mockPersonRepo.fetchDistinctIdsForPersons.mockClear()await triggerWorkflow(createGlobals({ distinct_id: personDistinctId }))@@ -1003,7 +1023,7 @@ describe.each(['postgres-v2' as const, 'postgres' as const])('Workflows E2E (%s)expect(mockFetch).toHaveBeenCalled()}, 5000)- expect(distinctIdSpy).not.toHaveBeenCalled()+ expect(mockPersonRepo.fetchDistinctIdsForPersons).not.toHaveBeenCalled()})})})diff --git a/nodejs/src/ingestion/personhog/personhog-person-read-repository.test.ts b/nodejs/src/ingestion/personhog/personhog-person-read-repository.test.tsnew file mode 100644index 000000000000..a9bcdb22398c--- /dev/null+++ b/nodejs/src/ingestion/personhog/personhog-person-read-repository.test.ts@@ -0,0 +1,224 @@+import { create } from '@bufbuild/protobuf'+import { Code, ConnectError, createRouterTransport } from '@connectrpc/connect'++import { PersonHogService } from '../../generated/personhog/personhog/service/v1/service_pb'+import { PersonSchema } from '../../generated/personhog/personhog/types/v1/person_pb'+import { TeamId } from '../../types'+import { PersonHogClient } from './client'+import { PersonHogPersonReadRepository } from './personhog-person-read-repository'++jest.mock('../../utils/logger')++const textEncoder = new TextEncoder()++function jsonBytes(obj: unknown): Uint8Array {+ return textEncoder.encode(JSON.stringify(obj))+}++const TEAM_ID = 1 as TeamId++function makeProtoPerson(id: bigint = 42n, uuid: string = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee') {+ return create(PersonSchema, {+ id,+ uuid,+ teamId: BigInt(TEAM_ID),+ properties: jsonBytes({ name: 'Test User' }),+ propertiesLastUpdatedAt: jsonBytes({}),+ propertiesLastOperation: jsonBytes({}),+ createdAt: 1704067200000n,+ version: 1n,+ isIdentified: true,+ })+}++type ServiceHandlers = {+ getPersonsByDistinctIds: jest.Mock+ getPersonsByUuids: jest.Mock+ getDistinctIdsForPersons: jest.Mock+}++function createMockClientAndHandlers(): { client: PersonHogClient; handlers: ServiceHandlers } {+ const handlers: ServiceHandlers = {+ getPersonsByDistinctIds: jest.fn().mockResolvedValue({ results: [] }),+ getPersonsByUuids: jest.fn().mockResolvedValue({ persons: [], missingIds: [] }),+ getDistinctIdsForPersons: jest.fn().mockResolvedValue({ personDistinctIds: [] }),+ }++ const transport = createRouterTransport(({ service }) => {+ service(PersonHogService, {+ getPersonsByDistinctIds: handlers.getPersonsByDistinctIds,+ getPersonsByUuids: handlers.getPersonsByUuids,+ getDistinctIdsForPersons: handlers.getDistinctIdsForPersons,+ })+ })++ const client = PersonHogClient.fromTransport(transport)+ return { client, handlers }+}++describe('PersonHogPersonReadRepository', () => {+ describe('fetchPerson', () => {+ it('returns person when found', async () => {+ const { client, handlers } = createMockClientAndHandlers()+ handlers.getPersonsByDistinctIds.mockImplementation(() => ({+ results: [{ person: makeProtoPerson(), key: { teamId: BigInt(TEAM_ID), distinctId: 'user-1' } }],+ }))++ const repo = new PersonHogPersonReadRepository(client)+ const result = await repo.fetchPerson(TEAM_ID, 'user-1')++ expect(result).toBeDefined()+ expect(result!.uuid).toBe('aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee')+ expect(result!.properties).toEqual({ name: 'Test User' })+ })++ it('returns undefined when not found', async () => {+ const { client } = createMockClientAndHandlers()+ const repo = new PersonHogPersonReadRepository(client)+ const result = await repo.fetchPerson(TEAM_ID, 'nonexistent')++ expect(result).toBeUndefined()+ })+ })++ describe('fetchPersonsByDistinctIds', () => {+ it('returns persons with distinct ids', async () => {+ const { client, handlers } = createMockClientAndHandlers()+ handlers.getPersonsByDistinctIds.mockImplementation(() => ({+ results: [{ person: makeProtoPerson(), key: { teamId: BigInt(TEAM_ID), distinctId: 'user-1' } }],+ }))++ const repo = new PersonHogPersonReadRepository(client)+ const result = await repo.fetchPersonsByDistinctIds([{ teamId: TEAM_ID, distinctId: 'user-1' }])++ expect(result).toHaveLength(1)+ expect(result[0].distinct_id).toBe('user-1')+ })++ it('returns empty array for empty input', async () => {+ const { client, handlers } = createMockClientAndHandlers()+ const repo = new PersonHogPersonReadRepository(client)+ const result = await repo.fetchPersonsByDistinctIds([])++ expect(result).toEqual([])+ expect(handlers.getPersonsByDistinctIds).not.toHaveBeenCalled()+ })+ })++ describe('fetchPersonsByPersonIds', () => {+ it('returns persons by uuid', async () => {+ const { client, handlers } = createMockClientAndHandlers()+ handlers.getPersonsByUuids.mockImplementation(() => ({+ persons: [makeProtoPerson()],+ missingIds: [],+ }))++ const repo = new PersonHogPersonReadRepository(client)+ const result = await repo.fetchPersonsByPersonIds([+ { teamId: TEAM_ID, personId: 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee' },+ ])++ expect(result).toHaveLength(1)+ expect(result[0].uuid).toBe('aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee')+ })++ it('returns empty array for empty input', async () => {+ const { client, handlers } = createMockClientAndHandlers()+ const repo = new PersonHogPersonReadRepository(client)+ const result = await repo.fetchPersonsByPersonIds([])++ expect(result).toEqual([])+ expect(handlers.getPersonsByUuids).not.toHaveBeenCalled()+ })+ })++ describe('fetchDistinctIdsForPersons', () => {+ it('returns distinct ids keyed by person id', async () => {+ const { client, handlers } = createMockClientAndHandlers()+ handlers.getDistinctIdsForPersons.mockImplementation(() => ({+ personDistinctIds: [+ { personId: 42n, distinctIds: [{ distinctId: 'user-1' }, { distinctId: 'user-2' }] },+ ],+ }))++ const repo = new PersonHogPersonReadRepository(client)+ const result = await repo.fetchDistinctIdsForPersons(TEAM_ID, ['42'])++ expect(result).toEqual({ '42': ['user-1', 'user-2'] })+ })++ it('returns empty record for empty input', async () => {+ const { client, handlers } = createMockClientAndHandlers()+ const repo = new PersonHogPersonReadRepository(client)+ const result = await repo.fetchDistinctIdsForPersons(TEAM_ID, [])++ expect(result).toEqual({})+ expect(handlers.getDistinctIdsForPersons).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.getPersonsByDistinctIds.mockImplementation(() => {+ callCount+++ if (callCount === 1) {+ throw new ConnectError('transient', code)+ }+ return {+ results: [{ person: makeProtoPerson(), key: { teamId: BigInt(TEAM_ID), distinctId: 'user-1' } }],+ }+ })++ const repo = new PersonHogPersonReadRepository(client)+ const result = await repo.fetchPerson(TEAM_ID, 'user-1')++ expect(result).toBeDefined()+ 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) => {+ const { client, handlers } = createMockClientAndHandlers()+ handlers.getPersonsByDistinctIds.mockImplementation(() => {+ throw new ConnectError('non-retryable', code)+ })++ const repo = new PersonHogPersonReadRepository(client)+ await expect(repo.fetchPerson(TEAM_ID, 'user-1')).rejects.toThrow(ConnectError)++ expect(handlers.getPersonsByDistinctIds).toHaveBeenCalledTimes(1)+ })++ it('throws after max retries exhausted', async () => {+ const { client, handlers } = createMockClientAndHandlers()+ handlers.getPersonsByDistinctIds.mockImplementation(() => {+ throw new ConnectError('unavailable', Code.Unavailable)+ })++ const repo = new PersonHogPersonReadRepository(client)+ await expect(repo.fetchPerson(TEAM_ID, 'user-1')).rejects.toThrow(ConnectError)++ // 1 initial + 2 retries = 3 total+ expect(handlers.getPersonsByDistinctIds).toHaveBeenCalledTimes(3)+ })+ })+})diff --git a/nodejs/src/ingestion/personhog/personhog-person-read-repository.ts b/nodejs/src/ingestion/personhog/personhog-person-read-repository.tsnew file mode 100644index 000000000000..bebc6ed94f66--- /dev/null+++ b/nodejs/src/ingestion/personhog/personhog-person-read-repository.ts@@ -0,0 +1,113 @@+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 { 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+ * on transient errors.+ */+export class PersonHogPersonReadRepository implements PersonReadRepository {+ constructor(+ private grpcClient: PersonHogClient,+ private clientLabel: string = 'unknown'+ ) {}++ async fetchPerson(teamId: number, distinctId: string, callerTag?: string): Promise<InternalPerson | undefined> {+ const results = await withRetry(() =>+ timedGrpc(this.clientLabel, 'fetchPerson', () =>+ this.grpcClient.persons.fetchPersonsByDistinctIds([{ teamId, distinctId }], callerTag)+ )+ )+ return results.length > 0 ? results[0] : undefined+ }++ async fetchPersonsByDistinctIds(+ teamPersons: { teamId: TeamId; distinctId: string }[],+ callerTag?: string+ ): Promise<InternalPersonWithDistinctId[]> {+ return withRetry(() =>+ timedGrpc(this.clientLabel, 'fetchPersonsByDistinctIds', () =>+ this.grpcClient.persons.fetchPersonsByDistinctIds(teamPersons, callerTag)+ )+ )+ }++ async fetchPersonsByPersonIds(+ teamPersons: { teamId: TeamId; personId: string }[],+ callerTag?: string+ ): Promise<InternalPerson[]> {+ return withRetry(() =>+ timedGrpc(this.clientLabel, 'fetchPersonsByPersonIds', () =>+ this.grpcClient.persons.fetchPersonsByPersonIds(teamPersons, callerTag)+ )+ )+ }++ async fetchDistinctIdsForPersons(+ teamId: TeamId,+ personIntIds: string[],+ options?: { limitPerPerson?: number },+ callerTag?: string+ ): Promise<Record<string, string[]>> {+ return withRetry(() =>+ timedGrpc(this.clientLabel, 'fetchDistinctIdsForPersons', () =>+ this.grpcClient.persons.getDistinctIdsForPersons(+ teamId,+ personIntIds,+ options?.limitPerPerson,+ callerTag+ )+ )+ )+ }+}diff --git a/nodejs/src/server.ts b/nodejs/src/server.tsindex 0e6ad6d9f039..f7190e767e6a 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, buildPersonRepository, createPersonHogClient } from './ingestion/personhog'+import { buildGroupRepository, createPersonHogClient } from './ingestion/personhog'+import { PersonHogPersonReadRepository } from './ingestion/personhog/personhog-person-read-repository'import { CleanupResources, NodeServer, ServerLifecycle } from './servers/base-server'import { PluginServerService, PluginsServerConfig, RedisPool } from './types'import { ServerCommands } from './utils/commands'@@ -42,8 +43,7 @@ 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 { PersonRepository } from './worker/ingestion/persons/repositories/person-repository'-import { PostgresPersonRepository } from './worker/ingestion/persons/repositories/postgres-person-repository'+import { PersonReadRepository } from './worker/ingestion/persons/repositories/person-repository'/*** PluginServer handles CDP, logs, evaluation scheduler, and local-dev combined modes.@@ -362,7 +362,7 @@ export class PluginServer implements NodeServer {private async createCdpSharedServices(): Promise<{geoipService: GeoIPService- personRepository: PersonRepository+ personRepository: PersonReadRepositorygroupRepository: GroupRepositoryencryptedFields: EncryptedFieldsintegrationManager: IntegrationManagerService@@ -374,16 +374,13 @@ export class PluginServer implements NodeServer {const personhogClient = createPersonHogClient(this.config)const clientLabel = this.config.PLUGIN_SERVER_MODE ?? 'unknown'- const postgresPersonRepository = new PostgresPersonRepository(this.postgres!, {- calculatePropertiesSize: this.config.PERSON_UPDATE_CALCULATE_PROPERTIES_SIZE,- })- const personRepository = buildPersonRepository(- personhogClient,- postgresPersonRepository,- this.config.PERSONHOG_PERSONS_ROLLOUT_PERCENTAGE,- this.config.PERSONHOG_PERSONS_ROLLOUT_TEAM_IDS,- clientLabel- )+ if (!personhogClient) {+ throw new Error('PersonHog client is required for CDP — set PERSONHOG_ENABLED=true and PERSONHOG_ADDR')+ }++ const personRepository = new PersonHogPersonReadRepository(personhogClient, clientLabel)++ // Groups still use the old rollout-based repository for nowconst postgresGroupRepository = new PostgresGroupRepository(this.postgres!)const groupRepository = buildGroupRepository(personhogClient,diff --git a/nodejs/src/worker/ingestion/persons/repositories/person-repository.ts b/nodejs/src/worker/ingestion/persons/repositories/person-repository.tsindex 11cdb9d2d738..0883bbd11114 100644--- a/nodejs/src/worker/ingestion/persons/repositories/person-repository.ts+++ b/nodejs/src/worker/ingestion/persons/repositories/person-repository.ts@@ -34,6 +34,39 @@ export class PersonPropertiesSizeViolationError extends Error {readonly isRetriable = false}+/**+ * Read-only person lookups backed by personhog gRPC. Used by services that+ * only need to fetch person data (CDP, error tracking, future pipelines).+ * Always uses eventual consistency. Independent of PersonRepository — the+ * two interfaces have different parameter shapes reflecting their different+ * backends and consumers.+ */+export interface PersonReadRepository {+ fetchPerson(teamId: Team['id'], distinctId: string, callerTag?: string): Promise<InternalPerson | undefined>++ fetchPersonsByDistinctIds(+ teamPersons: { teamId: TeamId; distinctId: string }[],+ callerTag?: string+ ): Promise<InternalPersonWithDistinctId[]>++ fetchPersonsByPersonIds(+ teamPersons: { teamId: TeamId; personId: string }[],+ callerTag?: string+ ): Promise<InternalPerson[]>++ fetchDistinctIdsForPersons(+ teamId: TeamId,+ personIntIds: string[],+ options?: { limitPerPerson?: number },+ callerTag?: string+ ): Promise<Record<string, string[]>>+}++/**+ * Full person repository with read and write operations. Used by the+ * ingestion pipeline which creates, updates, merges, and deletes persons.+ * Postgres-backed with support for consistency control and row locking.+ */export interface PersonRepository {fetchPerson(teamId: Team['id'],diff --git a/nodejs/tests/helpers/cdp.ts b/nodejs/tests/helpers/cdp.tsindex b4f810648db7..15ccbe1c992d 100644--- a/nodejs/tests/helpers/cdp.ts+++ b/nodejs/tests/helpers/cdp.ts@@ -12,6 +12,7 @@ import { InternalCaptureService } from '../../src/common/services/internal-captuimport { KafkaProducerRegistry } from '../../src/ingestion/outputs/kafka-producer-registry'import { KafkaProducerWrapper } from '../../src/kafka/producer'import { Hub } from '../../src/types'+import { PersonReadRepository } from '../../src/worker/ingestion/persons/repositories/person-repository'/*** Single shared kafkaProducer is enough for tests — point every CDP producer@@ -30,6 +31,17 @@ function buildTestCdpProducerRegistry(})}+/**+ * No-op PersonReadRepository for tests that don't exercise person lookups.+ * Tests that need person resolution should override via spread.+ */+const noopPersonReadRepository: PersonReadRepository = {+ fetchPerson: () => Promise.resolve(undefined),+ fetchPersonsByDistinctIds: () => Promise.resolve([]),+ fetchPersonsByPersonIds: () => Promise.resolve([]),+ fetchDistinctIdsForPersons: () => Promise.resolve({}),+}+export function createCdpConsumerDeps(hub: Hub, kafkaProducer?: KafkaProducerWrapper): CdpConsumerBaseDeps {return {postgres: hub.postgres,@@ -39,7 +51,7 @@ export function createCdpConsumerDeps(hub: Hub, kafkaProducer?: KafkaProducerWraintegrationManager: hub.integrationManager,cdpProducerRegistry: buildTestCdpProducerRegistry(kafkaProducer),internalCaptureService: new InternalCaptureService(hub),- personRepository: hub.personRepository,+ personRepository: noopPersonReadRepository,geoipService: hub.geoipService,groupRepository: hub.groupRepository,quotaLimiting: hub.quotaLimiting,diff --git a/nodejs/tests/server.test.ts b/nodejs/tests/server.test.tsindex 4711ebe74ac4..0c811073c2e2 100644--- a/nodejs/tests/server.test.ts+++ b/nodejs/tests/server.test.ts@@ -39,6 +39,8 @@ describe('server', () => {pluginsServer = new PluginServer({LOG_LEVEL: 'debug',PLUGIN_SERVER_MODE: PluginServerMode.cdp_processed_events,+ PERSONHOG_ENABLED: true,+ PERSONHOG_ADDR: 'localhost:50052',})await pluginsServer.start()})