: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): enforce 250-ID limit on batch person lookup RPCs (#60508)
Nick Bestfa32c990edd1
diff --git a/nodejs/src/ingestion/personhog/persons.test.ts b/nodejs/src/ingestion/personhog/persons.test.tsnew file mode 100644index 000000000000..ae103133dd22--- /dev/null+++ b/nodejs/src/ingestion/personhog/persons.test.ts@@ -0,0 +1,176 @@+import { create } from '@bufbuild/protobuf'+import { type ServiceImpl, createClient, 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 type {+ GetPersonsByDistinctIdsRequest,+ GetPersonsByUuidsRequest,+} from '../../generated/personhog/personhog/types/v1/person_pb'+import { PersonHogPersonOperations } from './persons'++const textEncoder = new TextEncoder()++function jsonBytes(obj: unknown): Uint8Array {+ return textEncoder.encode(JSON.stringify(obj))+}++function makeProtoPerson(id: number, uuid: string, teamId: number) {+ return create(PersonSchema, {+ id: BigInt(id),+ uuid,+ teamId: BigInt(teamId),+ properties: jsonBytes({ name: `person-${id}` }),+ propertiesLastUpdatedAt: jsonBytes({}),+ propertiesLastOperation: jsonBytes({}),+ createdAt: BigInt(Date.now()),+ version: 1n,+ isIdentified: true,+ })+}++const SERVICE_DEFAULTS: ServiceImpl<typeof PersonHogService> = {+ getGroup: () => ({}),+ getGroups: () => ({ groups: [], missingGroups: [] }),+ getGroupsBatch: () => ({ results: [] }),+ listGroups: () => ({ groups: [], hasMore: false }),+ getGroupTypeMappingsByTeamId: () => ({ mappings: [] }),+ getGroupTypeMappingsByTeamIds: () => ({ results: [] }),+ getGroupTypeMappingsByProjectId: () => ({ mappings: [] }),+ getGroupTypeMappingsByProjectIds: () => ({ results: [] }),+ getGroupTypeMappingByDashboardId: () => ({}),+ createGroup: () => ({}),+ updateGroup: () => ({ updated: false }),+ deleteGroupsBatchForTeam: () => ({ deletedCount: 0n }),+ updateGroupTypeMapping: () => ({}),+ deleteGroupTypeMapping: () => ({ deleted: false }),+ deleteGroupTypeMappingsBatchForTeam: () => ({ deletedCount: 0n }),+ getPerson: () => ({}),+ getPersons: () => ({ persons: [] }),+ getPersonByUuid: () => ({}),+ getPersonsByUuids: () => ({ persons: [] }),+ getPersonByDistinctId: () => ({}),+ getPersonsByDistinctIdsInTeam: () => ({ results: [] }),+ getPersonsByDistinctIds: () => ({ results: [] }),+ getDistinctIdsForPerson: () => ({ distinctIds: [] }),+ getDistinctIdsForPersons: () => ({ personDistinctIds: [] }),+ getHashKeyOverrideContext: () => ({ results: [] }),+ upsertHashKeyOverrides: () => ({}),+ deleteHashKeyOverridesByTeams: () => ({}),+ checkCohortMembership: () => ({ memberships: [] }),+ countCohortMembers: () => ({ count: 0n }),+ deleteCohortMember: () => ({ deleted: false }),+ deleteCohortMembersBulk: () => ({ deletedCount: 0n }),+ insertCohortMembers: () => ({ insertedCount: 0n }),+ listCohortMemberIds: () => ({ personIds: [], nextCursor: 0n }),+ updatePersonProperties: () => ({}),+ deletePersons: () => ({ deletedCount: 0n }),+ deletePersonsBatchForTeam: () => ({ deletedCount: 0n }),+}++function createOperations(overrides: Partial<ServiceImpl<typeof PersonHogService>> = {}): {+ ops: PersonHogPersonOperations+ handlers: { getPersonsByDistinctIds: jest.Mock; getPersonsByUuids: jest.Mock }+} {+ const handlers = {+ getPersonsByDistinctIds: jest.fn(() => ({ results: [] })),+ getPersonsByUuids: jest.fn(() => ({ persons: [] })),+ }++ const transport = createRouterTransport(({ service }) => {+ service(PersonHogService, {+ ...SERVICE_DEFAULTS,+ ...handlers,+ ...overrides,+ })+ })++ const client = createClient(PersonHogService, transport)+ const ops = new PersonHogPersonOperations(client)+ return { ops, handlers }+}++describe('PersonHogPersonOperations', () => {+ describe.each([+ {+ method: 'fetchPersonsByDistinctIds' as const,+ handler: 'getPersonsByDistinctIds' as const,+ makeItem: (i: number) => ({ teamId: 1, distinctId: `d-${i}` }),+ },+ {+ method: 'fetchPersonsByPersonIds' as const,+ handler: 'getPersonsByUuids' as const,+ makeItem: (i: number) => ({ teamId: 1, personId: `uuid-${i}` }),+ },+ ])('$method batching', ({ method, handler, makeItem }) => {+ const invoke = (ops: PersonHogPersonOperations, count: number): Promise<any> =>+ (ops[method] as any)(Array.from({ length: count }, (_, i) => makeItem(i)))++ it('sends a single RPC when under the batch limit', async () => {+ const { ops, handlers } = createOperations()+ await invoke(ops, 10)+ expect(handlers[handler]).toHaveBeenCalledTimes(1)+ })++ it('splits into multiple RPCs when over the batch limit', async () => {+ const { ops, handlers } = createOperations()+ await invoke(ops, 400)+ expect(handlers[handler]).toHaveBeenCalledTimes(2)+ })++ it('handles exact batch boundary without duplicating or dropping', async () => {+ const { ops, handlers } = createOperations()+ await invoke(ops, 250)+ expect(handlers[handler]).toHaveBeenCalledTimes(1)+ })+ })++ describe('fetchPersonsByDistinctIds', () => {+ it('merges results from multiple batches', async () => {+ const handler = jest.fn()+ let callCount = 0+ handler.mockImplementation((req: GetPersonsByDistinctIdsRequest) => {+ callCount+++ return {+ results: req.teamDistinctIds.map((td) => ({+ key: { teamId: td.teamId, distinctId: td.distinctId },+ person: makeProtoPerson(+ callCount * 1000 + Number(td.teamId),+ `uuid-${td.distinctId}`,+ Number(td.teamId)+ ),+ })),+ }+ })++ const { ops } = createOperations({ getPersonsByDistinctIds: handler })+ const items = Array.from({ length: 300 }, (_, i) => ({ teamId: 1, distinctId: `d-${i}` }))++ const results = await ops.fetchPersonsByDistinctIds(items)++ expect(handler).toHaveBeenCalledTimes(2)+ expect(results).toHaveLength(300)+ })+ })++ describe('fetchPersonsByPersonIds', () => {+ it('merges results from multiple batches across teams', async () => {+ const handler = jest.fn()+ handler.mockImplementation((req: GetPersonsByUuidsRequest) => ({+ persons: req.uuids.map((uuid, i) => makeProtoPerson(i, uuid, Number(req.teamId))),+ }))++ const { ops } = createOperations({ getPersonsByUuids: handler })+ const items = [+ ...Array.from({ length: 300 }, (_, i) => ({ teamId: 1, personId: `uuid-t1-${i}` })),+ ...Array.from({ length: 100 }, (_, i) => ({ teamId: 2, personId: `uuid-t2-${i}` })),+ ]++ const results = await ops.fetchPersonsByPersonIds(items)++ // team 1: 2 batches (250 + 50), team 2: 1 batch (100)+ expect(handler).toHaveBeenCalledTimes(3)+ expect(results).toHaveLength(400)+ })+ })+})diff --git a/nodejs/src/ingestion/personhog/persons.ts b/nodejs/src/ingestion/personhog/persons.tsindex 1f65aa4b0459..be5ca04fbe70 100644--- a/nodejs/src/ingestion/personhog/persons.ts+++ b/nodejs/src/ingestion/personhog/persons.ts@@ -29,6 +29,8 @@ function protoPersonToDomain(proto: ProtoPerson): InternalPerson {}}+const PERSONHOG_BATCH_SIZE = 250+export class PersonHogPersonOperations {constructor(private client: Client<typeof PersonHogService>) {}@@ -39,24 +41,27 @@ export class PersonHogPersonOperations {return []}- const response = await this.client.getPersonsByDistinctIds(- create(GetPersonsByDistinctIdsRequestSchema, {- teamDistinctIds: teamPersons.map(({ teamId, distinctId }) =>- create(TeamDistinctIdSchema, {- teamId: BigInt(teamId),- distinctId,- })- ),- readOptions: eventualReadOptions(),- })- )-const results: InternalPersonWithDistinctId[] = []- for (const result of response.results) {- if (result.person && result.key) {- const person = protoPersonToDomain(result.person) as InternalPersonWithDistinctId- person.distinct_id = result.key.distinctId- results.push(person)+ for (let i = 0; i < teamPersons.length; i += PERSONHOG_BATCH_SIZE) {+ const batch = teamPersons.slice(i, i + PERSONHOG_BATCH_SIZE)+ const response = await this.client.getPersonsByDistinctIds(+ create(GetPersonsByDistinctIdsRequestSchema, {+ teamDistinctIds: batch.map(({ teamId, distinctId }) =>+ create(TeamDistinctIdSchema, {+ teamId: BigInt(teamId),+ distinctId,+ })+ ),+ readOptions: eventualReadOptions(),+ })+ )++ for (const result of response.results) {+ if (result.person && result.key) {+ const person = protoPersonToDomain(result.person) as InternalPersonWithDistinctId+ person.distinct_id = result.key.distinctId+ results.push(person)+ }}}return results@@ -97,10 +102,6 @@ export class PersonHogPersonOperations {return []}- // Group by team_id since GetPersonsByUuids is a single-team RPC.- // In practice callers (e.g. CDP PersonsManager) almost always pass a single team,- // so multiple RPCs here is an edge case. If metrics show frequent multi-team batches,- // consider adding a cross-team UUID RPC (similar to GetPersonsByDistinctIds).const byTeam = new Map<number, string[]>()for (const { teamId, personId } of teamPersons) {const uuids = byTeam.get(teamId) ?? []@@ -110,14 +111,19 @@ export class PersonHogPersonOperations {const allPersons = await Promise.all([...byTeam].map(async ([teamId, uuids]) => {- const response = await this.client.getPersonsByUuids(- create(GetPersonsByUuidsRequestSchema, {- teamId: BigInt(teamId),- uuids,- readOptions: eventualReadOptions(),- })- )- return response.persons.map(protoPersonToDomain)+ const batchResults: InternalPerson[] = []+ for (let i = 0; i < uuids.length; i += PERSONHOG_BATCH_SIZE) {+ const batch = uuids.slice(i, i + PERSONHOG_BATCH_SIZE)+ const response = await this.client.getPersonsByUuids(+ create(GetPersonsByUuidsRequestSchema, {+ teamId: BigInt(teamId),+ uuids: batch,+ readOptions: eventualReadOptions(),+ })+ )+ batchResults.push(...response.persons.map(protoPersonToDomain))+ }+ return batchResults}))return allPersons.flat()diff --git a/proto/personhog/types/v1/person.proto b/proto/personhog/types/v1/person.protoindex 209d5c23ac76..855b8ec9c23e 100644--- a/proto/personhog/types/v1/person.proto+++ b/proto/personhog/types/v1/person.proto@@ -54,6 +54,7 @@ message GetPersonResponse {message GetPersonsRequest {int64 team_id = 1;+ // Max 250 per request.repeated int64 person_ids = 2;ReadOptions read_options = 3;}@@ -71,6 +72,7 @@ message GetPersonByUuidRequest {message GetPersonsByUuidsRequest {int64 team_id = 1;+ // Max 250 per request.repeated string uuids = 2;ReadOptions read_options = 3;}@@ -83,6 +85,7 @@ message GetPersonByDistinctIdRequest {message GetPersonsByDistinctIdsInTeamRequest {int64 team_id = 1;+ // Max 250 per request.repeated string distinct_ids = 2;ReadOptions read_options = 3;}@@ -92,6 +95,7 @@ message PersonsByDistinctIdsInTeamResponse {}message GetPersonsByDistinctIdsRequest {+ // Max 250 per request.repeated TeamDistinctId team_distinct_ids = 1;ReadOptions read_options = 2;}diff --git a/rust/personhog-replica/src/service/mod.rs b/rust/personhog-replica/src/service/mod.rsindex 02dd3c322905..bee44fdcbdcc 100644--- a/rust/personhog-replica/src/service/mod.rs+++ b/rust/personhog-replica/src/service/mod.rs@@ -44,6 +44,7 @@ use uuid::Uuid;use crate::storage::{self, FullStorage};+const MAX_BATCH_LOOKUP_SIZE: usize = 250;const MAX_BATCH_DELETE_SIZE: i64 = 50_000;const MAX_LIST_COHORT_MEMBER_IDS_LIMIT: i32 = 10_000;const MAX_LIST_GROUPS_LIMIT: i32 = 1_000;@@ -96,6 +97,12 @@ impl PersonHogReplica for PersonHogReplicaService {let req = request.into_inner();reject_strong_consistency(&req.read_options)?;+ if req.person_ids.len() > MAX_BATCH_LOOKUP_SIZE {+ return Err(Status::invalid_argument(format!(+ "Maximum {MAX_BATCH_LOOKUP_SIZE} person IDs per request"+ )));+ }+let include_props = person_needs_properties(&req.read_options);let persons = self.storage@@ -150,6 +157,12 @@ impl PersonHogReplica for PersonHogReplicaService {let req = request.into_inner();reject_strong_consistency(&req.read_options)?;+ if req.uuids.len() > MAX_BATCH_LOOKUP_SIZE {+ return Err(Status::invalid_argument(format!(+ "Maximum {MAX_BATCH_LOOKUP_SIZE} UUIDs per request"+ )));+ }+let uuids: Vec<Uuid> = req.uuids.iter()@@ -205,6 +218,12 @@ impl PersonHogReplica for PersonHogReplicaService {let req = request.into_inner();reject_strong_consistency(&req.read_options)?;+ if req.distinct_ids.len() > MAX_BATCH_LOOKUP_SIZE {+ return Err(Status::invalid_argument(format!(+ "Maximum {MAX_BATCH_LOOKUP_SIZE} distinct IDs per request"+ )));+ }+let include_props = person_needs_properties(&req.read_options);let results = self.storage@@ -237,6 +256,12 @@ impl PersonHogReplica for PersonHogReplicaService {let req = request.into_inner();reject_strong_consistency(&req.read_options)?;+ if req.team_distinct_ids.len() > MAX_BATCH_LOOKUP_SIZE {+ return Err(Status::invalid_argument(format!(+ "Maximum {MAX_BATCH_LOOKUP_SIZE} distinct IDs per request"+ )));+ }+let include_props = person_needs_properties(&req.read_options);let team_distinct_ids: Vec<(i64, String)> = req.team_distinct_ids