Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(personhog): identity read RPCs — resolve and distinct-id expansion (#80701)

Zach Brown3e30a5e98ea4
diff --git a/proto/personhog/identity/v1/identity.proto b/proto/personhog/identity/v1/identity.proto
index c6f8aa4c9d6c..53c3b5b093d8 100644
--- a/proto/personhog/identity/v1/identity.proto
+++ b/proto/personhog/identity/v1/identity.proto
@@ -68,6 +68,49 @@ message GetOrCreatePersonsByDistinctIdsResponse {
repeated GetOrCreatePersonResult results = 1;
}
+// A single resolution key: distinct_id within team_id.
+message PersonKey {
+ int64 team_id = 1;
+ string distinct_id = 2;
+}
+
+message GetPersonsByDistinctIdsRequest {
+ // Max 250 per request. Keys may span teams.
+ repeated PersonKey keys = 1;
+}
+
+// The per-key outcome of a batch resolve. Mirrors GetOrCreatePersonResult
+// minus the creation fields: resolution never creates, so an absent key
+// is a result, not an error.
+message GetPersonByDistinctIdResult {
+ int64 team_id = 1;
+ string distinct_id = 2;
+ // Absent when the distinct id resolves to no live person — unknown,
+ // tombstoned, or its person deleted.
+ optional personhog.types.v1.Person person = 3;
+}
+
+message GetPersonsByDistinctIdsResponse {
+ // Same order as the request keys.
+ repeated GetPersonByDistinctIdResult results = 1;
+}
+
+// The identity-side twin of the service RPC of the same name, minus
+// ReadOptions: identity always reads the primary, so there is no
+// consistency to choose.
+message GetDistinctIdsForPersonsRequest {
+ int64 team_id = 1;
+ // Max 250 per request.
+ repeated int64 person_ids = 2;
+ // Max distinct ids returned per person; identified ids survive the
+ // cut. 0 or absent = no limit.
+ optional int64 limit_per_person = 3;
+}
+
+message GetDistinctIdsForPersonsResponse {
+ repeated personhog.types.v1.PersonDistinctIds person_distinct_ids = 1;
+}
+
// PersonHogIdentity owns the identity graph: distinct id resolution and
// get-or-create orchestration across the sync plane (Postgres primary) and
// the async plane (leader-owned properties). Ingestion calls this service
@@ -83,4 +126,12 @@ message GetOrCreatePersonsByDistinctIdsResponse {
service PersonHogIdentity {
rpc GetOrCreatePersonByDistinctId(GetOrCreatePersonByDistinctIdRequest) returns (GetOrCreatePersonByDistinctIdResponse);
rpc GetOrCreatePersonsByDistinctIds(GetOrCreatePersonsByDistinctIdsRequest) returns (GetOrCreatePersonsByDistinctIdsResponse);
+ // Resolve-only counterpart of get-or-create: same primary-backed
+ // resolution, same Person payload, never creates. This is the strong
+ // resolve — the router's GetPersonsByDistinctIds reads the replica and
+ // its consistency option does not change that.
+ rpc GetPersonsByDistinctIds(GetPersonsByDistinctIdsRequest) returns (GetPersonsByDistinctIdsResponse);
+ // Person-id to distinct-ids expansion on the primary; the strong twin
+ // of the router RPC of the same name (which reads the replica).
+ rpc GetDistinctIdsForPersons(GetDistinctIdsForPersonsRequest) returns (GetDistinctIdsForPersonsResponse);
}
diff --git a/rust/personhog-identity/.sqlx/query-8432c495e71b8f42f55c7f9338d6718e108ec2c4baf1e73555bf22588aaa9640.json b/rust/personhog-identity/.sqlx/query-8432c495e71b8f42f55c7f9338d6718e108ec2c4baf1e73555bf22588aaa9640.json
new file mode 100644
index 000000000000..a401cf2a632b
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-8432c495e71b8f42f55c7f9338d6718e108ec2c4baf1e73555bf22588aaa9640.json
@@ -0,0 +1,35 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT person_id, distinct_id, version\n FROM posthog_persondistinctid\n WHERE team_id = $1 AND person_id = ANY($2) AND is_deleted = false\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "person_id",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 1,
+ "name": "distinct_id",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 2,
+ "name": "version",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Int4",
+ "Int8Array"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ true
+ ]
+ },
+ "hash": "8432c495e71b8f42f55c7f9338d6718e108ec2c4baf1e73555bf22588aaa9640"
+}
diff --git a/rust/personhog-identity/.sqlx/query-e14a76228d22554c12b6b837fb8db1bb890726b380eba0255855b15427a926f3.json b/rust/personhog-identity/.sqlx/query-e14a76228d22554c12b6b837fb8db1bb890726b380eba0255855b15427a926f3.json
new file mode 100644
index 000000000000..03bea104c9bb
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-e14a76228d22554c12b6b837fb8db1bb890726b380eba0255855b15427a926f3.json
@@ -0,0 +1,36 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT l.person_id, l.distinct_id, l.version\n FROM UNNEST($2::bigint[]) AS pid(id)\n CROSS JOIN LATERAL (\n SELECT capped.person_id, capped.distinct_id, capped.version\n FROM (\n SELECT person_id, distinct_id, version, id\n FROM posthog_persondistinctid\n WHERE team_id = $1 AND person_id = pid.id AND is_deleted = false\n LIMIT 2500\n ) capped\n ORDER BY (capped.distinct_id ~ '^([a-z0-9]+-){4}[a-z0-9]+$'), capped.id\n LIMIT $3\n ) l\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "person_id",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 1,
+ "name": "distinct_id",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 2,
+ "name": "version",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Int4",
+ "Int8Array",
+ "Int8"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ true
+ ]
+ },
+ "hash": "e14a76228d22554c12b6b837fb8db1bb890726b380eba0255855b15427a926f3"
+}
diff --git a/rust/personhog-identity/src/service/mod.rs b/rust/personhog-identity/src/service/mod.rs
index b89003d8865c..4e3a647b176e 100644
--- a/rust/personhog-identity/src/service/mod.rs
+++ b/rust/personhog-identity/src/service/mod.rs
@@ -12,13 +12,18 @@ use tonic::{Request, Response, Status};
use personhog_proto::personhog::identity::v1::person_hog_identity_server::PersonHogIdentity;
use personhog_proto::personhog::identity::v1::{
+ GetDistinctIdsForPersonsRequest, GetDistinctIdsForPersonsResponse,
GetOrCreatePersonByDistinctIdRequest, GetOrCreatePersonByDistinctIdResponse,
GetOrCreatePersonResult, GetOrCreatePersonsByDistinctIdsRequest,
- GetOrCreatePersonsByDistinctIdsResponse,
+ GetOrCreatePersonsByDistinctIdsResponse, GetPersonByDistinctIdResult,
+ GetPersonsByDistinctIdsRequest, GetPersonsByDistinctIdsResponse,
};
+use personhog_proto::personhog::types::v1::{DistinctIdWithVersion, PersonDistinctIds};
use crate::leader::PropertyWriter;
-use crate::service::validation::{validate_batch_size, validate_entry, RequestLimits};
+use crate::service::validation::{
+ validate_batch_size, validate_entry, validate_team_id, RequestLimits,
+};
use crate::storage::IdentityStorage;
pub struct PersonHogIdentityService {
@@ -99,4 +104,90 @@ impl PersonHogIdentity for PersonHogIdentityService {
results,
}))
}
+
+ async fn get_persons_by_distinct_ids(
+ &self,
+ request: Request<GetPersonsByDistinctIdsRequest>,
+ ) -> Result<Response<GetPersonsByDistinctIdsResponse>, Status> {
+ let keys = request.into_inner().keys;
+ validate_batch_size(&self.limits, keys.len())?;
+ for key in &keys {
+ validate_team_id(key.team_id)?;
+ }
+
+ let identifiers: Vec<(i64, String)> = keys
+ .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 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);
+ GetPersonByDistinctIdResult {
+ team_id,
+ distinct_id,
+ person,
+ }
+ })
+ .collect();
+ Ok(Response::new(GetPersonsByDistinctIdsResponse { results }))
+ }
+
+ async fn get_distinct_ids_for_persons(
+ &self,
+ request: Request<GetDistinctIdsForPersonsRequest>,
+ ) -> Result<Response<GetDistinctIdsForPersonsResponse>, Status> {
+ let req = request.into_inner();
+ validate_team_id(req.team_id)?;
+ validate_batch_size(&self.limits, req.person_ids.len())?;
+
+ // Dedupe: the response groups by person, so a repeated id adds
+ // nothing — but the limited query's UNNEST + LATERAL runs per
+ // occurrence, and duplicated rows would merge into one group
+ // that exceeds the advertised per-person limit.
+ let mut person_ids = req.person_ids;
+ person_ids.sort_unstable();
+ person_ids.dedup();
+
+ let mappings = self
+ .storage
+ .get_distinct_ids_for_persons(req.team_id, &person_ids, req.limit_per_person)
+ .await
+ .map_err(|e| {
+ crate::service::error::log_and_convert_error(e, "get_distinct_ids_for_persons")
+ })?;
+
+ let mut by_person: std::collections::HashMap<i64, Vec<DistinctIdWithVersion>> =
+ std::collections::HashMap::new();
+ for mapping in mappings {
+ by_person
+ .entry(mapping.person_id)
+ .or_default()
+ .push(DistinctIdWithVersion {
+ distinct_id: mapping.distinct_id,
+ version: mapping.version,
+ });
+ }
+ let person_distinct_ids = by_person
+ .into_iter()
+ .map(|(person_id, distinct_ids)| PersonDistinctIds {
+ person_id,
+ distinct_ids,
+ })
+ .collect();
+ Ok(Response::new(GetDistinctIdsForPersonsResponse {
+ person_distinct_ids,
+ }))
+ }
}
diff --git a/rust/personhog-identity/src/service/validation.rs b/rust/personhog-identity/src/service/validation.rs
index 83c05b86f42b..2c7f608472a3 100644
--- a/rust/personhog-identity/src/service/validation.rs
+++ b/rust/personhog-identity/src/service/validation.rs
@@ -16,6 +16,20 @@ pub struct RequestLimits {
// tonic Status is a large Err variant; boxing here would diverge from the
// tonic handler signatures these feed into.
+
+/// The persons DB stores team_id as int4 and the storage layer narrows
+/// with `as i32` — an unchecked value above i32::MAX would wrap and read
+/// another tenant's rows.
+#[allow(clippy::result_large_err)]
+pub fn validate_team_id(team_id: i64) -> Result<(), Status> {
+ if team_id <= 0 || team_id > i32::MAX as i64 {
+ return Err(Status::invalid_argument(
+ "team_id must be a positive 32-bit integer",
+ ));
+ }
+ Ok(())
+}
+
#[allow(clippy::result_large_err)]
pub fn validate_batch_size(limits: &RequestLimits, len: usize) -> Result<(), Status> {
if len > limits.max_batch_size {
diff --git a/rust/personhog-identity/src/storage/mod.rs b/rust/personhog-identity/src/storage/mod.rs
index 54506e620617..9401f23b23fa 100644
--- a/rust/personhog-identity/src/storage/mod.rs
+++ b/rust/personhog-identity/src/storage/mod.rs
@@ -7,7 +7,7 @@ use std::collections::HashMap;
use async_trait::async_trait;
pub use error::{StorageError, StorageResult};
-pub use types::{Person, PersonStub, StubOutcome};
+pub use types::{DistinctIdMapping, Person, PersonStub, StubOutcome};
pub const DB_QUERY_DURATION: &str = "personhog_identity_db_query_duration_ms";
@@ -23,6 +23,17 @@ pub trait IdentityStorage: Send + Sync {
keys: &[(i64, String)],
) -> StorageResult<HashMap<(i64, String), Person>>;
+ /// 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 ordering
+ /// contract as the replica's expansion.
+ async fn get_distinct_ids_for_persons(
+ &self,
+ team_id: i64,
+ person_ids: &[i64],
+ limit_per_person: Option<i64>,
+ ) -> StorageResult<Vec<DistinctIdMapping>>;
+
/// Create person stubs (uuidv5 from team_id:distinct_id, version 0, empty
/// properties) plus their distinct id rows in one multi-row transaction.
/// Safe to race: unique conflicts resolve per row to the winner instead of
diff --git a/rust/personhog-identity/src/storage/postgres/distinct_ids.rs b/rust/personhog-identity/src/storage/postgres/distinct_ids.rs
new file mode 100644
index 000000000000..12ae1b3f4112
--- /dev/null
+++ b/rust/personhog-identity/src/storage/postgres/distinct_ids.rs
@@ -0,0 +1,63 @@
+use sqlx::postgres::PgPool;
+
+use crate::storage::error::StorageResult;
+use crate::storage::types::DistinctIdMapping;
+
+/// Expand person ids to live distinct id rows on the primary. With a
+/// per-person limit, identified ids survive the cut (the regex mirrors
+/// ANONYMOUS_REGEX in posthog/utils.py) and the scan is capped for
+/// pathological persons — the same ordering contract as the replica's
+/// expansion, so callers can switch sources without behavior change.
+pub(super) async fn get_distinct_ids_for_persons(
+ pool: &PgPool,
+ team_id: i64,
+ person_ids: &[i64],
+ limit_per_person: Option<i64>,
+) -> StorageResult<Vec<DistinctIdMapping>> {
+ if person_ids.is_empty() {
+ return Ok(Vec::new());
+ }
+
+ let rows = match limit_per_person {
+ Some(limit) if limit > 0 => {
+ sqlx::query_as!(
+ DistinctIdMapping,
+ r#"
+ SELECT l.person_id, l.distinct_id, l.version
+ FROM UNNEST($2::bigint[]) AS pid(id)
+ CROSS JOIN LATERAL (
+ SELECT capped.person_id, capped.distinct_id, capped.version
+ FROM (
+ SELECT person_id, distinct_id, version, id
+ FROM posthog_persondistinctid
+ WHERE team_id = $1 AND person_id = pid.id AND is_deleted = false
+ LIMIT 2500
+ ) capped
+ ORDER BY (capped.distinct_id ~ '^([a-z0-9]+-){4}[a-z0-9]+$'), capped.id
+ LIMIT $3
+ ) l
+ "#,
+ team_id as i32,
+ person_ids,
+ limit
+ )
+ .fetch_all(pool)
+ .await?
+ }
+ _ => {
+ sqlx::query_as!(
+ DistinctIdMapping,
+ r#"
+ SELECT person_id, distinct_id, version
+ FROM posthog_persondistinctid
+ WHERE team_id = $1 AND person_id = ANY($2) AND is_deleted = false
+ "#,
+ team_id as i32,
+ person_ids
+ )
+ .fetch_all(pool)
+ .await?
+ }
+ };
+ Ok(rows)
+}
diff --git a/rust/personhog-identity/src/storage/postgres/mod.rs b/rust/personhog-identity/src/storage/postgres/mod.rs
index 58810359d760..eef74adaf487 100644
--- a/rust/personhog-identity/src/storage/postgres/mod.rs
+++ b/rust/personhog-identity/src/storage/postgres/mod.rs
@@ -2,6 +2,7 @@
//! trait method's logic lives in its own submodule (`resolve`,
//! `stub_create`), keyed by the metrics operation label.
+mod distinct_ids;
mod resolve;
mod stub_create;
@@ -13,7 +14,7 @@ use sqlx::postgres::PgPool;
use personhog_common::grpc::{current_client_name, current_method_name};
use crate::storage::error::StorageResult;
-use crate::storage::types::{Person, PersonStub, StubOutcome};
+use crate::storage::types::{DistinctIdMapping, Person, PersonStub, StubOutcome};
use crate::storage::{IdentityStorage, DB_QUERY_DURATION};
const POOL_LABEL: &str = "primary";
@@ -48,6 +49,23 @@ impl IdentityStorage for PostgresIdentityStorage {
resolve::resolve_distinct_ids(&self.primary_pool, keys).await
}
+ async fn get_distinct_ids_for_persons(
+ &self,
+ team_id: i64,
+ person_ids: &[i64],
+ limit_per_person: Option<i64>,
+ ) -> StorageResult<Vec<DistinctIdMapping>> {
+ let labels = Self::query_labels("get_distinct_ids_for_persons");
+ let _timer = common_metrics::timing_guard(DB_QUERY_DURATION, &labels);
+ distinct_ids::get_distinct_ids_for_persons(
+ &self.primary_pool,
+ team_id,
+ person_ids,
+ limit_per_person,
+ )
+ .await
+ }
+
async fn create_person_stubs(&self, stubs: &[PersonStub]) -> StorageResult<Vec<StubOutcome>> {
let labels = Self::query_labels("create_person_stubs");
let _timer = common_metrics::timing_guard(DB_QUERY_DURATION, &labels);
diff --git a/rust/personhog-identity/src/storage/types.rs b/rust/personhog-identity/src/storage/types.rs
index 97ea88a7982e..9ec64519a173 100644
--- a/rust/personhog-identity/src/storage/types.rs
+++ b/rust/personhog-identity/src/storage/types.rs
@@ -23,3 +23,11 @@ pub enum StubOutcome {
/// the transaction rolled back. The caller re-resolves to find the winner.
LostRace,
}
+
+/// One live distinct id row for a person.
+#[derive(Debug, Clone)]
+pub struct DistinctIdMapping {
+ pub person_id: i64,
+ pub distinct_id: String,
+ pub version: Option<i64>,
+}
diff --git a/rust/personhog-identity/tests/service_tests.rs b/rust/personhog-identity/tests/service_tests.rs
index 5ab34575fce4..6494a6cd3da3 100644
--- a/rust/personhog-identity/tests/service_tests.rs
+++ b/rust/personhog-identity/tests/service_tests.rs
@@ -12,8 +12,8 @@ use personhog_identity::service::validation::RequestLimits;
use personhog_identity::service::PersonHogIdentityService;
use personhog_proto::personhog::identity::v1::person_hog_identity_server::PersonHogIdentity;
use personhog_proto::personhog::identity::v1::{
- GetOrCreatePersonByDistinctIdRequest, GetOrCreatePersonEntry,
- GetOrCreatePersonsByDistinctIdsRequest,
+ GetDistinctIdsForPersonsRequest, GetOrCreatePersonByDistinctIdRequest, GetOrCreatePersonEntry,
+ GetOrCreatePersonsByDistinctIdsRequest, GetPersonsByDistinctIdsRequest, PersonKey,
};
use personhog_proto::personhog::types::v1::{
UpdatePersonPropertiesRequest, UpdatePersonPropertiesResponse,
@@ -292,3 +292,177 @@ async fn batch_over_limit_is_rejected() {
t.ctx.cleanup().await.ok();
}
+
+/// The resolve-only RPC answers exactly like get-or-create for existing
+/// persons and answers absence instead of creating for unknown keys — the
+/// contract the node store's fetch paths rely on.
+#[tokio::test]
+async fn resolve_returns_existing_persons_and_absence_without_creating() {
+ let t = ServiceTestContext::new().await;
+ t.get_or_create_single(t.entry("known-id"))
+ .await
+ .expect("seed person");
+
+ let response = 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(),
+ },
+ ],
+ }))
+ .await
+ .expect("resolve must succeed")
+ .into_inner();
+
+ assert_eq!(response.results.len(), 2);
+ let known = &response.results[0];
+ assert_eq!(known.distinct_id, "known-id");
+ let person = known.person.as_ref().expect("known id resolves");
+ assert!(person.id > 0);
+
+ let unknown = &response.results[1];
+ assert_eq!(unknown.distinct_id, "never-seen");
+ assert!(unknown.person.is_none(), "resolve must not create");
+
+ // A second resolve still finds nothing for the unknown key — the
+ // first call created no row.
+ let again = t
+ .service
+ .get_persons_by_distinct_ids(Request::new(GetPersonsByDistinctIdsRequest {
+ keys: vec![PersonKey {
+ team_id: t.ctx.team_id,
+ distinct_id: "never-seen".to_string(),
+ }],
+ }))
+ .await
+ .expect("resolve must succeed")
+ .into_inner();
+ assert!(again.results[0].person.is_none());
+}
+
+/// The identity-side expansion mirrors the replica RPC's contract:
+/// grouped per person, live rows only, and the per-person limit keeps
+/// identified ids over anonymous ones.
+#[tokio::test]
+async fn distinct_id_expansion_groups_per_person_on_the_primary() {
+ let t = ServiceTestContext::new().await;
+ let (person_id, _) = t
+ .get_or_create_single(t.entry("expansion-primary"))
+ .await
+ .expect("seed person");
+ let person_id = person_id.expect("seeded person has an id");
+
+ let response = t
+ .service
+ .get_distinct_ids_for_persons(Request::new(GetDistinctIdsForPersonsRequest {
+ team_id: t.ctx.team_id,
+ person_ids: vec![person_id, 999_999_999],
+ limit_per_person: None,
+ }))
+ .await
+ .expect("expansion must succeed")
+ .into_inner();
+
+ assert_eq!(
+ response.person_distinct_ids.len(),
+ 1,
+ "absent ids yield no group"
+ );
+ let group = &response.person_distinct_ids[0];
+ assert_eq!(group.person_id, person_id);
+ assert_eq!(group.distinct_ids.len(), 1);
+ assert_eq!(group.distinct_ids[0].distinct_id, "expansion-primary");
+}
+
+/// Duplicate keys in one resolve request each get the person — the node
+/// prefetch sends per-event keys where hot distinct ids repeat.
+#[tokio::test]
+async fn duplicate_resolve_keys_each_resolve() {
+ let t = ServiceTestContext::new().await;
+ t.get_or_create_single(t.entry("dup-id"))
+ .await
+ .expect("seed");
+ let key = || PersonKey {
+ team_id: t.ctx.team_id,
+ distinct_id: "dup-id".to_string(),
+ };
+ let response = t
+ .service
+ .get_persons_by_distinct_ids(Request::new(GetPersonsByDistinctIdsRequest {
+ keys: vec![key(), key(), key()],
+ }))
+ .await
+ .expect("resolve must succeed")
+ .into_inner();
+ assert_eq!(response.results.len(), 3);
+ for result in &response.results {
+ assert!(result.person.is_some(), "every occurrence must resolve");
+ }
+}
+
+/// A team_id above i32::MAX would wrap at the int4 column and read
+/// another tenant's rows; both new RPCs must refuse it at the boundary.
+#[tokio::test]
+async fn new_rpcs_reject_wrapping_team_ids() {
+ let t = ServiceTestContext::new().await;
+ let bad_team = (i32::MAX as i64) + 2;
+
+ let resolve = t
+ .service
+ .get_persons_by_distinct_ids(Request::new(GetPersonsByDistinctIdsRequest {
+ keys: vec![PersonKey {
+ team_id: bad_team,
+ distinct_id: "x".to_string(),
+ }],
+ }))
+ .await;
+ assert_eq!(resolve.unwrap_err().code(), Code::InvalidArgument);
+
+ let expand = t
+ .service
+ .get_distinct_ids_for_persons(Request::new(GetDistinctIdsForPersonsRequest {
+ team_id: bad_team,
+ person_ids: vec![1],
+ limit_per_person: None,
+ }))
+ .await;
+ assert_eq!(expand.unwrap_err().code(), Code::InvalidArgument);
+}
+
+/// A repeated person id must not multiply its rows: the limited query
+/// runs its lateral lookup per occurrence, so without dedupe one group
+/// would carry duplicates and exceed the advertised per-person limit.
+#[tokio::test]
+async fn repeated_person_ids_do_not_exceed_the_per_person_limit() {
+ let t = ServiceTestContext::new().await;
+ let mut entry = t.entry("dup-expand-primary");
+ entry.extra_distinct_ids = vec!["dup-expand-extra".to_string()];
+ let (person_id, _) = t.get_or_create_single(entry).await.expect("seed");
+ let person_id = person_id.expect("seeded person has an id");
+
+ let response = t
+ .service
+ .get_distinct_ids_for_persons(Request::new(GetDistinctIdsForPersonsRequest {
+ team_id: t.ctx.team_id,
+ person_ids: vec![person_id, person_id, person_id],
+ limit_per_person: Some(1),
+ }))
+ .await
+ .expect("expansion must succeed")
+ .into_inner();
+
+ assert_eq!(response.person_distinct_ids.len(), 1);
+ let group = &response.person_distinct_ids[0];
+ assert_eq!(
+ group.distinct_ids.len(),
+ 1,
+ "the per-person limit must hold under repeated ids"
+ );
+}