: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
feat(personhog): resolve prefetch distinct ids to person ids only (#114893)
José Sequeira68574b4c084a
diff --git a/nodejs/src/common/generated/personhog/personhog/identity/v1/identity_pb.ts b/nodejs/src/common/generated/personhog/personhog/identity/v1/identity_pb.tsindex 3e6817c52f36..aa4ae4f1d510 100644--- a/nodejs/src/common/generated/personhog/personhog/identity/v1/identity_pb.ts+++ b/nodejs/src/common/generated/personhog/personhog/identity/v1/identity_pb.ts@@ -13,7 +13,7 @@ import { file_personhog_types_v1_person } from '../../types/v1/person_pb'export const file_personhog_identity_v1_identity: GenFile =/*@__PURE__*/fileDesc(- 'CiRwZXJzb25ob2cvaWRlbnRpdHkvdjEvaWRlbnRpdHkucHJvdG8SFXBlcnNvbmhvZy5pZGVudGl0eS52MSLOAQoWR2V0T3JDcmVhdGVQZXJzb25FbnRyeRIPCgd0ZWFtX2lkGAEgASgDEhMKC2Rpc3RpbmN0X2lkGAIgASgJEhoKEmV4dHJhX2Rpc3RpbmN0X2lkcxgDIAMoCRISCgpldmVudF9uYW1lGAQgASgJEhYKDnNldF9wcm9wZXJ0aWVzGAUgASgMEhsKE3NldF9vbmNlX3Byb3BlcnRpZXMYBiABKAwSEgoKY3JlYXRlZF9hdBgHIAEoAxIVCg1pc19pZGVudGlmaWVkGAggASgIImQKJEdldE9yQ3JlYXRlUGVyc29uQnlEaXN0aW5jdElkUmVxdWVzdBI8CgVlbnRyeRgBIAEoCzItLnBlcnNvbmhvZy5pZGVudGl0eS52MS5HZXRPckNyZWF0ZVBlcnNvbkVudHJ5ImQKJUdldE9yQ3JlYXRlUGVyc29uQnlEaXN0aW5jdElkUmVzcG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ZXNwb25zZRKgAQofR2V0T3JDcmVhdGVQZXJzb25zQnlEaXN0aW5jdElkcxI9LnBlcnNvbmhvZy5pZGVudGl0eS52MS5HZXRPckNyZWF0ZVBlcnNvbnNCeURpc3RpbmN0SWRzUmVxdWVzdBo+LnBlcnNvbmhvZy5pZGVudGl0eS52MS5HZXRPckNyZWF0ZVBlcnNvbnNCeURpc3RpbmN0SWRzUmVzcG9uc2USiAEKF0dldFBlcnNvbnNCeURpc3RpbmN0SWRzEjUucGVyc29uaG9nLmlkZW50aXR5LnYxLkdldFBlcnNvbnNCeURpc3RpbmN0SWRzUmVxdWVzdBo2LnBlcnNvbmhvZy5pZGVudGl0eS52MS5HZXRQZXJzb25zQnlEaXN0aW5jdElkc1Jlc3BvbnNlEosBChhHZXREaXN0aW5jdElkc0ZvclBlcnNvbnMSNi5wZXJzb25ob2cuaWRlbnRpdHkudjEuR2V0RGlzdGluY3RJZHNGb3JQZXJzb25zUmVxdWVzdBo3LnBlcnNvbmhvZy5pZGVudGl0eS52MS5HZXREaXN0aW5jdElkc0ZvclBlcnNvbnNSZXNwb25zZRJnCgxNZXJnZVBlcnNvbnMSKi5wZXJzb25ob2cuaWRlbnRpdHkudjEuTWVyZ2VQZXJzb25zUmVxdWVzdBorLnBlcnNvbmhvZy5pZGVudGl0eS52MS5NZXJnZVBlcnNvbnNSZXNwb25zZWIGcHJvdG8z',[file_personhog_types_v1_person])@@ -268,6 +268,13 @@ export type GetPersonsByDistinctIdsRequest = Message<'personhog.identity.v1.GetP* @generated from field: repeated personhog.identity.v1.PersonKey keys = 1;*/keys: PersonKey[]++ /**+ * Answer only id and team_id, read from the distinct id table without checking the person is live.+ *+ * @generated from field: bool ids_only = 2;+ */+ idsOnly: boolean}/**@@ -300,6 +307,7 @@ export type GetPersonByDistinctIdResult = Message<'personhog.identity.v1.GetPers* Absent when the distinct id resolves to no live person — unknown,* tombstoned, or its person deleted. Identity fields only: properties are* never populated here, fetch the person by id from its leader for state.+ * With ids_only, only id and team_id are set and the person may be deleted.** @generated from field: optional personhog.types.v1.Person person = 3;*/diff --git a/nodejs/src/common/personhog/identity.test.ts b/nodejs/src/common/personhog/identity.test.tsindex f26bf0d1905c..8017a94ccee8 100644--- a/nodejs/src/common/personhog/identity.test.ts+++ b/nodejs/src/common/personhog/identity.test.ts@@ -7,7 +7,7 @@ import {PersonHogIdentity,} from '~/common/generated/personhog/personhog/identity/v1/identity_pb'-import { PersonhogIdentityOperations } from './identity'+import { DistinctIdKey, PersonhogIdentityOperations } from './identity'import { createIdentityClients } from './identity-clients'describe('PersonhogIdentityOperations', () => {@@ -130,19 +130,39 @@ describe('PersonhogIdentityOperations', () => {// The identity service rejects batches above 250, so the wrappers must// chunk — without this, a large-batch prefetch degrades to a silent// no-op on exactly the batches it exists for.- it('chunks resolve requests to the service batch cap', async () => {+ it.each([+ [+ 'getPersonsByDistinctIds',+ false,+ async (ops: PersonhogIdentityOperations, keys: DistinctIdKey[]): Promise<(string | null)[]> =>+ (await ops.getPersonsByDistinctIds(keys)).map((result) => result.person?.id ?? null),+ ],+ [+ 'getPersonIdsByDistinctIds',+ true,+ async (ops: PersonhogIdentityOperations, keys: DistinctIdKey[]): Promise<(string | null)[]> =>+ (await ops.getPersonIdsByDistinctIds(keys)).map((result) => result.personId),+ ],+ ])('%s chunks resolve requests to the service batch cap', async (_method, idsOnly, resolveIds) => {const handler = jest.fn((req: GetPersonsByDistinctIdsRequest) => ({- results: req.keys.map((key) => ({ teamId: key.teamId, distinctId: key.distinctId, person: undefined })),+ results: req.keys.map((key) => ({+ teamId: key.teamId,+ distinctId: key.distinctId,+ person: key.distinctId === 'd0' ? { id: 9007199254740993n, teamId: key.teamId } : undefined,+ })),}))const ops = makeOps({ getPersonsByDistinctIds: handler })const keys = Array.from({ length: 251 }, (_, i) => ({ teamId: 1, distinctId: `d${i}` }))- const results = await ops.getPersonsByDistinctIds(keys)+ const ids = await resolveIds(ops, keys)expect(handler).toHaveBeenCalledTimes(2)- expect(handler.mock.calls[0][0].keys).toHaveLength(250)- expect(handler.mock.calls[1][0].keys).toHaveLength(1)- expect(results).toHaveLength(251)+ expect(handler.mock.calls.map(([req]) => [req.keys.length, req.idsOnly])).toEqual([+ [250, idsOnly],+ [1, idsOnly],+ ])+ expect(ids).toHaveLength(251)+ expect(ids.slice(0, 2)).toEqual(['9007199254740993', null])})it('chunks expansion requests to the service batch cap', async () => {diff --git a/nodejs/src/common/personhog/identity.ts b/nodejs/src/common/personhog/identity.tsindex 7f1c42edc2a0..474e93f7ecc2 100644--- a/nodejs/src/common/personhog/identity.ts+++ b/nodejs/src/common/personhog/identity.ts@@ -5,6 +5,7 @@ import { Counter } from 'prom-client'import {GetDistinctIdsForPersonsRequestSchema,GetOrCreatePersonByDistinctIdRequestSchema,+ GetPersonByDistinctIdResult,GetPersonsByDistinctIdsRequestSchema,MergePersonsRequestSchema,MergeSourceOutcome,@@ -177,10 +178,32 @@ export class PersonhogIdentityOperations {keys: DistinctIdKey[],callerTag?: string): Promise<{ teamId: number; distinctId: string; person: PersonIdentity | null }[]> {- if (keys.length === 0) {- return []- }- const out: { teamId: number; distinctId: string; person: PersonIdentity | null }[] = []+ const results = await this.resolveInChunks(keys, false, callerTag)+ return results.map((result) => ({+ teamId: Number(result.teamId),+ distinctId: result.distinctId,+ person: result.person ? protoPersonToIdentity(result.person) : null,+ }))+ }++ async getPersonIdsByDistinctIds(+ keys: DistinctIdKey[],+ callerTag?: string+ ): Promise<{ teamId: number; distinctId: string; personId: string | null }[]> {+ const results = await this.resolveInChunks(keys, true, callerTag)+ return results.map((result) => ({+ teamId: Number(result.teamId),+ distinctId: result.distinctId,+ personId: result.person ? String(result.person.id) : null,+ }))+ }++ private async resolveInChunks(+ keys: DistinctIdKey[],+ idsOnly: boolean,+ callerTag?: string+ ): Promise<GetPersonByDistinctIdResult[]> {+ const out: GetPersonByDistinctIdResult[] = []for (let i = 0; i < keys.length; i += IDENTITY_BATCH_SIZE) {const chunk = keys.slice(i, i + IDENTITY_BATCH_SIZE)const response = await this.client.getPersonsByDistinctIds(@@ -189,16 +212,11 @@ export class PersonhogIdentityOperations {teamId: BigInt(key.teamId),distinctId: key.distinctId,})),+ idsOnly,}),callerTag ? { headers: { 'x-caller-tag': callerTag } } : undefined)- for (const result of response.results) {- out.push({- teamId: Number(result.teamId),- distinctId: result.distinctId,- person: result.person ? protoPersonToIdentity(result.person) : null,- })- }+ out.push(...response.results)}return out}diff --git a/nodejs/src/common/personhog/personhog-person-write-repository.ts b/nodejs/src/common/personhog/personhog-person-write-repository.tsindex 9e9640b646a1..24d7191915ff 100644--- a/nodejs/src/common/personhog/personhog-person-write-repository.ts+++ b/nodejs/src/common/personhog/personhog-person-write-repository.ts@@ -52,6 +52,19 @@ export class PersonHogPersonWriteRepository {)}+ /** Person ids only; confirm each person through `fetchPersonById` before trusting it. */+ resolvePersonIdsByDistinctIds(+ keys: DistinctIdKey[],+ callerTag?: string+ ): Promise<{ teamId: number; distinctId: string; personId: string | null }[]> {+ const method = 'resolvePersonIdsByDistinctIds'+ return withRetry(+ () => timedGrpc(this.clientLabel, method, () => this.identity.getPersonIdsByDistinctIds(keys, callerTag)),+ this.clientLabel,+ method+ )+ }+/** Leader-routed strong person read; null when deleted or merged away. */fetchPersonById(teamId: number, personId: string, callerTag?: string): Promise<InternalPerson | null> {const method = 'fetchPersonById'diff --git a/nodejs/src/ingestion/common/persons/personhog-persons-store.test.ts b/nodejs/src/ingestion/common/persons/personhog-persons-store.test.tsindex db5f78b4a607..6c2a83f14051 100644--- a/nodejs/src/ingestion/common/persons/personhog-persons-store.test.ts+++ b/nodejs/src/ingestion/common/persons/personhog-persons-store.test.ts@@ -101,6 +101,15 @@ describe('PersonhogPersonsStore', () => {getDistinctIdsForPersons: jest.fn().mockResolvedValue({}),getOrCreatePersonByDistinctId: jest.fn().mockResolvedValue({ person, created: true }),} as unknown as jest.Mocked<PersonHogPersonWriteRepository>+ repository.resolvePersonIdsByDistinctIds = jest.fn((keys, callerTag) =>+ repository.resolvePersonsByDistinctIds(keys, callerTag).then((results) =>+ results.map(({ teamId, distinctId, person }) => ({+ teamId,+ distinctId,+ personId: person?.id ?? null,+ }))+ )+ ) as neverstore = new PersonhogPersonsStore(repository)})@@ -344,8 +353,8 @@ describe('PersonhogPersonsStore', () => {expect((await bound.fetchForUpdate(1, distinctId))?.id).toBe('7')}- expect(repository.resolvePersonsByDistinctIds).toHaveBeenCalledTimes(1)- expect(repository.resolvePersonsByDistinctIds.mock.calls[0][0]).toHaveLength(ids.length)+ expect(repository.resolvePersonIdsByDistinctIds).toHaveBeenCalledTimes(1)+ expect(repository.resolvePersonIdsByDistinctIds.mock.calls[0][0]).toHaveLength(ids.length)})it.each([['fetchForUpdate' as const], ['fetchForChecking' as const]])(@@ -399,8 +408,8 @@ describe('PersonhogPersonsStore', () => {{ teamId: 1, distinctId: 'd1', batchId: 0 },{ teamId: 1, distinctId: 'd1', batchId: 0 },])- expect(repository.resolvePersonsByDistinctIds).toHaveBeenCalledTimes(1)- expect(repository.resolvePersonsByDistinctIds.mock.calls[0][0]).toEqual([{ teamId: 1, distinctId: 'd1' }])+ expect(repository.resolvePersonIdsByDistinctIds).toHaveBeenCalledTimes(1)+ expect(repository.resolvePersonIdsByDistinctIds.mock.calls[0][0]).toEqual([{ teamId: 1, distinctId: 'd1' }])})it('a failed prefetch falls back to first-touch resolution', async () => {diff --git a/nodejs/src/ingestion/common/persons/personhog-persons-store.ts b/nodejs/src/ingestion/common/persons/personhog-persons-store.tsindex 8071063ce036..78b3c2769efa 100644--- a/nodejs/src/ingestion/common/persons/personhog-persons-store.ts+++ b/nodejs/src/ingestion/common/persons/personhog-persons-store.ts@@ -517,6 +517,14 @@ export class PersonhogPersonsStore implements PersonsStore {return this.repository.resolvePersonsByDistinctIds(keys, CALLER_TAG)}+ private resolvePersonIds(+ site: ResolveSite,+ keys: DistinctIdKey[]+ ): ReturnType<PersonHogPersonWriteRepository['resolvePersonIdsByDistinctIds']> {+ personResolveKeysPerCallHistogram.observe({ backend: this.backend, site }, keys.length)+ return this.repository.resolvePersonIdsByDistinctIds(keys, CALLER_TAG)+ }+/** Resolves through identity and serves its answer directly, saving the leader hop. */async fetchForChecking(teamId: number, distinctId: string, batchId: number): Promise<InternalPerson | null> {const cached = this.getCachedPerson(teamId, distinctId, 'check')@@ -1120,7 +1128,7 @@ export class PersonhogPersonsStore implements PersonsStore {}}try {- const resolved = await this.resolveDistinctIds(+ const resolved = await this.resolvePersonIds('prefetch',unresolved.map((entry) => ({ teamId: entry.teamId, distinctId: entry.distinctId })))@@ -1136,7 +1144,7 @@ export class PersonhogPersonsStore implements PersonsStore {personhogStorePrefetchAnswerCounter.inc({ outcome: 'batch_released' })return}- if (!entry.person) {+ if (entry.personId === null) {this.cacheFetchedPerson(entry.teamId, entry.distinctId, null, batchId, {grade: 'check',generation,@@ -1144,8 +1152,8 @@ export class PersonhogPersonsStore implements PersonsStore {})return}- const person = await this.repository.fetchPersonById(entry.teamId, entry.person.id, CALLER_TAG)- // Merged away since identity answered; the update read resolves it.+ const person = await this.repository.fetchPersonById(entry.teamId, entry.personId, CALLER_TAG)+ // Deleted or merged away; the update read resolves it.if (!this.prefetchingBatches.has(batchId) || person === null) {personhogStorePrefetchAnswerCounter.inc({outcome: this.prefetchingBatches.has(batchId) ? 'leader_gone' : 'batch_released',diff --git a/proto/personhog/identity/v1/identity.proto b/proto/personhog/identity/v1/identity.protoindex 786248fbbac3..97f6501232d8 100644--- a/proto/personhog/identity/v1/identity.proto+++ b/proto/personhog/identity/v1/identity.proto@@ -81,6 +81,8 @@ message PersonKey {message GetPersonsByDistinctIdsRequest {// Max 250 per request. Keys may span teams.repeated PersonKey keys = 1;+ // Answer only id and team_id, read from the distinct id table without checking the person is live.+ bool ids_only = 2;}// The per-key outcome of a batch resolve. Mirrors GetOrCreatePersonResult@@ -92,6 +94,7 @@ message GetPersonByDistinctIdResult {// Absent when the distinct id resolves to no live person — unknown,// tombstoned, or its person deleted. Identity fields only: properties are// never populated here, fetch the person by id from its leader for state.+ // With ids_only, only id and team_id are set and the person may be deleted.optional personhog.types.v1.Person person = 3;}diff --git a/rust/personhog-identity/src/service/mod.rs b/rust/personhog-identity/src/service/mod.rsindex 34476d0294cd..44c1bc80d1df 100644--- a/rust/personhog-identity/src/service/mod.rs+++ b/rust/personhog-identity/src/service/mod.rs@@ -22,7 +22,9 @@ use personhog_proto::personhog::identity::v1::{GetPersonsByDistinctIdsRequest, GetPersonsByDistinctIdsResponse, MergePersonsRequest,MergePersonsResponse,};-use personhog_proto::personhog::types::v1::{DistinctIdWithVersion, PersonDistinctIds};+use personhog_proto::personhog::types::v1::{+ DistinctIdWithVersion, Person as ProtoPerson, PersonDistinctIds,+};use crate::leader::PropertyWriter;use crate::service::merge::MergeEntrance;@@ -123,7 +125,8 @@ impl PersonHogIdentity for PersonHogIdentityService {&self,request: Request<GetPersonsByDistinctIdsRequest>,) -> Result<Response<GetPersonsByDistinctIdsResponse>, Status> {- let keys = request.into_inner().keys;+ let request = request.into_inner();+ let keys = request.keys;common_metrics::histogram(RESOLVE_KEYS_PER_CALL, &[], keys.len() as f64);validate_batch_size(&self.limits, keys.len())?;for key in &keys {@@ -134,21 +137,39 @@ impl PersonHogIdentity for PersonHogIdentityService {.iter().map(|key| (key.team_id, key.distinct_id.clone())).collect();- let resolved = self- .storage- .resolve_distinct_ids(&identifiers)- .await- .map_err(|e| crate::service::error::log_and_convert_error(e, "resolve_distinct_ids"))?;+ let resolved: std::collections::HashMap<(i64, String), ProtoPerson> = if request.ids_only {+ self.storage+ .resolve_person_ids(&identifiers)+ .await+ .map_err(|e| crate::service::error::log_and_convert_error(e, "resolve_person_ids"))?+ .into_iter()+ .map(|((team_id, distinct_id), id)| {+ let person = ProtoPerson {+ id,+ team_id,+ ..Default::default()+ };+ ((team_id, distinct_id), person)+ })+ .collect()+ } else {+ self.storage+ .resolve_distinct_ids(&identifiers)+ .await+ .map_err(|e| {+ crate::service::error::log_and_convert_error(e, "resolve_distinct_ids")+ })?+ .into_iter()+ .map(|(key, person)| (key, person.into()))+ .collect()+ };let results = identifiers.into_iter().map(|(team_id, distinct_id)| {// Look up rather than consume: a key repeated in one// request must resolve on every occurrence.- let person = resolved- .get(&(team_id, distinct_id.clone()))- .cloned()- .map(Into::into);+ let person = resolved.get(&(team_id, distinct_id.clone())).cloned();GetPersonByDistinctIdResult {team_id,distinct_id,diff --git a/rust/personhog-identity/src/storage/mod.rs b/rust/personhog-identity/src/storage/mod.rsindex fb0d0bb2b63a..a8bbedf6f9e6 100644--- a/rust/personhog-identity/src/storage/mod.rs+++ b/rust/personhog-identity/src/storage/mod.rs@@ -24,6 +24,12 @@ pub trait IdentityStorage: Send + Sync {keys: &[(i64, String)],) -> StorageResult<HashMap<(i64, String), Person>>;+ /// Person ids from live distinct id rows, without reading the person table.+ async fn resolve_person_ids(+ &self,+ keys: &[(i64, String)],+ ) -> StorageResult<HashMap<(i64, String), i64>>;+/// Expand person ids to their live distinct id rows on the primary./// With a per-person limit, identified ids survive the cut and the/// scan is capped for pathological persons — the same orderingdiff --git a/rust/personhog-identity/src/storage/postgres/mod.rs b/rust/personhog-identity/src/storage/postgres/mod.rsindex 414159fdd0f5..7874ea79bd87 100644--- a/rust/personhog-identity/src/storage/postgres/mod.rs+++ b/rust/personhog-identity/src/storage/postgres/mod.rs@@ -89,6 +89,15 @@ impl IdentityStorage for PostgresIdentityStorage {resolve::resolve_distinct_ids(&self.pools, &self.tables, keys).await}+ async fn resolve_person_ids(+ &self,+ keys: &[(i64, String)],+ ) -> StorageResult<HashMap<(i64, String), i64>> {+ let labels = Self::query_labels("resolve_person_ids", Lane::Fast);+ let _timer = common_metrics::timing_guard(DB_QUERY_DURATION, &labels);+ resolve::resolve_person_ids(&self.pools, &self.tables, keys).await+ }+async fn get_distinct_ids_for_persons(&self,team_id: i64,diff --git a/rust/personhog-identity/src/storage/postgres/resolve.rs b/rust/personhog-identity/src/storage/postgres/resolve.rsindex 51cf93eafa5b..c3ffcb0bc659 100644--- a/rust/personhog-identity/src/storage/postgres/resolve.rs+++ b/rust/personhog-identity/src/storage/postgres/resolve.rs@@ -2,6 +2,7 @@ use std::collections::HashMap;use chrono::{DateTime, Utc};use common_sqlx_macros::mirrored_query_as;+use personhog_common::query_tag;use uuid::Uuid;use crate::config::IdentityTables;@@ -83,3 +84,38 @@ pub(super) async fn resolve_distinct_ids(}Ok(resolved)}++pub(super) async fn resolve_person_ids(+ pools: &IdentityPools,+ tables: &IdentityTables,+ keys: &[(i64, String)],+) -> StorageResult<HashMap<(i64, String), i64>> {+ if keys.is_empty() {+ return Ok(HashMap::new());+ }++ let team_ids: Vec<i32> = keys.iter().map(|(t, _)| *t as i32).collect();+ let distinct_ids: Vec<String> = keys.iter().map(|(_, d)| d.clone()).collect();++ let sql = format!(+ r#"+ SELECT k.team_id, k.distinct_id, pdi.person_id+ FROM unnest($1::int[], $2::text[]) AS k(team_id, distinct_id)+ JOIN {pdi_table} pdi+ ON pdi.team_id = k.team_id AND pdi.distinct_id = k.distinct_id+ AND pdi.is_deleted = false+ "#,+ pdi_table = tables.person_distinct_id,+ );+ let mut conn = pools.acquire(Lane::Fast).await?;+ let rows: Vec<(i32, String, i64)> = sqlx::query_as(&query_tag!("resolve_person_ids", sql))+ .bind(&team_ids)+ .bind(&distinct_ids)+ .fetch_all(&mut *conn)+ .await?;++ Ok(rows+ .into_iter()+ .map(|(team_id, distinct_id, person_id)| ((i64::from(team_id), distinct_id), person_id))+ .collect())+}diff --git a/rust/personhog-identity/tests/common/mod.rs b/rust/personhog-identity/tests/common/mod.rsindex 72d13f28306d..94d609dd0d08 100644--- a/rust/personhog-identity/tests/common/mod.rs+++ b/rust/personhog-identity/tests/common/mod.rs@@ -293,6 +293,14 @@ impl personhog_identity::storage::IdentityStorage for UnusedStorage {panic!("not exercised by this test")}+ async fn resolve_person_ids(+ &self,+ _keys: &[(i64, String)],+ ) -> personhog_identity::storage::StorageResult<std::collections::HashMap<(i64, String), i64>>+ {+ panic!("not exercised by this test")+ }+async fn get_distinct_ids_for_persons(&self,_team_id: i64,@@ -372,6 +380,14 @@ impl personhog_identity::storage::IdentityStorage for RacingStorage {self.inner.resolve_distinct_ids(keys).await}+ async fn resolve_person_ids(+ &self,+ keys: &[(i64, String)],+ ) -> personhog_identity::storage::StorageResult<std::collections::HashMap<(i64, String), i64>>+ {+ self.inner.resolve_person_ids(keys).await+ }+async fn get_distinct_ids_for_persons(&self,team_id: i64,diff --git a/rust/personhog-identity/tests/lifecycle_delete_tests.rs b/rust/personhog-identity/tests/lifecycle_delete_tests.rsindex 458559aa07d2..708bae0af33d 100644--- a/rust/personhog-identity/tests/lifecycle_delete_tests.rs+++ b/rust/personhog-identity/tests/lifecycle_delete_tests.rs@@ -973,6 +973,12 @@ async fn full_flow_works_on_a_configured_person_table() {.await.expect("resolve succeeds");assert_eq!(resolved.get(&key).map(|p| p.id), Some(person_id));+ let resolved_ids = ctx+ .storage+ .resolve_person_ids(std::slice::from_ref(&key))+ .await+ .expect("ids-only resolve succeeds");+ assert_eq!(resolved_ids.get(&key), Some(&person_id));// Distinct id expansion must read the configured mapping table too.let mappings = ctx@@ -1048,6 +1054,15 @@ async fn full_flow_works_on_a_configured_person_table() {.await.expect("resolve after delete succeeds");assert!(resolved.is_empty(), "tombstoned person must not resolve");+ let resolved_ids = ctx+ .storage+ .resolve_person_ids(std::slice::from_ref(&key))+ .await+ .expect("ids-only resolve after delete succeeds");+ assert!(+ resolved_ids.is_empty(),+ "a tombstoned mapping must not resolve"+ );// The tmp mapping row tombstoned; the colliding real one untouched.let tmp_mapping_deleted: bool = sqlx::query_scalar(diff --git a/rust/personhog-identity/tests/service_tests.rs b/rust/personhog-identity/tests/service_tests.rsindex 7893b78ceb14..e079ce260004 100644--- a/rust/personhog-identity/tests/service_tests.rs+++ b/rust/personhog-identity/tests/service_tests.rs@@ -337,6 +337,7 @@ async fn resolve_returns_existing_persons_and_absence_without_creating() {distinct_id: "never-seen".to_string(),},],+ ids_only: false,})).await.expect("resolve must succeed")@@ -361,11 +362,40 @@ async fn resolve_returns_existing_persons_and_absence_without_creating() {team_id: t.ctx.team_id,distinct_id: "never-seen".to_string(),}],+ ids_only: false,})).await.expect("resolve must succeed").into_inner();assert!(again.results[0].person.is_none());++ let ids_only = t+ .service+ .get_persons_by_distinct_ids(Request::new(GetPersonsByDistinctIdsRequest {+ keys: vec![+ PersonKey {+ team_id: t.ctx.team_id,+ distinct_id: "known-id".to_string(),+ },+ PersonKey {+ team_id: t.ctx.team_id,+ distinct_id: "never-seen".to_string(),+ },+ ],+ ids_only: true,+ }))+ .await+ .expect("ids-only resolve must succeed")+ .into_inner();+ let known_ids_only = ids_only.results[0]+ .person+ .as_ref()+ .expect("known id resolves");+ assert_eq!(+ (known_ids_only.id, known_ids_only.team_id),+ (person.id, person.team_id)+ );+ assert!(ids_only.results[1].person.is_none());}/// The identity-side expansion mirrors the replica RPC's contract:@@ -418,6 +448,7 @@ async fn duplicate_resolve_keys_each_resolve() {.service.get_persons_by_distinct_ids(Request::new(GetPersonsByDistinctIdsRequest {keys: vec![key(), key(), key()],+ ids_only: false,})).await.expect("resolve must succeed")@@ -442,6 +473,7 @@ async fn new_rpcs_reject_wrapping_team_ids() {team_id: bad_team,distinct_id: "x".to_string(),}],+ ids_only: false,})).await;assert_eq!(resolve.unwrap_err().code(), Code::InvalidArgument);