: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
fix(workflows): backfill event.distinct_id at cyclotron worker for batch invocations (#60619)
Meikel Ratz5c42305a05e9
diff --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 12d7858fa987..b283ed1c0c2d 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@@ -31,7 +31,12 @@ type MockPersonHogClient = {'fetchGroup' | 'fetchGroupsByKeys' | 'fetchGroupTypesByTeamIds' | 'fetchGroupTypesByProjectIds'>>- persons: jest.Mocked<Pick<PersonHogClient['persons'], 'fetchPersonsByDistinctIds' | 'fetchPersonsByPersonIds'>>+ persons: jest.Mocked<+ Pick<+ PersonHogClient['persons'],+ 'fetchPersonsByDistinctIds' | 'fetchPersonsByPersonIds' | 'getDistinctIdsForPersons'+ >+ >}describe('CdpCyclotronWorkerHogFlow with PersonHog', () => {@@ -108,6 +113,7 @@ describe('CdpCyclotronWorkerHogFlow with PersonHog', () => {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')),},}@@ -158,6 +164,7 @@ describe('CdpCyclotronWorkerHogFlow with PersonHog', () => {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')),},}@@ -191,5 +198,11 @@ describe('CdpCyclotronWorkerHogFlow with PersonHog', () => {// gRPC was attempted for personId lookupexpect(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')})})diff --git a/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow.consumer.ts b/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow.consumer.tsindex 8a39ce01c89d..b861cde4850b 100644--- a/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow.consumer.ts+++ b/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow.consumer.ts@@ -79,6 +79,14 @@ export class CdpCyclotronWorkerHogFlow extends CdpCyclotronWorker {})}+ // Batch-triggered invocations arrive with an empty event.distinct_id because the+ // blast-radius query returns UUIDs only. The person lookup above resolves one+ // distinct_id for us (when the person has any), so backfill it here so templates+ // defaulting to `{event.distinct_id}` resolve at hog runtime.+ if (!hogFlowInvocationState.event.distinct_id && person?.distinct_id) {+ hogFlowInvocationState.event.distinct_id = person.distinct_id+ }+const filterGlobals = convertToHogFunctionFilterGlobal({event: hogFlowInvocationState.event,person: person ?? undefined,diff --git a/nodejs/src/cdp/services/managers/persons-manager-personhog.test.ts b/nodejs/src/cdp/services/managers/persons-manager-personhog.test.tsindex c7563dda3957..d4f240dfacc4 100644--- a/nodejs/src/cdp/services/managers/persons-manager-personhog.test.ts+++ b/nodejs/src/cdp/services/managers/persons-manager-personhog.test.ts@@ -22,7 +22,12 @@ type MockPersonHogClient = {'fetchGroup' | 'fetchGroupsByKeys' | 'fetchGroupTypesByTeamIds' | 'fetchGroupTypesByProjectIds'>>- persons: jest.Mocked<Pick<PersonHogClient['persons'], 'fetchPersonsByDistinctIds' | 'fetchPersonsByPersonIds'>>+ persons: jest.Mocked<+ Pick<+ PersonHogClient['persons'],+ 'fetchPersonsByDistinctIds' | 'fetchPersonsByPersonIds' | 'getDistinctIdsForPersons'+ >+ >}function createMockPostgres(persons: Record<string, any>[]): jest.Mocked<PersonRepository> {@@ -30,6 +35,7 @@ function createMockPostgres(persons: Record<string, any>[]): jest.Mocked<PersonRfetchPerson: jest.fn(),fetchPersonsByDistinctIds: jest.fn(),fetchPersonsByPersonIds: jest.fn(),+ fetchDistinctIdsForPersons: jest.fn(),createPerson: jest.fn(),updatePerson: jest.fn(),updatePersonAssertVersion: jest.fn(),@@ -44,6 +50,17 @@ function createMockPostgres(persons: Record<string, any>[]): jest.Mocked<PersonRinTransaction: 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(@@ -91,6 +108,16 @@ function createMockGrpcClient(persons: Record<string, any>[]): MockPersonHogClie)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)+ }),},}}@@ -186,6 +213,7 @@ describe('PersonsManagerService + PersonHogPersonRepository integration', () =>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) {@@ -195,20 +223,28 @@ describe('PersonsManagerService + PersonHogPersonRepository integration', () =>}})- it('looks up person by person_id', async () => {+ 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,+ })}})@@ -258,6 +294,7 @@ describe('PersonsManagerService + PersonHogPersonRepository integration', () =>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()diff --git a/nodejs/src/cdp/services/managers/persons-manager.service.test.ts b/nodejs/src/cdp/services/managers/persons-manager.service.test.tsindex 14f0cc15c967..6249dbfeafa9 100644--- a/nodejs/src/cdp/services/managers/persons-manager.service.test.ts+++ b/nodejs/src/cdp/services/managers/persons-manager.service.test.ts@@ -74,12 +74,14 @@ describe('PersonsManager', () => {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[1].uuid,properties: { foo: '2' },name: 'distinct_id_B_1',url: `http://localhost:8000/project/${team.id}/person/distinct_id_B_1`,+ distinct_id: 'distinct_id_B_1',},])})@@ -99,12 +101,14 @@ describe('PersonsManager', () => {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: 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',},])})@@ -121,12 +125,14 @@ describe('PersonsManager', () => {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',},])})diff --git a/nodejs/src/cdp/services/managers/persons-manager.service.ts b/nodejs/src/cdp/services/managers/persons-manager.service.tsindex de2a1770de34..f5f37fcbd847 100644--- a/nodejs/src/cdp/services/managers/persons-manager.service.ts+++ b/nodejs/src/cdp/services/managers/persons-manager.service.ts@@ -21,6 +21,8 @@ export type PersonManagerPerson = {id: stringproperties: Record<string, any>team_id: number+ // Populated by fetchPersonsByPersonIds when the person has at least one distinct_id+ distinct_id?: string}export type PersonManagerPersonWithDistinctId = PersonManagerPerson & {@@ -74,6 +76,7 @@ export class PersonsManagerService {properties: dbPerson.properties,name: getPersonDisplayName(team, id, dbPerson.properties),url: `${this.siteUrl}/project/${teamId}/person/${encodeURIComponent(id)}`,+ distinct_id: dbPerson.distinct_id,}}@@ -114,6 +117,34 @@ export class PersonsManagerService {teamPersons.map(({ teamId, id }) => ({ teamId, personId: id })))+ // Fetch one distinct_id per person so callers that need to identify the user+ // (e.g. capture-based hog templates) can do so without a separate round-trip.+ // Grouping by team lets us call the single-team RPC once per team in the batch.+ const intIdsByTeam = new Map<number, string[]>()+ for (const row of personRows) {+ const list = intIdsByTeam.get(row.team_id) ?? []+ list.push(row.id)+ intIdsByTeam.set(row.team_id, list)+ }++ const distinctIdLookups = await Promise.all(+ [...intIdsByTeam].map(async ([teamId, intIds]) => {+ const map = await this.personRepository.fetchDistinctIdsForPersons(teamId, intIds, {+ limitPerPerson: 1,+ })+ return { teamId, map }+ })+ )++ const distinctIdByTeamAndIntId = new Map<string, string>()+ for (const { teamId, map } of distinctIdLookups) {+ for (const [intId, distinctIds] of Object.entries(map)) {+ if (distinctIds.length > 0) {+ distinctIdByTeamAndIntId.set(`${teamId}:${intId}`, distinctIds[0])+ }+ }+ }+// Map results back to the original keysconst result: Record<string, PersonManagerPerson | undefined> = {}@@ -124,6 +155,7 @@ export class PersonsManagerService {id: row.uuid,properties: row.properties,team_id: row.team_id,+ distinct_id: distinctIdByTeamAndIntId.get(`${row.team_id}:${row.id}`),}}diff --git a/nodejs/src/cdp/types.ts b/nodejs/src/cdp/types.tsindex 5700ce4704b5..30150322980d 100644--- a/nodejs/src/cdp/types.ts+++ b/nodejs/src/cdp/types.ts@@ -66,6 +66,10 @@ export type CyclotronPerson = {properties: Record<string, any>name: stringurl: string+ // Populated whenever the manager could resolve a distinct_id for this person.+ // Always present when looked up by distinct_id; for person_id lookups, present+ // when the person has at least one distinct_id in the persondistinctid table.+ distinct_id?: string}export type HogFunctionInvocationGlobals = {diff --git a/nodejs/src/cdp/workflows-e2e.test.ts b/nodejs/src/cdp/workflows-e2e.test.tsindex 51585e9c2056..2578594287ad 100644--- a/nodejs/src/cdp/workflows-e2e.test.ts+++ b/nodejs/src/cdp/workflows-e2e.test.ts@@ -25,9 +25,11 @@ import { getFirstTeam, resetTestDatabase } from '~/tests/helpers/sql'import { KAFKA_APP_METRICS_2, KAFKA_LOG_ENTRIES } from '../../src/config/kafka-topics'import { KafkaProducerWrapper } from '../../src/kafka/producer'+import { HogFlow } from '../../src/schema/hogflow'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 { FixtureHogFlowBuilder } from './_tests/builders/hogflow.builder'import { HOG_FILTERS_EXAMPLES } from './_tests/examples'@@ -40,6 +42,8 @@ import { CyclotronJobQueuePostgres } from './services/job-queue/job-queue-postgrimport { CyclotronJobQueuePostgresV2 } from './services/job-queue/job-queue-postgres-v2'import { JobQueue } from './services/job-queue/job-queue.interface'import { HogFunctionInvocationGlobals } from './types'+import { convertBatchHogFlowRequestToHogFunctionInvocationGlobals } from './utils'+import { convertToHogFunctionFilterGlobal } from './utils/hog-function-filtering'const ActualKafkaProducerWrapper = jest.requireActual('../../src/kafka/producer').KafkaProducerWrapper@@ -54,6 +58,7 @@ describe.each(['postgres-v2' as const, 'postgres' as const])('Workflows E2E (%s)let eventsConsumer: CdpEventsConsumerlet hogflowWorker: CdpCyclotronWorkerHogFlow+ let hogflowQueue: JobQueuelet hub: Hublet kafkaProducer: KafkaProducerWrapper@@ -113,7 +118,6 @@ describe.each(['postgres-v2' as const, 'postgres' as const])('Workflows E2E (%s)const kafkaQueue = new CyclotronJobQueueKafka(hub.KAFKA_CLIENT_RACK, hub, hub.CONSUMER_BATCH_SIZE)// Build the hogflow queue for the current mode- let hogflowQueue: JobQueueif (mode === 'postgres-v2') {hogflowQueue = new CyclotronJobQueuePostgresV2(hub.CONSUMER_BATCH_SIZE, hub)} else {@@ -191,13 +195,54 @@ describe.each(['postgres-v2' as const, 'postgres' as const])('Workflows E2E (%s)workflow: Parameters<FixtureHogFlowBuilder['withWorkflow']>[0],opts?: { name?: string }): Promise<string> {+ const flow = await createWorkflowFlow(workflow, opts)+ return flow.id+ }++ /** Same as createWorkflow but returns the full HogFlow object (useful for hand-built invocations) */+ async function createWorkflowFlow(+ workflow: Parameters<FixtureHogFlowBuilder['withWorkflow']>[0],+ opts?: { name?: string }+ ): Promise<HogFlow> {const builder = new FixtureHogFlowBuilder().withTeamId(team.id).withStatus('active').withWorkflow(workflow)if (opts?.name) {builder.withName(opts.name)}const flow = builder.build()await insertHogFlow(hub.postgres, flow)- return flow.id+ return flow+ }++ /**+ * Construct and enqueue a batch-shaped CyclotronJobInvocation directly, mimicking what+ * CdpBatchHogFlowRequestsConsumer.createHogFlowInvocation would produce. Skips the+ * blast-radius API call so tests don't need to stand up the Django side.+ */+ async function triggerBatchWorkflow(hogFlow: HogFlow, personUuid: string): Promise<void> {+ const invocationGlobals = convertBatchHogFlowRequestToHogFunctionInvocationGlobals({+ team,+ personId: personUuid,+ siteUrl: hub.SITE_URL,+ })+ const filterGlobals = convertToHogFunctionFilterGlobal(invocationGlobals)+ const invocation = {+ id: new UUIDT().toString(),+ state: {+ event: invocationGlobals.event,+ personId: personUuid,+ actionStepCount: 0,+ variables: {},+ },+ teamId: team.id,+ functionId: hogFlow.id,+ parentRunId: new UUIDT().toString(),+ hogFlow,+ person: invocationGlobals.person,+ filterGlobals,+ queue: 'hogflow' as const,+ queuePriority: 1,+ }+ await hogflowQueue.queueInvocations([invocation])}// Reusable action configs@@ -707,4 +752,126 @@ describe.each(['postgres-v2' as const, 'postgres' as const])('Workflows E2E (%s))})})++ describe('batch workflow: event.distinct_id resolved at the worker', () => {+ // A batch-triggered workflow enqueues invocations with personId but an empty+ // event.distinct_id (blast radius returns UUIDs only). The cyclotron worker is+ // responsible for resolving one distinct_id per person during its existing+ // postgres lookup and backfilling state.event.distinct_id — otherwise capture-based+ // templates defaulting to {event.distinct_id} would silently mint new person profiles.+ const personUuid = 'aaaaaaaa-1111-1111-1111-111111111111'+ const personDistinctId = 'batch-person-distinct-id'+ let hogFlow: HogFlow++ beforeEach(async () => {+ const personRepository = new PostgresPersonRepository(hub.postgres)+ await personRepository.createPerson(+ DateTime.utc(),+ { email: '[email protected]', plan: 'enterprise' },+ {},+ {},+ team.id,+ null,+ true,+ personUuid,+ { distinctId: personDistinctId }+ )++ await insertHogFunctionTemplate(hub.postgres, {+ id: 'template-workflows-e2e-batch-distinct-id',+ name: 'Workflows E2E Batch Distinct Id',+ code: `fetch(inputs.url, { 'method': 'POST', 'body': inputs.distinct_id });`,+ inputs_schema: [+ { key: 'url', type: 'string', required: true },+ { key: 'distinct_id', type: 'string', required: true },+ ],+ })++ hogFlow = await createWorkflowFlow({+ actions: {+ trigger: {+ type: 'trigger',+ config: {+ // 'batch' trigger so the events consumer skips this workflow —+ // it only fires when an invocation is queued directly.+ type: 'batch',+ filters: { properties: [{ key: 'plan', value: 'enterprise', type: 'person' }] },+ },+ },+ function_1: {+ type: 'function',+ config: {+ template_id: 'template-workflows-e2e-batch-distinct-id',+ inputs: {+ url: { value: 'https://example.com/batch-distinct-id' },+ distinct_id: {+ value: '{event.distinct_id}',+ bytecode: ['_H', 1, 32, 'distinct_id', 32, 'event', 1, 2, 38],+ },+ },+ },+ },+ exit: exitAction(),+ },+ edges: [+ { from: 'trigger', to: 'function_1', type: 'continue' },+ { from: 'function_1', to: 'exit', type: 'continue' },+ ],+ })+ })++ it("backfills {event.distinct_id} from the person's distinct_id at dequeue", async () => {+ await triggerBatchWorkflow(hogFlow, personUuid)++ await waitForExpect(() => {+ expect(mockFetch).toHaveBeenCalledTimes(1)+ }, 5000)++ // The hog template's `{event.distinct_id}` resolved at runtime to the value+ // the worker backfilled — proving the full chain: postgres lookup → CyclotronPerson.distinct_id+ // → state.event.distinct_id mutation → hog input resolution.+ expect(mockFetch).toHaveBeenCalledWith(+ 'https://example.com/batch-distinct-id',+ expect.objectContaining({+ body: personDistinctId,+ method: 'POST',+ })+ )+ })++ it('does NOT call fetchDistinctIdsForPersons for event-triggered invocations', async () => {+ // Regression guard for the optimization: when event.distinct_id is set going in,+ // the persons-manager uses the by-distinct_id lookup which returns the distinct_id+ // as part of the lookup key — no separate fetchDistinctIdsForPersons RPC needed.+ // Without this guard, the by-person_id path could accidentally be used for event+ // triggers and pay an unnecessary postgres round-trip per worker tick.+ await insertHogFunctionTemplate(hub.postgres, {+ id: 'template-workflows-e2e-event-no-extra-rpc',+ name: 'Workflows E2E Event No Extra RPC',+ code: `fetch(inputs.url, { 'method': 'POST' });`,+ inputs_schema: [{ key: 'url', type: 'string', required: true }],+ })+ await createWorkflow({+ actions: {+ trigger: trigger(),+ function_1: fetchAction('https://example.com/event-trigger-no-extra-rpc'),+ exit: exitAction(),+ },+ edges: [+ { from: 'trigger', to: 'function_1', type: 'continue' },+ { from: 'function_1', to: 'exit', type: 'continue' },+ ],+ })++ const distinctIdSpy = jest.spyOn(hub.personRepository, 'fetchDistinctIdsForPersons')++ await triggerWorkflow(createGlobals({ distinct_id: personDistinctId }))++ await waitForExpect(() => {+ expect(mockFetch).toHaveBeenCalled()+ }, 5000)++ expect(distinctIdSpy).not.toHaveBeenCalled()+ })+ })})diff --git a/nodejs/src/ingestion/error-tracking/error-tracking-consumer.test.ts b/nodejs/src/ingestion/error-tracking/error-tracking-consumer.test.tsindex 69390c36f846..e8617411baac 100644--- a/nodejs/src/ingestion/error-tracking/error-tracking-consumer.test.ts+++ b/nodejs/src/ingestion/error-tracking/error-tracking-consumer.test.ts@@ -60,6 +60,7 @@ const createMockPersonRepository = (): jest.Mocked<PersonRepository> => ({fetchPerson: jest.fn().mockResolvedValue(undefined),fetchPersonsByDistinctIds: jest.fn().mockResolvedValue([]),fetchPersonsByPersonIds: jest.fn(),+ fetchDistinctIdsForPersons: jest.fn().mockResolvedValue({}),createPerson: jest.fn(),updatePerson: jest.fn(),updatePersonAssertVersion: jest.fn(),diff --git a/nodejs/src/ingestion/error-tracking/error-tracking-pipeline.test.ts b/nodejs/src/ingestion/error-tracking/error-tracking-pipeline.test.tsindex 4353ff16ac91..546d6bc24152 100644--- a/nodejs/src/ingestion/error-tracking/error-tracking-pipeline.test.ts+++ b/nodejs/src/ingestion/error-tracking/error-tracking-pipeline.test.ts@@ -234,6 +234,7 @@ describe('ErrorTrackingPipeline', () => {fetchPerson: jest.fn(),fetchPersonsByDistinctIds: jest.fn().mockResolvedValue([]),fetchPersonsByPersonIds: jest.fn(),+ fetchDistinctIdsForPersons: jest.fn().mockResolvedValue({}),createPerson: jest.fn(),updatePerson: jest.fn(),updatePersonAssertVersion: jest.fn(),diff --git a/nodejs/src/ingestion/error-tracking/person-properties-step.test.ts b/nodejs/src/ingestion/error-tracking/person-properties-step.test.tsindex ee60c2515311..8d65d0678df4 100644--- a/nodejs/src/ingestion/error-tracking/person-properties-step.test.ts+++ b/nodejs/src/ingestion/error-tracking/person-properties-step.test.ts@@ -37,6 +37,7 @@ describe('createFetchPersonBatchStep', () => {fetchPerson: jest.fn(),fetchPersonsByDistinctIds: jest.fn(),fetchPersonsByPersonIds: jest.fn(),+ fetchDistinctIdsForPersons: jest.fn(),createPerson: jest.fn(),updatePerson: jest.fn(),updatePersonAssertVersion: jest.fn(),diff --git a/nodejs/src/ingestion/personhog/personhog-person-repository.test.ts b/nodejs/src/ingestion/personhog/personhog-person-repository.test.tsindex ce1ddfa14744..ec1f77b77d7f 100644--- a/nodejs/src/ingestion/personhog/personhog-person-repository.test.ts+++ b/nodejs/src/ingestion/personhog/personhog-person-repository.test.ts@@ -76,6 +76,7 @@ function createMockPostgres(): jest.Mocked<PersonRepository> {fetchPerson: jest.fn(),fetchPersonsByDistinctIds: jest.fn(),fetchPersonsByPersonIds: jest.fn(),+ fetchDistinctIdsForPersons: jest.fn(),createPerson: jest.fn(),updatePerson: jest.fn(),updatePersonAssertVersion: jest.fn(),diff --git a/nodejs/src/ingestion/personhog/personhog-person-repository.ts b/nodejs/src/ingestion/personhog/personhog-person-repository.tsindex 2de98fd644b5..5507d61af0d3 100644--- a/nodejs/src/ingestion/personhog/personhog-person-repository.ts+++ b/nodejs/src/ingestion/personhog/personhog-person-repository.ts@@ -126,6 +126,34 @@ export class PersonHogPersonRepository implements PersonRepository {}}+ async fetchDistinctIdsForPersons(+ teamId: TeamId,+ personIntIds: string[],+ options?: { limitPerPerson?: number; useReadReplica?: boolean }+ ): Promise<Record<string, string[]>> {+ const useReadReplica = options?.useReadReplica ?? true++ if (useReadReplica === false || !shouldUseGrpcForTeam(this.rolloutTeamIds, teamId, this.grpcPercentage)) {+ return timedPostgres(this.clientLabel, 'fetchDistinctIdsForPersons', () =>+ this.postgres.fetchDistinctIdsForPersons(teamId, personIntIds, options)+ )+ }++ try {+ return await timedGrpc(this.clientLabel, 'fetchDistinctIdsForPersons', () =>+ this.grpcClient.persons.getDistinctIdsForPersons(teamId, personIntIds, options?.limitPerPerson)+ )+ } catch (error) {+ logger.warn('[PersonHog] gRPC fetchDistinctIdsForPersons failed, falling back to Postgres', {+ count: personIntIds.length,+ error: String(error),+ })+ return timedPostgres(this.clientLabel, 'fetchDistinctIdsForPersons', () =>+ this.postgres.fetchDistinctIdsForPersons(teamId, personIntIds, options)+ )+ }+ }+// All write operations delegate directly to PostgrescreatePerson(diff --git a/nodejs/src/ingestion/personhog/persons.ts b/nodejs/src/ingestion/personhog/persons.tsindex 97b32f3aab50..1f65aa4b0459 100644--- a/nodejs/src/ingestion/personhog/persons.ts+++ b/nodejs/src/ingestion/personhog/persons.ts@@ -4,6 +4,7 @@ import { Client } from '@connectrpc/connect'import { PersonHogService } from '../../generated/personhog/personhog/service/v1/service_pb'import { TeamDistinctIdSchema } from '../../generated/personhog/personhog/types/v1/common_pb'import {+ GetDistinctIdsForPersonsRequestSchema,GetPersonsByDistinctIdsRequestSchema,GetPersonsByUuidsRequestSchema,} from '../../generated/personhog/personhog/types/v1/person_pb'@@ -61,6 +62,36 @@ export class PersonHogPersonOperations {return results}+ /**+ * Fetch up to ``limitPerPerson`` distinct_ids for each given int person_id.+ * Returns a record keyed by the int person_id (as a string, matching InternalPerson.id).+ * Callers that hold UUIDs should first convert via fetchPersonsByPersonIds to get int IDs.+ */+ async getDistinctIdsForPersons(+ teamId: number,+ personIntIds: string[],+ limitPerPerson?: number+ ): Promise<Record<string, string[]>> {+ if (personIntIds.length === 0) {+ return {}+ }++ const response = await this.client.getDistinctIdsForPersons(+ create(GetDistinctIdsForPersonsRequestSchema, {+ teamId: BigInt(teamId),+ personIds: personIntIds.map((id) => BigInt(id)),+ limitPerPerson: limitPerPerson != null ? BigInt(limitPerPerson) : undefined,+ readOptions: eventualReadOptions(),+ })+ )++ const result: Record<string, string[]> = {}+ for (const pd of response.personDistinctIds) {+ result[String(pd.personId)] = pd.distinctIds.map((d) => d.distinctId)+ }+ return result+ }+async fetchPersonsByPersonIds(teamPersons: { teamId: number; personId: string }[]): Promise<InternalPerson[]> {if (teamPersons.length === 0) {return []diff --git a/nodejs/src/worker/ingestion/persons/batch-writing-person-store.test.ts b/nodejs/src/worker/ingestion/persons/batch-writing-person-store.test.tsindex 0ee17f37b907..c2c66e22ea95 100644--- a/nodejs/src/worker/ingestion/persons/batch-writing-person-store.test.ts+++ b/nodejs/src/worker/ingestion/persons/batch-writing-person-store.test.ts@@ -102,6 +102,7 @@ describe('BatchWritingPersonStore', () => {fetchPersonDistinctIds: jest.fn().mockResolvedValue([]),fetchPersonsByDistinctIds: jest.fn().mockResolvedValue([]),fetchPersonsByPersonIds: jest.fn().mockResolvedValue([]),+ fetchDistinctIdsForPersons: jest.fn().mockResolvedValue({}),createPerson: jest.fn().mockResolvedValue([person, []]),updatePerson: jest.fn().mockResolvedValue([person, [], false]),updatePersonAssertVersion: jest.fn().mockResolvedValue([person.version + 1, []]),diff --git a/nodejs/src/worker/ingestion/persons/repositories/person-repository.ts b/nodejs/src/worker/ingestion/persons/repositories/person-repository.tsindex d1572341d317..c95bb76ca7b9 100644--- a/nodejs/src/worker/ingestion/persons/repositories/person-repository.ts+++ b/nodejs/src/worker/ingestion/persons/repositories/person-repository.ts@@ -51,6 +51,17 @@ export interface PersonRepository {useReadReplica?: boolean): Promise<InternalPerson[]>+ /**+ * Fetch up to ``limitPerPerson`` distinct_ids for each given int person_id (single team).+ * Returns a record keyed by int person_id as a string (matching InternalPerson.id).+ * Persons with no distinct_ids will be absent from the result.+ */+ fetchDistinctIdsForPersons(+ teamId: TeamId,+ personIntIds: string[],+ options?: { limitPerPerson?: number; useReadReplica?: boolean }+ ): Promise<Record<string, string[]>>+createPerson(createdAt: DateTime,properties: Properties,diff --git a/nodejs/src/worker/ingestion/persons/repositories/postgres-person-repository.test.ts b/nodejs/src/worker/ingestion/persons/repositories/postgres-person-repository.test.tsindex ba7d9fbec85f..f104fe171b0f 100644--- a/nodejs/src/worker/ingestion/persons/repositories/postgres-person-repository.test.ts+++ b/nodejs/src/worker/ingestion/persons/repositories/postgres-person-repository.test.ts@@ -998,6 +998,42 @@ describe('PostgresPersonRepository', () => {})})+ describe('fetchDistinctIdsForPersons', () => {+ it('returns empty object when no person ids provided', async () => {+ const team = await getFirstTeam(hub.postgres)+ const result = await repository.fetchDistinctIdsForPersons(team.id, [])+ expect(result).toEqual({})+ })++ it('returns distinct_ids keyed by int person_id, capped per person', async () => {+ const team = await getFirstTeam(hub.postgres)+ const person1 = await createTestPerson(team.id, 'distinct-1-a', { name: 'Person 1' })+ await repository.addDistinctId(person1, 'distinct-1-b', 0)+ await repository.addDistinctId(person1, 'distinct-1-c', 0)+ const person2 = await createTestPerson(team.id, 'distinct-2-a', { name: 'Person 2' })++ const all = await repository.fetchDistinctIdsForPersons(team.id, [person1.id, person2.id])+ expect(all[person1.id]).toEqual(expect.arrayContaining(['distinct-1-a', 'distinct-1-b', 'distinct-1-c']))+ expect(all[person1.id]).toHaveLength(3)+ expect(all[person2.id]).toEqual(['distinct-2-a'])++ const limited = await repository.fetchDistinctIdsForPersons(team.id, [person1.id], {+ limitPerPerson: 1,+ })+ // Ordered by insertion (id ASC), so the cap keeps the first one+ expect(limited[person1.id]).toEqual(['distinct-1-a'])+ })++ it('omits persons that have no distinct_ids in the target team', async () => {+ const team1 = await getFirstTeam(hub.postgres)+ const team2Id = await createTeam(postgres, team1.organization_id)+ const personInTeam2 = await createTestPerson(team2Id, 'team2-only', { name: 'Team 2' })++ const result = await repository.fetchDistinctIdsForPersons(team1.id, [personInTeam2.id])+ expect(result).toEqual({})+ })+ })+describe('addPersonlessDistinctId', () => {it('should insert personless distinct ID successfully', async () => {const team = await getFirstTeam(hub.postgres)diff --git a/nodejs/src/worker/ingestion/persons/repositories/postgres-person-repository.ts b/nodejs/src/worker/ingestion/persons/repositories/postgres-person-repository.tsindex 6b3578d9b4ac..910830963706 100644--- a/nodejs/src/worker/ingestion/persons/repositories/postgres-person-repository.ts+++ b/nodejs/src/worker/ingestion/persons/repositories/postgres-person-repository.ts@@ -376,6 +376,51 @@ export class PostgresPersonRepositoryreturn rows.map(this.toPerson)}+ async fetchDistinctIdsForPersons(+ teamId: TeamId,+ personIntIds: string[],+ options?: { limitPerPerson?: number; useReadReplica?: boolean }+ ): Promise<Record<string, string[]>> {+ if (personIntIds.length === 0) {+ return {}+ }++ const useReadReplica = options?.useReadReplica ?? true+ // LATERAL JOIN applies the LIMIT per person_id, so a person with 100 distinct_ids+ // and limitPerPerson=1 reads one row from the index instead of 100.+ // When unlimited, we pass a very large LIMIT — postgres still uses the index seek per person.+ const perPersonLimit = options?.limitPerPerson != null ? options.limitPerPerson : Number.MAX_SAFE_INTEGER++ const queryString = `SELECT p.id AS person_id, pdi.distinct_id+ FROM unnest($2::bigint[]) AS p(id)+ JOIN LATERAL (+ SELECT distinct_id, id AS pdi_id+ FROM posthog_persondistinctid+ WHERE team_id = $1 AND person_id = p.id+ ORDER BY id ASC+ LIMIT $3::bigint+ ) pdi ON true`++ const { rows } = await this.postgres.query<{ person_id: string; distinct_id: string }>(+ useReadReplica ? PostgresUse.PERSONS_READ : PostgresUse.PERSONS_WRITE,+ queryString,+ [teamId, personIntIds, perPersonLimit],+ 'fetchDistinctIdsForPersons'+ )++ const result: Record<string, string[]> = {}+ for (const row of rows) {+ const key = String(row.person_id)+ const existing = result[key]+ if (existing) {+ existing.push(row.distinct_id)+ } else {+ result[key] = [row.distinct_id]+ }+ }+ return result+ }+async createPerson(createdAt: DateTime,properties: Properties,