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): add identity service with get-or-create person RPCs (#73257)

José Sequeira4fbdaf5b34b6
diff --git a/.github/rust-images.yml b/.github/rust-images.yml
index e32bafbe7a42..9fbbf8ea2427 100644
--- a/.github/rust-images.yml
+++ b/.github/rust-images.yml
@@ -102,6 +102,10 @@
dockerfile: ./rust/Dockerfile
project: vznmbshh6q
+- image: personhog-identity
+ dockerfile: ./rust/Dockerfile
+ project: jfz76fgvqd
+
- image: personhog-leader
dockerfile: ./rust/Dockerfile
project: g0kjbvxgqx
diff --git a/.github/workflows/ci-rust.yml b/.github/workflows/ci-rust.yml
index 81160f0d0552..7fe1d45a06b1 100644
--- a/.github/workflows/ci-rust.yml
+++ b/.github/workflows/ci-rust.yml
@@ -150,6 +150,7 @@ jobs:
"lifecycle": 17,
"limiters": 25,
"personhog-coordination": 24,
+ "personhog-identity": 40,
"personhog-leader": 115,
"personhog-replica": 140,
"personhog-router": 38,
@@ -559,7 +560,7 @@ jobs:
sqlx migrate run --source persons_migrations/
- name: Build the personhog stack and harness
- run: cargo build -p personhog-replica -p personhog-router -p personhog-leader -p personhog-writer -p personhog-test-harness
+ run: cargo build -p personhog-replica -p personhog-router -p personhog-leader -p personhog-writer -p personhog-identity -p personhog-test-harness
# Unit tests for the harness's own verification logic — a
# false-negative verifier would pass gates that lost data.
@@ -571,6 +572,22 @@ jobs:
./target/debug/personhog-test-harness gate \
--leaders 2 --partitions 4 --persons 100 --concurrency 10 --duration 10s
+ # The identity-service create path: persons are created through
+ # GetOrCreatePersonsByDistinctIds (stub insert on the primary,
+ # then initial properties through the router to the owning
+ # leader) and then updated through the router. Create acks are
+ # journaled and held to the same visibility invariant as update
+ # acks, through a leader kill and a scale-up. The identity
+ # service writes the real posthog_person table (its distinct id
+ # FKs require it), so the whole stack targets it here instead of
+ # the default personhog_person_tmp.
+ - name: Run the e2e gate creating persons via the identity service
+ run: |
+ ./target/debug/personhog-test-harness gate \
+ --create-via-identity --pg-target-table posthog_person \
+ --leaders 3 --partitions 8 --persons 100 \
+ --concurrency 10 --duration 15s --kill-after 5s --scale-up-after 8s
+
# Regression gate for eviction under writer lag: the cache is
# sized far below the person count so dirty entries evict while
# the paused writer guarantees their PG rows are stale. Before
diff --git a/.github/workflows/rust-docker-build.yml b/.github/workflows/rust-docker-build.yml
index f42aacd731f0..01276a479d1d 100644
--- a/.github/workflows/rust-docker-build.yml
+++ b/.github/workflows/rust-docker-build.yml
@@ -180,6 +180,9 @@ jobs:
- release: sqlx-migrate
digest_key: sqlx-migrate
values_key: image
+ - release: personhog-identity
+ digest_key: personhog-identity
+ values_key: image
- release: personhog-leader
digest_key: personhog-leader
values_key: image
diff --git a/bin/mprocs.yaml b/bin/mprocs.yaml
index e2704523b6e9..f936e5ef6786 100755
--- a/bin/mprocs.yaml
+++ b/bin/mprocs.yaml
@@ -479,6 +479,16 @@ procs:
layer: Product services
tech: Rust
+ personhog-identity:
+ shell: |-
+ bin/wait-for-docker && \
+ bin/start-rust-service personhog-identity
+ capability: personhog
+ ready_pattern: 'Metrics server listening on *'
+ groups:
+ layer: Product services
+ tech: Rust
+
personhog-etcd-init:
shell: |-
bin/wait-for-docker && \
diff --git a/bin/start-rust-service b/bin/start-rust-service
index 04a89076ba8a..9361ea21083a 100755
--- a/bin/start-rust-service
+++ b/bin/start-rust-service
@@ -285,6 +285,16 @@ case "$RS_SVC" in
export METRICS_PORT=9101
;;
+ personhog-identity)
+ SQLX_QUERY_LEVEL=${SQLX_QUERY_LEVEL:-trace}
+ export RUST_LOG=debug,sqlx::query=$SQLX_QUERY_LEVEL
+ export RUST_BACKTRACE=1
+ export GRPC_ADDRESS=127.0.0.1:50055
+ export PRIMARY_DATABASE_URL="${PRIMARY_DATABASE_URL:-postgres://posthog:posthog@${PGHOST:-db}:${PGPORT:-5432}/posthog_persons}"
+ export ROUTER_URL=http://127.0.0.1:50054
+ export METRICS_PORT=9108
+ ;;
+
flags-consumer)
SQLX_QUERY_LEVEL=${SQLX_QUERY_LEVEL:-warn}
export RUST_LOG=debug,sqlx::query=$SQLX_QUERY_LEVEL,rdkafka=warn
diff --git a/proto/personhog/identity/v1/identity.proto b/proto/personhog/identity/v1/identity.proto
new file mode 100644
index 000000000000..c6f8aa4c9d6c
--- /dev/null
+++ b/proto/personhog/identity/v1/identity.proto
@@ -0,0 +1,86 @@
+syntax = "proto3";
+package personhog.identity.v1;
+
+import "personhog/types/v1/person.proto";
+
+// GetOrCreatePersonEntry is a single get-or-create key: resolve distinct_id
+// within team_id, creating a person stub when absent. The properties and
+// scalars are used on the creation branch only — when the person already
+// exists the caller applies $set/$set_once through UpdatePersonProperties.
+message GetOrCreatePersonEntry {
+ int64 team_id = 1;
+ // The primary distinct id. The person UUID derives deterministically from
+ // team_id:distinct_id, so its distinct id row is always version 0.
+ string distinct_id = 2;
+ // Additional distinct ids mapped to the person on the creation branch.
+ // Their rows get version 1 when the distinct id has personless history
+ // (a posthog_personlessdistinctid row already existed), else version 0.
+ // An extra already mapped to a different person keeps its existing
+ // mapping: get-or-create never re-points or merges, so the conflict is
+ // not an error and is not reported — re-pointing distinct ids is the
+ // merge path's job.
+ repeated string extra_distinct_ids = 3;
+ // The event name that triggered this call (e.g. "$identify", "$pageview").
+ // Forwarded to the leader's property update on the creation branch.
+ string event_name = 4;
+ // JSON-encoded $set map, applied via the leader on the creation branch.
+ bytes set_properties = 5;
+ // JSON-encoded $set_once map, applied via the leader on the creation branch.
+ bytes set_once_properties = 6;
+ // Person created_at, epoch millis. Used on the creation branch.
+ int64 created_at = 7;
+ bool is_identified = 8;
+}
+
+message GetOrCreatePersonByDistinctIdRequest {
+ GetOrCreatePersonEntry entry = 1;
+}
+
+// created = true means the stub row is committed in Postgres AND the initial
+// properties (when provided) are durable in the leader's changelog.
+message GetOrCreatePersonByDistinctIdResponse {
+ personhog.types.v1.Person person = 1;
+ bool created = 2;
+}
+
+message GetOrCreatePersonsByDistinctIdsRequest {
+ // Max 250 per request. Keys may span teams; each entry is independent and
+ // individually retryable.
+ repeated GetOrCreatePersonEntry entries = 1;
+}
+
+// GetOrCreatePersonResult is the per-key outcome of a batch get-or-create.
+message GetOrCreatePersonResult {
+ int64 team_id = 1;
+ string distinct_id = 2;
+ // Absent when this key failed (see error).
+ optional personhog.types.v1.Person person = 3;
+ bool created = 4;
+ // Set when this key failed; the caller should retry the key. A committed
+ // stub whose initial-properties write failed surfaces here — the retried
+ // key resolves to the stub (created = false) and applies properties through
+ // the normal update path.
+ optional string error = 5;
+}
+
+message GetOrCreatePersonsByDistinctIdsResponse {
+ // Same order as the request entries.
+ repeated GetOrCreatePersonResult results = 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
+// directly; it is not fronted by the router.
+//
+// Get-or-create semantics: created = true means the person stub row is
+// committed in Postgres AND the initial properties (when provided) are
+// durable in the leader's changelog. A crash between the stub commit and the
+// leader ack surfaces as an error; the retried key resolves to the stub
+// (created = false) and the caller applies properties through the normal
+// UpdatePersonProperties path — the event remains the durable source of the
+// initial properties.
+service PersonHogIdentity {
+ rpc GetOrCreatePersonByDistinctId(GetOrCreatePersonByDistinctIdRequest) returns (GetOrCreatePersonByDistinctIdResponse);
+ rpc GetOrCreatePersonsByDistinctIds(GetOrCreatePersonsByDistinctIdsRequest) returns (GetOrCreatePersonsByDistinctIdsResponse);
+}
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index 025cf68537f8..c01b909016e7 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -7715,6 +7715,30 @@ dependencies = [
"uuid",
]
+[[package]]
+name = "personhog-identity"
+version = "0.1.0"
+dependencies = [
+ "async-trait",
+ "axum 0.7.9",
+ "chrono",
+ "common-alloc",
+ "common-database",
+ "common-metrics",
+ "envconfig",
+ "futures",
+ "lifecycle",
+ "personhog-common",
+ "personhog-proto",
+ "rand 0.8.5",
+ "sqlx",
+ "tokio",
+ "tonic 0.12.3",
+ "tracing",
+ "tracing-subscriber",
+ "uuid",
+]
+
[[package]]
name = "personhog-leader"
version = "0.1.0"
@@ -7847,6 +7871,7 @@ dependencies = [
"hdrhistogram",
"humantime",
"metrics",
+ "personhog-common",
"personhog-coordination",
"personhog-proto",
"rand 0.8.5",
diff --git a/rust/Cargo.toml b/rust/Cargo.toml
index 3d4fe29f491a..312fbb66da1f 100644
--- a/rust/Cargo.toml
+++ b/rust/Cargo.toml
@@ -57,6 +57,7 @@ members = [
"kafka-deduplicator",
"personhog-common",
"personhog-coordination",
+ "personhog-identity",
"personhog-leader",
"personhog-writer",
"personhog-proto",
diff --git a/rust/affected-services/determinator-rules.toml b/rust/affected-services/determinator-rules.toml
index 36bd08c173f1..4afb273c7ba9 100644
--- a/rust/affected-services/determinator-rules.toml
+++ b/rust/affected-services/determinator-rules.toml
@@ -101,5 +101,6 @@ on-affected = [
"personhog-router",
"personhog-leader",
"personhog-writer",
+ "personhog-identity",
]
mark-changed = ["personhog-test-harness"]
diff --git a/rust/personhog-identity/.sqlx/query-423195f96062037eb486b038c35db0a8556ba0d7f054b6bd661a4b5e514e397b.json b/rust/personhog-identity/.sqlx/query-423195f96062037eb486b038c35db0a8556ba0d7f054b6bd661a4b5e514e397b.json
new file mode 100644
index 000000000000..9ab855fe5db6
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-423195f96062037eb486b038c35db0a8556ba0d7f054b6bd661a4b5e514e397b.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT person_id FROM posthog_persondistinctid WHERE team_id = $1 AND distinct_id = $2",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "person_id",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Int4",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "423195f96062037eb486b038c35db0a8556ba0d7f054b6bd661a4b5e514e397b"
+}
diff --git a/rust/personhog-identity/.sqlx/query-4501d897722f15a3966ba862b7c2dd8117edcc4aaddd4eee6e169c151e7ac56d.json b/rust/personhog-identity/.sqlx/query-4501d897722f15a3966ba862b7c2dd8117edcc4aaddd4eee6e169c151e7ac56d.json
new file mode 100644
index 000000000000..588fa587a66c
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-4501d897722f15a3966ba862b7c2dd8117edcc4aaddd4eee6e169c151e7ac56d.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "DELETE FROM posthog_person WHERE team_id = $1 AND id = $2",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Int4",
+ "Int8"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "4501d897722f15a3966ba862b7c2dd8117edcc4aaddd4eee6e169c151e7ac56d"
+}
diff --git a/rust/personhog-identity/.sqlx/query-5a2c4ddc7893ddc7e538ceec011db61fe93a7caa738953b10401542e24168d81.json b/rust/personhog-identity/.sqlx/query-5a2c4ddc7893ddc7e538ceec011db61fe93a7caa738953b10401542e24168d81.json
new file mode 100644
index 000000000000..d06de8aca676
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-5a2c4ddc7893ddc7e538ceec011db61fe93a7caa738953b10401542e24168d81.json
@@ -0,0 +1,37 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO posthog_persondistinctid (distinct_id, person_id, team_id, version)\n SELECT d, p, t, v FROM unnest($1::text[], $2::bigint[], $3::int[], $4::bigint[])\n AS u(d, p, t, v)\n ON CONFLICT (team_id, distinct_id) DO NOTHING\n RETURNING team_id::bigint as \"team_id!\", distinct_id, person_id\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "team_id!",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 1,
+ "name": "distinct_id",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 2,
+ "name": "person_id",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "TextArray",
+ "Int8Array",
+ "Int4Array",
+ "Int8Array"
+ ]
+ },
+ "nullable": [
+ null,
+ false,
+ false
+ ]
+ },
+ "hash": "5a2c4ddc7893ddc7e538ceec011db61fe93a7caa738953b10401542e24168d81"
+}
diff --git a/rust/personhog-identity/.sqlx/query-62e9588b4f822c063707416bec0cfc4e9ca9fdab71bad9b589fab3445b0faf1c.json b/rust/personhog-identity/.sqlx/query-62e9588b4f822c063707416bec0cfc4e9ca9fdab71bad9b589fab3445b0faf1c.json
new file mode 100644
index 000000000000..35b65adb925a
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-62e9588b4f822c063707416bec0cfc4e9ca9fdab71bad9b589fab3445b0faf1c.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "DELETE FROM posthog_persondistinctid WHERE team_id = $1 AND person_id = $2",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Int4",
+ "Int8"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "62e9588b4f822c063707416bec0cfc4e9ca9fdab71bad9b589fab3445b0faf1c"
+}
diff --git a/rust/personhog-identity/.sqlx/query-a0a0e59de0ba70e26bb6262d08a9d258e6f0a3bf0f0a7844474a6b299dc5403d.json b/rust/personhog-identity/.sqlx/query-a0a0e59de0ba70e26bb6262d08a9d258e6f0a3bf0f0a7844474a6b299dc5403d.json
new file mode 100644
index 000000000000..73b8c94db0b6
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-a0a0e59de0ba70e26bb6262d08a9d258e6f0a3bf0f0a7844474a6b299dc5403d.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n DELETE FROM posthog_personlessdistinctid pl\n USING unnest($1::int[], $2::text[]) AS u(t, d)\n WHERE pl.team_id = u.t AND pl.distinct_id = u.d\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Int4Array",
+ "TextArray"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "a0a0e59de0ba70e26bb6262d08a9d258e6f0a3bf0f0a7844474a6b299dc5403d"
+}
diff --git a/rust/personhog-identity/.sqlx/query-a9bfb47f93f0fadcc0a05a5182eb9e488ac1ecd1fd6517d3f23adaa2979e4b2d.json b/rust/personhog-identity/.sqlx/query-a9bfb47f93f0fadcc0a05a5182eb9e488ac1ecd1fd6517d3f23adaa2979e4b2d.json
new file mode 100644
index 000000000000..58adcd8132b5
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-a9bfb47f93f0fadcc0a05a5182eb9e488ac1ecd1fd6517d3f23adaa2979e4b2d.json
@@ -0,0 +1,95 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT k.team_id as \"key_team_id!\", k.distinct_id as \"key_distinct_id!\",\n p.id as \"id!\", p.uuid as \"uuid!\", p.team_id::bigint as \"team_id!\",\n p.properties::text as \"properties?\",\n p.properties_last_updated_at::text as \"properties_last_updated_at?\",\n p.properties_last_operation::text as \"properties_last_operation?\",\n p.created_at as \"created_at!\", p.version, p.is_identified as \"is_identified!\",\n CASE WHEN p.is_user_id IS NULL THEN NULL ELSE (p.is_user_id != 0) END as is_user_id,\n p.last_seen_at\n FROM unnest($1::int[], $2::text[]) AS k(team_id, distinct_id)\n JOIN posthog_persondistinctid pdi\n ON pdi.team_id = k.team_id AND pdi.distinct_id = k.distinct_id\n JOIN posthog_person p\n ON p.team_id = pdi.team_id AND p.id = pdi.person_id\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "key_team_id!",
+ "type_info": "Int4"
+ },
+ {
+ "ordinal": 1,
+ "name": "key_distinct_id!",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "id!",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 3,
+ "name": "uuid!",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 4,
+ "name": "team_id!",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 5,
+ "name": "properties?",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 6,
+ "name": "properties_last_updated_at?",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 7,
+ "name": "properties_last_operation?",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 8,
+ "name": "created_at!",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 9,
+ "name": "version",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 10,
+ "name": "is_identified!",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 11,
+ "name": "is_user_id",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 12,
+ "name": "last_seen_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Int4Array",
+ "TextArray"
+ ]
+ },
+ "nullable": [
+ null,
+ null,
+ false,
+ false,
+ null,
+ null,
+ null,
+ null,
+ false,
+ true,
+ false,
+ null,
+ true
+ ]
+ },
+ "hash": "a9bfb47f93f0fadcc0a05a5182eb9e488ac1ecd1fd6517d3f23adaa2979e4b2d"
+}
diff --git a/rust/personhog-identity/.sqlx/query-b69ec4c1a3eaba4a40ef4c0fbbc3b3473ad6dbc501a3933a10ce759a36362677.json b/rust/personhog-identity/.sqlx/query-b69ec4c1a3eaba4a40ef4c0fbbc3b3473ad6dbc501a3933a10ce759a36362677.json
new file mode 100644
index 000000000000..7f635092e1fc
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-b69ec4c1a3eaba4a40ef4c0fbbc3b3473ad6dbc501a3933a10ce759a36362677.json
@@ -0,0 +1,83 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT p.id as \"id!\", p.uuid as \"uuid!\", p.team_id::bigint as \"team_id!\",\n p.properties::text as \"properties?\",\n p.properties_last_updated_at::text as \"properties_last_updated_at?\",\n p.properties_last_operation::text as \"properties_last_operation?\",\n p.created_at as \"created_at!\", p.version, p.is_identified as \"is_identified!\",\n CASE WHEN p.is_user_id IS NULL THEN NULL ELSE (p.is_user_id != 0) END as is_user_id,\n p.last_seen_at\n FROM posthog_person p\n JOIN unnest($1::int[], $2::uuid[]) AS k(team_id, uuid)\n ON p.team_id = k.team_id AND p.uuid = k.uuid\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id!",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 1,
+ "name": "uuid!",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 2,
+ "name": "team_id!",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 3,
+ "name": "properties?",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 4,
+ "name": "properties_last_updated_at?",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 5,
+ "name": "properties_last_operation?",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 6,
+ "name": "created_at!",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 7,
+ "name": "version",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 8,
+ "name": "is_identified!",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 9,
+ "name": "is_user_id",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 10,
+ "name": "last_seen_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Int4Array",
+ "UuidArray"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ null,
+ null,
+ null,
+ null,
+ false,
+ true,
+ false,
+ null,
+ true
+ ]
+ },
+ "hash": "b69ec4c1a3eaba4a40ef4c0fbbc3b3473ad6dbc501a3933a10ce759a36362677"
+}
diff --git a/rust/personhog-identity/.sqlx/query-d8b6bab380a1ace8a636722d9733fc1609a2b044b46efdadd316f0a5652c5955.json b/rust/personhog-identity/.sqlx/query-d8b6bab380a1ace8a636722d9733fc1609a2b044b46efdadd316f0a5652c5955.json
new file mode 100644
index 000000000000..080fc404aebc
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-d8b6bab380a1ace8a636722d9733fc1609a2b044b46efdadd316f0a5652c5955.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE posthog_personlessdistinctid pl\n SET is_merged = false\n FROM unnest($1::int[], $2::text[]) AS u(t, d)\n WHERE pl.team_id = u.t AND pl.distinct_id = u.d\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Int4Array",
+ "TextArray"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "d8b6bab380a1ace8a636722d9733fc1609a2b044b46efdadd316f0a5652c5955"
+}
diff --git a/rust/personhog-identity/.sqlx/query-df8fe96a88ca9bdae39ca8a24e5b61aef4e6fec01aaa222fb6775d355ca1bf5d.json b/rust/personhog-identity/.sqlx/query-df8fe96a88ca9bdae39ca8a24e5b61aef4e6fec01aaa222fb6775d355ca1bf5d.json
new file mode 100644
index 000000000000..dafbfd7cb763
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-df8fe96a88ca9bdae39ca8a24e5b61aef4e6fec01aaa222fb6775d355ca1bf5d.json
@@ -0,0 +1,85 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO posthog_person\n (created_at, properties, properties_last_updated_at, properties_last_operation,\n team_id, is_identified, uuid, version, last_seen_at)\n SELECT u.created_at, '{}'::jsonb, '{}'::jsonb, '{}'::jsonb,\n u.team_id, u.is_identified, u.uuid, 0, date_trunc('hour', u.created_at)\n FROM unnest($1::timestamptz[], $2::int[], $3::bool[], $4::uuid[])\n AS u(created_at, team_id, is_identified, uuid)\n ON CONFLICT (team_id, uuid) DO NOTHING\n RETURNING id, uuid, team_id::bigint as \"team_id!\", properties::text as \"properties?\",\n properties_last_updated_at::text as \"properties_last_updated_at?\",\n properties_last_operation::text as \"properties_last_operation?\",\n created_at, version, is_identified,\n CASE WHEN is_user_id IS NULL THEN NULL ELSE (is_user_id != 0) END as is_user_id,\n last_seen_at\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 1,
+ "name": "uuid",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 2,
+ "name": "team_id!",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 3,
+ "name": "properties?",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 4,
+ "name": "properties_last_updated_at?",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 5,
+ "name": "properties_last_operation?",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 6,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 7,
+ "name": "version",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 8,
+ "name": "is_identified",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 9,
+ "name": "is_user_id",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 10,
+ "name": "last_seen_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "TimestamptzArray",
+ "Int4Array",
+ "BoolArray",
+ "UuidArray"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ null,
+ null,
+ null,
+ null,
+ false,
+ true,
+ false,
+ null,
+ true
+ ]
+ },
+ "hash": "df8fe96a88ca9bdae39ca8a24e5b61aef4e6fec01aaa222fb6775d355ca1bf5d"
+}
diff --git a/rust/personhog-identity/.sqlx/query-fa8aa398308891a81fb744122f3fecbb5fabf27d158099cb25adb33efe9ad280.json b/rust/personhog-identity/.sqlx/query-fa8aa398308891a81fb744122f3fecbb5fabf27d158099cb25adb33efe9ad280.json
new file mode 100644
index 000000000000..deb6980db07a
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-fa8aa398308891a81fb744122f3fecbb5fabf27d158099cb25adb33efe9ad280.json
@@ -0,0 +1,35 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO posthog_personlessdistinctid (distinct_id, is_merged, created_at, team_id)\n SELECT d, true, now(), t FROM unnest($1::int[], $2::text[]) AS u(t, d)\n ON CONFLICT (team_id, distinct_id) DO UPDATE SET is_merged = true\n WHERE posthog_personlessdistinctid.is_merged = false\n RETURNING team_id::bigint as \"team_id!\", distinct_id, (xmax = 0) as \"inserted!\"\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "team_id!",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 1,
+ "name": "distinct_id",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 2,
+ "name": "inserted!",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Int4Array",
+ "TextArray"
+ ]
+ },
+ "nullable": [
+ null,
+ false,
+ null
+ ]
+ },
+ "hash": "fa8aa398308891a81fb744122f3fecbb5fabf27d158099cb25adb33efe9ad280"
+}
diff --git a/rust/personhog-identity/Cargo.toml b/rust/personhog-identity/Cargo.toml
new file mode 100644
index 000000000000..6dcfd6e1a2bd
--- /dev/null
+++ b/rust/personhog-identity/Cargo.toml
@@ -0,0 +1,32 @@
+[package]
+name = "personhog-identity"
+version = "0.1.0"
+edition = "2021"
+publish = false
+
+[dependencies]
+personhog-common = { path = "../personhog-common" }
+personhog-proto = { path = "../personhog-proto" }
+common-database = { path = "../common/database" }
+common-alloc = { path = "../common/alloc" }
+common-metrics = { path = "../common/metrics" }
+lifecycle = { path = "../common/lifecycle" }
+
+async-trait = { workspace = true }
+axum = { workspace = true }
+chrono = { workspace = true }
+envconfig = { workspace = true }
+futures = { workspace = true }
+sqlx = { workspace = true }
+tokio = { workspace = true }
+tonic = { workspace = true }
+tracing = { workspace = true }
+tracing-subscriber = { workspace = true }
+uuid = { workspace = true }
+
+[dev-dependencies]
+rand = { workspace = true }
+tokio = { workspace = true, features = ["test-util"] }
+
+[lints]
+workspace = true
diff --git a/rust/personhog-identity/README.md b/rust/personhog-identity/README.md
new file mode 100644
index 000000000000..c15057b1c457
--- /dev/null
+++ b/rust/personhog-identity/README.md
@@ -0,0 +1,37 @@
+# personhog-identity
+
+The identity service of the personhog cluster. It owns the identity graph — distinct id resolution and get-or-create orchestration — per the personhog-identity saga RFC.
+
+Person state spans two planes:
+
+- the sync plane (Postgres primary), which owns existence, identity topology, and lifecycle scalars
+- the async plane (leader + changelog), which owns person property content
+
+`GetOrCreatePersonByDistinctId` / `GetOrCreatePersonsByDistinctIds` orchestrate both planes so a single ack covers both: `created = true` means the person stub is committed in Postgres AND the initial `$set`/`$set_once` are durable in the leader's changelog. The identity service never runs a saga; person-destroying operations (merge case 3, delete) belong to the lifecycle manager.
+
+## How get-or-create works
+
+1. Batch resolve `(team_id, distinct_id)` keys on the Postgres primary (one UNNEST probe).
+2. Misses get a person stub — deterministic uuidv5 of `team_id:distinct_id`, version 0, empty properties — plus distinct id rows, in one multi-row transaction with per-row `ON CONFLICT` handling. Extra distinct ids carry personless history forward (version 1 when a `posthog_personlessdistinctid` row already existed).
+3. Created stubs fan out initial properties to their owning leaders through the router (`UpdatePersonProperties` with `x-team-id`/`x-person-id` routing headers), with bounded concurrency.
+
+Races resolve per key, never failing the rest of a batch: a concurrent create conflicts on the deterministic uuid and returns the winner (`created = false`); a distinct id concurrently mapped elsewhere rolls back only that stub and re-resolves. A crash between the stub commit and the leader ack surfaces as a per-key error; the retried key resolves to the stub (`created = false`) and the caller applies properties through the normal update path.
+
+## Layout
+
+- `src/service/` — gRPC surface; `mod.rs` is dispatch-only, each RPC family has its own module (`get_or_create.rs`)
+- `src/storage/` — `IdentityStorage` trait + Postgres implementation (primary pool only; identity reads must never be stale)
+- `src/leader.rs` — `PropertyWriter` trait + router-backed implementation
+- Shared person primitives (row type, storage errors, uuidv5 scheme) live in `personhog-common::persons`
+
+## Running locally
+
+```bash
+bin/start-rust-service personhog-identity # gRPC :50055, metrics :9108
+```
+
+Tests need the persons database (`posthog_persons`) with `rust/persons_migrations` applied:
+
+```bash
+cargo test -p personhog-identity
+```
diff --git a/rust/personhog-identity/src/config.rs b/rust/personhog-identity/src/config.rs
new file mode 100644
index 000000000000..e2fd1a44abbc
--- /dev/null
+++ b/rust/personhog-identity/src/config.rs
@@ -0,0 +1,152 @@
+use envconfig::Envconfig;
+use std::net::SocketAddr;
+use std::time::Duration;
+
+#[derive(Envconfig, Clone, Debug)]
+pub struct Config {
+ #[envconfig(default = "127.0.0.1:50055")]
+ pub grpc_address: SocketAddr,
+
+ /// Primary database URL. All identity work (resolution and stub creation)
+ /// runs on the primary — the identity plane is synchronous with Postgres.
+ #[envconfig(default = "postgres://posthog:posthog@localhost:5432/posthog")]
+ pub primary_database_url: String,
+
+ #[envconfig(default = "10")]
+ pub max_pg_connections: u32,
+
+ #[envconfig(default = "0")]
+ pub min_pg_connections: u32,
+
+ #[envconfig(default = "10")]
+ pub acquire_timeout_secs: u64,
+
+ #[envconfig(default = "300")]
+ pub idle_timeout_secs: u64,
+
+ #[envconfig(default = "5000")]
+ pub statement_timeout_ms: u64,
+
+ /// Maximum number of server-side (PgBouncer → Postgres) connections to
+ /// warm at startup via SELECT 1. Clamped to min_pg_connections. Set to 0
+ /// to skip server-side warming entirely.
+ #[envconfig(default = "3")]
+ pub warmup_server_connections: u32,
+
+ #[envconfig(default = "10")]
+ pub pool_monitor_interval_secs: u64,
+
+ #[envconfig(default = "9108")]
+ pub metrics_port: u16,
+
+ /// Maximum entries per batch RPC.
+ #[envconfig(default = "250")]
+ pub max_batch_size: usize,
+
+ /// Maximum accepted distinct_id length in bytes. Must not exceed the
+ /// posthog_persondistinctid.distinct_id column limit (varchar(400)).
+ #[envconfig(default = "400")]
+ pub max_distinct_id_length: usize,
+
+ /// Maximum extra distinct ids per get-or-create entry. Real entries carry
+ /// one or two (the anon id at $identify); persons stop accumulating
+ /// distinct ids around 2,500 in the merge path, so 5,000 only stops
+ /// runaway callers.
+ #[envconfig(default = "5000")]
+ pub max_extra_distinct_ids: usize,
+
+ /// Router endpoint used to reach the owning leader for initial-properties
+ /// writes on the creation branch (UpdatePersonProperties).
+ #[envconfig(default = "http://127.0.0.1:50054")]
+ pub router_url: String,
+
+ /// Per-call timeout for leader-routed property writes (ms).
+ #[envconfig(default = "5000")]
+ pub leader_request_timeout_ms: u64,
+
+ /// Interval between HTTP/2 keepalive pings sent by the gRPC server (0 = disabled)
+ #[envconfig(default = "30")]
+ pub grpc_keepalive_interval_secs: u64,
+
+ /// Timeout for a keepalive ping ack before considering the connection dead
+ #[envconfig(default = "10")]
+ pub grpc_keepalive_timeout_secs: u64,
+
+ /// Maximum gRPC message size to encode (send), in bytes. Defaults to 128 MiB.
+ #[envconfig(default = "134217728")]
+ pub grpc_max_send_message_size: usize,
+
+ /// Maximum gRPC message size to decode (receive), in bytes.
+ #[envconfig(default = "134217728")]
+ pub grpc_max_recv_message_size: usize,
+
+ /// Maximum age of a gRPC connection in seconds before the server sends GOAWAY.
+ /// Clients reconnect transparently, naturally staggering across pods.
+ /// 0 = disabled (connections live indefinitely).
+ #[envconfig(default = "300")]
+ pub grpc_max_connection_age_secs: u64,
+
+ /// Maximum concurrent gRPC requests before load shedding.
+ /// When exceeded, new requests get an immediate UNAVAILABLE response
+ /// so the caller retries on another pod. 0 = disabled.
+ #[envconfig(default = "0")]
+ pub max_concurrent_requests: usize,
+}
+
+impl Config {
+ pub fn request_limits(&self) -> crate::service::validation::RequestLimits {
+ crate::service::validation::RequestLimits {
+ max_batch_size: self.max_batch_size,
+ max_distinct_id_length: self.max_distinct_id_length,
+ max_extra_distinct_ids: self.max_extra_distinct_ids,
+ }
+ }
+
+ pub fn acquire_timeout(&self) -> Duration {
+ Duration::from_secs(self.acquire_timeout_secs)
+ }
+
+ pub fn idle_timeout(&self) -> Option<Duration> {
+ if self.idle_timeout_secs == 0 {
+ None
+ } else {
+ Some(Duration::from_secs(self.idle_timeout_secs))
+ }
+ }
+
+ pub fn statement_timeout(&self) -> Option<u64> {
+ if self.statement_timeout_ms == 0 {
+ None
+ } else {
+ Some(self.statement_timeout_ms)
+ }
+ }
+
+ pub fn leader_request_timeout(&self) -> Duration {
+ Duration::from_millis(self.leader_request_timeout_ms)
+ }
+
+ pub fn grpc_keepalive_interval(&self) -> Option<Duration> {
+ if self.grpc_keepalive_interval_secs == 0 {
+ None
+ } else {
+ Some(Duration::from_secs(self.grpc_keepalive_interval_secs))
+ }
+ }
+
+ pub fn grpc_keepalive_timeout(&self) -> Option<Duration> {
+ if self.grpc_keepalive_timeout_secs == 0 {
+ None
+ } else {
+ Some(Duration::from_secs(self.grpc_keepalive_timeout_secs))
+ }
+ }
+
+ pub fn grpc_max_connection_age(&self) -> Option<Duration> {
+ if self.grpc_max_connection_age_secs == 0 {
+ None
+ } else {
+ Some(Duration::from_secs(self.grpc_max_connection_age_secs))
+ }
+ }
+}
diff --git a/rust/personhog-identity/src/leader.rs b/rust/personhog-identity/src/leader.rs
new file mode 100644
index 000000000000..4a22c2ea9cc4
--- /dev/null
+++ b/rust/personhog-identity/src/leader.rs
@@ -0,0 +1,27 @@
+use async_trait::async_trait;
+use tonic::Status;
+
+use personhog_common::client::RouterClient;
+use personhog_proto::personhog::types::v1::{
+ UpdatePersonPropertiesRequest, UpdatePersonPropertiesResponse,
+};
+
+/// Writes initial person properties on the creation branch. Production goes
+/// through the router (which routes to the owning leader); tests mock this.
+#[async_trait]
+pub trait PropertyWriter: Send + Sync {
+ async fn update_person_properties(
+ &self,
+ request: UpdatePersonPropertiesRequest,
+ ) -> Result<UpdatePersonPropertiesResponse, Status>;
+}
+
+#[async_trait]
+impl PropertyWriter for RouterClient {
+ async fn update_person_properties(
+ &self,
+ request: UpdatePersonPropertiesRequest,
+ ) -> Result<UpdatePersonPropertiesResponse, Status> {
+ RouterClient::update_person_properties(self, request).await
+ }
+}
diff --git a/rust/personhog-identity/src/lib.rs b/rust/personhog-identity/src/lib.rs
new file mode 100644
index 000000000000..5f71cac5d383
--- /dev/null
+++ b/rust/personhog-identity/src/lib.rs
@@ -0,0 +1,4 @@
+pub mod config;
+pub mod leader;
+pub mod service;
+pub mod storage;
diff --git a/rust/personhog-identity/src/main.rs b/rust/personhog-identity/src/main.rs
new file mode 100644
index 000000000000..1e5473f13078
--- /dev/null
+++ b/rust/personhog-identity/src/main.rs
@@ -0,0 +1,229 @@
+use std::sync::Arc;
+use std::time::Duration;
+
+use axum::{routing::get, Router};
+use common_database::{get_pool_with_config, PoolConfig};
+use common_metrics::setup_metrics_routes;
+use envconfig::Envconfig;
+use lifecycle::{ComponentOptions, Manager};
+use personhog_common::grpc::{tracked_tcp_incoming, GrpcLoadShedLayer, GrpcMetricsLayer};
+use personhog_common::{spawn_pool_monitor, MonitoredPool};
+use personhog_proto::personhog::identity::v1::person_hog_identity_server::PersonHogIdentityServer;
+use tonic::codec::CompressionEncoding;
+use tonic::transport::Server;
+use tracing::level_filters::LevelFilter;
+use tracing_subscriber::fmt;
+use tracing_subscriber::layer::SubscriberExt;
+use tracing_subscriber::util::SubscriberInitExt;
+use tracing_subscriber::EnvFilter;
+
+use personhog_common::client::RouterClient;
+use personhog_identity::config::Config;
+use personhog_identity::service::PersonHogIdentityService;
+use personhog_identity::storage::postgres::PostgresIdentityStorage;
+
+common_alloc::used!();
+
+fn create_storage(config: &Config) -> Arc<PostgresIdentityStorage> {
+ let primary_pool_config = PoolConfig {
+ min_connections: config.min_pg_connections,
+ max_connections: config.max_pg_connections,
+ acquire_timeout: config.acquire_timeout(),
+ idle_timeout: config.idle_timeout(),
+ test_before_acquire: false,
+ statement_timeout_ms: config.statement_timeout(),
+ pool_name: Some("primary".to_string()),
+ };
+
+ let primary_pool = get_pool_with_config(&config.primary_database_url, primary_pool_config)
+ .expect("Failed to create primary database pool");
+ tracing::info!("Created primary database pool");
+
+ Arc::new(PostgresIdentityStorage::new(primary_pool))
+}
+
+#[tokio::main]
+async fn main() -> Result<(), Box<dyn std::error::Error>> {
+ let config = Config::init_from_env().expect("Invalid configuration");
+
+ let log_layer = fmt::layer()
+ .with_target(true)
+ .with_thread_ids(true)
+ .with_level(true);
+
+ tracing_subscriber::registry()
+ .with(log_layer)
+ .with(
+ EnvFilter::builder()
+ .with_default_directive(LevelFilter::INFO.into())
+ .from_env_lossy(),
+ )
+ .init();
+
+ tracing::info!("Starting personhog-identity service");
+ tracing::info!("gRPC address: {}", config.grpc_address);
+ tracing::info!("Metrics port: {}", config.metrics_port);
+ tracing::info!("Router URL: {}", config.router_url);
+
+ // Build lifecycle manager and register components
+ let mut manager = Manager::builder("personhog-identity").build();
+
+ let grpc_handle = manager.register(
+ "grpc_server",
+ ComponentOptions::new().with_graceful_shutdown(Duration::from_secs(30)),
+ );
+ let metrics_handle = manager.register(
+ "metrics_server",
+ ComponentOptions::new().is_observability(true),
+ );
+
+ let readiness = manager.readiness_handler();
+ let liveness = manager.liveness_handler();
+
+ let monitor = manager.monitor_background();
+
+ // Metrics/health HTTP server (observability handle — stays alive during standard drain)
+ let metrics_port = config.metrics_port;
+ tokio::spawn(async move {
+ let _guard = metrics_handle.process_scope();
+
+ let health_router = Router::new()
+ .route(
+ "/_readiness",
+ get(move || {
+ let r = readiness.clone();
+ async move { r.check().await }
+ }),
+ )
+ .route("/_liveness", get(move || async move { liveness.check() }));
+ let metrics_router = setup_metrics_routes(health_router);
+
+ let bind = format!("0.0.0.0:{metrics_port}");
+ let listener = tokio::net::TcpListener::bind(&bind)
+ .await
+ .expect("Failed to bind metrics port");
+ tracing::info!("Metrics server listening on {}", bind);
+ axum::serve(listener, metrics_router)
+ .with_graceful_shutdown(metrics_handle.shutdown_signal())
+ .await
+ .expect("Metrics server error");
+ });
+
+ let storage = create_storage(&config);
+
+ // Pre-warm the DB connection pool before accepting traffic.
+ // connect_lazy() starts with zero connections; without this, the first
+ // burst of requests after K8s routes traffic all pay the cold-start cost.
+ // Warming here is safe because the gRPC server hasn't bound its port yet.
+ if config.min_pg_connections > 0 {
+ let warmup_count = config.min_pg_connections as usize;
+ let server_warmup_count = (config.warmup_server_connections as usize).min(warmup_count);
+ tracing::info!(
+ count = warmup_count,
+ server_warmup = server_warmup_count,
+ "Warming database connection pool before accepting traffic"
+ );
+ let pool_start = std::time::Instant::now();
+ let mut conns = Vec::with_capacity(warmup_count);
+ for _ in 0..warmup_count {
+ match storage.primary_pool.acquire().await {
+ Ok(conn) => conns.push(conn),
+ Err(e) => {
+ tracing::warn!(error = %e, "Failed to warm connection");
+ break;
+ }
+ }
+ }
+ // Run a query on a subset of held connections to warm PgBouncer → PG.
+ // acquire() only establishes app → PgBouncer; in transaction pooling
+ // mode PgBouncer doesn't open a server connection until a query runs.
+ let mut server_warmed = 0u32;
+ for conn in conns.iter_mut().take(server_warmup_count) {
+ match sqlx::query("SELECT 1").execute(&mut **conn).await {
+ Ok(_) => server_warmed += 1,
+ Err(e) => {
+ tracing::warn!(error = %e, "Failed to warm server-side connection");
+ }
+ }
+ }
+ tracing::info!(
+ client_conns = conns.len(),
+ server_conns = server_warmed,
+ elapsed_ms = pool_start.elapsed().as_millis() as u64,
+ "Pool warmup complete"
+ );
+ }
+
+ spawn_pool_monitor(
+ vec![MonitoredPool {
+ pool: storage.primary_pool.clone(),
+ label: "primary".to_string(),
+ max_connections: config.max_pg_connections,
+ }],
+ Duration::from_secs(config.pool_monitor_interval_secs),
+ );
+
+ let property_writer = Arc::new(
+ RouterClient::new(&config.router_url, config.leader_request_timeout())
+ .expect("Invalid router URL"),
+ );
+ let service = PersonHogIdentityService::new(storage, property_writer, config.request_limits());
+
+ let grpc_addr = config.grpc_address;
+ let keepalive_interval = config.grpc_keepalive_interval();
+ let keepalive_timeout = config.grpc_keepalive_timeout();
+ let max_connection_age = config.grpc_max_connection_age();
+ let max_send = config.grpc_max_send_message_size;
+ let max_recv = config.grpc_max_recv_message_size;
+ let max_concurrent_requests = config.max_concurrent_requests;
+ if max_concurrent_requests > 0 {
+ tracing::info!(
+ limit = max_concurrent_requests,
+ "gRPC load shedding enabled"
+ );
+ }
+ tracing::info!("Starting gRPC server on {}", grpc_addr);
+
+ tokio::spawn(async move {
+ let _guard = grpc_handle.process_scope();
+ let listener = match tokio::net::TcpListener::bind(grpc_addr).await {
+ Ok(l) => l,
+ Err(e) => {
+ grpc_handle.signal_failure(format!("Failed to bind gRPC port: {e}"));
+ return;
+ }
+ };
+ let incoming = tracked_tcp_incoming(listener);
+ let mut server = Server::builder()
+ .http2_keepalive_interval(keepalive_interval)
+ .http2_keepalive_timeout(keepalive_timeout);
+ if let Some(age) = max_connection_age {
+ server = server.max_connection_age(age);
+ }
+ // accept_compressed only decodes gzip request frames from opted-in
+ // clients (never send_compressed — see the tonic entry in Cargo.toml).
+ // Note max_decoding_message_size bounds the wire (compressed) size, so
+ // a compressed request can decode larger than the limit; tonic 0.12
+ // does not cap the decompressed size (0.14 does — bounding this means
+ // upgrading the workspace tonic). Until then this trusts internal
+ // callers not to send pathological frames, same as the replica.
+ if let Err(e) = server
+ .layer(GrpcMetricsLayer::default().with_processing_time_header())
+ .layer(GrpcLoadShedLayer::new(max_concurrent_requests))
+ .add_service(
+ PersonHogIdentityServer::new(service)
+ .accept_compressed(CompressionEncoding::Gzip)
+ .max_encoding_message_size(max_send)
+ .max_decoding_message_size(max_recv),
+ )
+ .serve_with_incoming_shutdown(incoming, grpc_handle.shutdown_signal())
+ .await
+ {
+ grpc_handle.signal_failure(format!("gRPC server error: {e}"));
+ }
+ });
+
+ monitor.wait().await?;
+
+ Ok(())
+}
diff --git a/rust/personhog-identity/src/service/error.rs b/rust/personhog-identity/src/service/error.rs
new file mode 100644
index 000000000000..2945543b4928
--- /dev/null
+++ b/rust/personhog-identity/src/service/error.rs
@@ -0,0 +1,43 @@
+use personhog_common::grpc::current_client_name;
+use tonic::Status;
+use tracing::error;
+
+use crate::storage;
+
+const STORAGE_ERRORS_TOTAL: &str = "personhog_identity_storage_errors_total";
+
+pub fn log_and_convert_error(err: storage::StorageError, operation: &str) -> Status {
+ let client = current_client_name();
+ let error_type = match &err {
+ storage::StorageError::Connection(_) => "connection",
+ storage::StorageError::PoolExhausted => "pool_exhausted",
+ storage::StorageError::Query(_) => "query",
+ storage::StorageError::NotFound(_) => "not_found",
+ storage::StorageError::FailedPrecondition(_) => "failed_precondition",
+ };
+ common_metrics::inc(
+ STORAGE_ERRORS_TOTAL,
+ &[
+ ("error_type".to_string(), error_type.to_string()),
+ ("operation".to_string(), operation.to_string()),
+ ("client".to_string(), client.to_string()),
+ ],
+ 1,
+ );
+ match err {
+ storage::StorageError::Connection(msg) => {
+ error!(operation, error = %msg, "Database connection error");
+ Status::unavailable(format!("Database unavailable: {msg}"))
+ }
+ storage::StorageError::PoolExhausted => {
+ error!(operation, "Database pool exhausted");
+ Status::unavailable("Database pool exhausted")
+ }
+ storage::StorageError::Query(msg) => {
+ error!(operation, error = %msg, "Database query error");
+ Status::internal(format!("Database error: {msg}"))
+ }
+ storage::StorageError::NotFound(msg) => Status::not_found(msg),
+ storage::StorageError::FailedPrecondition(msg) => Status::failed_precondition(msg),
+ }
+}
diff --git a/rust/personhog-identity/src/service/get_or_create.rs b/rust/personhog-identity/src/service/get_or_create.rs
new file mode 100644
index 000000000000..278fbcb98520
--- /dev/null
+++ b/rust/personhog-identity/src/service/get_or_create.rs
@@ -0,0 +1,273 @@
+//! The get-or-create pipeline: batch-resolve distinct ids on the primary,
+//! create person stubs for misses in one multi-row transaction, then apply
+//! initial properties through the leader with bounded concurrency.
+//!
+//! `created = true` in a result means the stub row is committed in Postgres
+//! AND the initial properties (when provided) are durable in the leader's
+//! changelog — the single ack covers both planes.
+
+use std::collections::{HashMap, HashSet};
+
+use chrono::{DateTime, Utc};
+use futures::stream::{self, StreamExt};
+use tonic::{Code, Status};
+
+use personhog_proto::personhog::identity::v1::GetOrCreatePersonEntry;
+use personhog_proto::personhog::types::v1::{Person as ProtoPerson, UpdatePersonPropertiesRequest};
+
+use crate::service::error::log_and_convert_error;
+use crate::service::validation::validate_entry;
+use crate::service::PersonHogIdentityService;
+use crate::storage::{Person, PersonStub, StubOutcome};
+
+/// Bound on concurrent leader-routed property writes within one batch.
+const MAX_CONCURRENT_PROPERTY_WRITES: usize = 8;
+
+const GET_OR_CREATE_TOTAL: &str = "personhog_identity_get_or_create_total";
+
+fn count_outcome(outcome: &str) {
+ common_metrics::inc(
+ GET_OR_CREATE_TOTAL,
+ &[("outcome".to_string(), outcome.to_string())],
+ 1,
+ );
+}
+
+/// Empty bytes and an empty JSON object both mean "no properties to apply".
+fn has_properties(raw: &[u8]) -> bool {
+ !raw.is_empty() && raw.trim_ascii() != b"{}"
+}
+
+fn entry_created_at(entry: &GetOrCreatePersonEntry) -> DateTime<Utc> {
+ if entry.created_at > 0 {
+ DateTime::from_timestamp_millis(entry.created_at).unwrap_or_else(Utc::now)
+ } else {
+ Utc::now()
+ }
+}
+
+/// How each entry proceeds after the resolve phase.
+enum Plan {
+ /// Terminal before stub creation: invalid entry, or the key resolved.
+ Done(Result<(ProtoPerson, bool), Status>),
+ /// First entry for a missing key; owns the stub at this index.
+ Owner(usize),
+ /// Duplicate of a missing key earlier in the batch; shares its outcome
+ /// but never reports created = true (exactly one entry creates).
+ Follower(usize),
+}
+
+impl PersonHogIdentityService {
+ /// Runs the get-or-create pipeline for a set of entries: one batched
+ /// resolve, one multi-row stub-create transaction for the misses, one
+ /// batched re-resolve for lost races, then the leader property fan-out.
+ /// Per-key conflicts and failures never affect other keys. Results are in
+ /// entry order.
+ pub(crate) async fn get_or_create_entries(
+ &self,
+ entries: Vec<GetOrCreatePersonEntry>,
+ ) -> Result<Vec<Result<(ProtoPerson, bool), Status>>, Status> {
+ let keys: Vec<(i64, String)> = entries
+ .iter()
+ .filter(|entry| validate_entry(&self.limits, entry).is_ok())
+ .map(|entry| (entry.team_id, entry.distinct_id.clone()))
+ .collect();
+ let resolved = self
+ .storage
+ .resolve_distinct_ids(&keys)
+ .await
+ .map_err(|e| log_and_convert_error(e, "resolve_distinct_ids"))?;
+
+ // Plan each entry and collect one stub per missing key.
+ let mut stubs: Vec<PersonStub> = Vec::new();
+ let mut stub_index: HashMap<(i64, String), usize> = HashMap::new();
+ let plans: Vec<Plan> = entries
+ .iter()
+ .map(|entry| {
+ if let Err(status) = validate_entry(&self.limits, entry) {
+ return Plan::Done(Err(status));
+ }
+ let key = (entry.team_id, entry.distinct_id.clone());
+ if let Some(person) = resolved.get(&key) {
+ count_outcome("exists");
+ return Plan::Done(Ok((person.clone().into(), false)));
+ }
+ if let Some(&index) = stub_index.get(&key) {
+ return Plan::Follower(index);
+ }
+ stub_index.insert(key, stubs.len());
+ stubs.push(build_stub(entry));
+ Plan::Owner(stubs.len() - 1)
+ })
+ .collect();
+
+ let outcomes = if stubs.is_empty() {
+ Vec::new()
+ } else {
+ self.storage
+ .create_person_stubs(&stubs)
+ .await
+ .map_err(|e| log_and_convert_error(e, "create_person_stubs"))?
+ };
+
+ // Lost races re-resolve in one batch: the winner's mapping committed,
+ // so a fresh resolve finds it.
+ let lost_keys: Vec<(i64, String)> = stub_index
+ .iter()
+ .filter(|(_, &index)| matches!(outcomes[index], StubOutcome::LostRace))
+ .map(|(key, _)| key.clone())
+ .collect();
+ let lost_resolved = if lost_keys.is_empty() {
+ HashMap::new()
+ } else {
+ self.storage
+ .resolve_distinct_ids(&lost_keys)
+ .await
+ .map_err(|e| log_and_convert_error(e, "resolve_after_lost_race"))?
+ };
+
+ // Assemble results; created owners go through the leader fan-out.
+ let lost_race_result = |i: usize| {
+ let key = (entries[i].team_id, entries[i].distinct_id.clone());
+ match lost_resolved.get(&key) {
+ Some(person) => {
+ count_outcome("lost_race_resolved");
+ Ok((person.clone().into(), false))
+ }
+ None => {
+ count_outcome("lost_race_unresolved");
+ Err(Status::aborted(
+ "concurrent identity operation on distinct id; retry",
+ ))
+ }
+ }
+ };
+ let mut results: Vec<Option<Result<(ProtoPerson, bool), Status>>> = Vec::new();
+ let mut property_writes: Vec<(usize, Person)> = Vec::new();
+ for (i, plan) in plans.into_iter().enumerate() {
+ let result = match plan {
+ Plan::Done(result) => Some(result),
+ Plan::Owner(index) => match &outcomes[index] {
+ StubOutcome::Committed {
+ person,
+ created: true,
+ } => {
+ property_writes.push((i, person.clone()));
+ None
+ }
+ StubOutcome::Committed {
+ person,
+ created: false,
+ } => {
+ count_outcome("exists");
+ Some(Ok((person.clone().into(), false)))
+ }
+ StubOutcome::LostRace => Some(lost_race_result(i)),
+ },
+ Plan::Follower(index) => match &outcomes[index] {
+ StubOutcome::Committed { person, .. } => {
+ count_outcome("exists");
+ Some(Ok((person.clone().into(), false)))
+ }
+ StubOutcome::LostRace => Some(lost_race_result(i)),
+ },
+ };
+ results.push(result);
+ }
+
+ let applied: Vec<(usize, Result<ProtoPerson, Status>)> =
+ stream::iter(property_writes.into_iter().map(|(i, person)| {
+ let entry = &entries[i];
+ async move { (i, self.apply_initial_properties(entry, person).await) }
+ }))
+ .buffered(MAX_CONCURRENT_PROPERTY_WRITES)
+ .collect()
+ .await;
+ for (i, result) in applied {
+ let result = result.map(|person| (person, true));
+ if result.is_ok() {
+ count_outcome("created");
+ }
+ results[i] = Some(result);
+ }
+
+ Ok(results
+ .into_iter()
+ .map(|result| result.expect("every entry has a result"))
+ .collect())
+ }
+
+ /// Applies the entry's $set/$set_once to a freshly created stub through
+ /// the leader (via the router). Success means the properties are durable
+ /// in the changelog — only then may the RPC report created = true.
+ async fn apply_initial_properties(
+ &self,
+ entry: &GetOrCreatePersonEntry,
+ person: Person,
+ ) -> Result<ProtoPerson, Status> {
+ if !has_properties(&entry.set_properties) && !has_properties(&entry.set_once_properties) {
+ return Ok(person.into());
+ }
+
+ let request = UpdatePersonPropertiesRequest {
+ team_id: person.team_id,
+ person_id: person.id,
+ event_name: entry.event_name.clone(),
+ set_properties: entry.set_properties.clone(),
+ set_once_properties: entry.set_once_properties.clone(),
+ unset_properties: Vec::new(),
+ };
+
+ match self
+ .property_writer
+ .update_person_properties(request.clone())
+ .await
+ {
+ Ok(response) => Ok(response.person.unwrap_or_else(|| person.into())),
+ Err(status) if status.code() == Code::NotFound => {
+ // The stub was destroyed (merged or deleted) between commit and
+ // the property write. Re-resolve and apply to the person the
+ // distinct id now maps to.
+ let key = (entry.team_id, entry.distinct_id.clone());
+ let mut resolved = self
+ .storage
+ .resolve_distinct_ids(std::slice::from_ref(&key))
+ .await
+ .map_err(|e| log_and_convert_error(e, "resolve_after_leader_not_found"))?;
+ let Some(current) = resolved.remove(&key) else {
+ return Err(status);
+ };
+ if current.id == person.id {
+ return Err(status);
+ }
+ let retry = UpdatePersonPropertiesRequest {
+ team_id: current.team_id,
+ person_id: current.id,
+ ..request
+ };
+ let response = self.property_writer.update_person_properties(retry).await?;
+ Ok(response.person.unwrap_or_else(|| current.into()))
+ }
+ Err(status) => Err(status),
+ }
+ }
+}
+
+/// Builds the storage stub for an entry, deduping extras and dropping the
+/// primary from them — the storage layer requires unique distinct ids.
+fn build_stub(entry: &GetOrCreatePersonEntry) -> PersonStub {
+ let mut seen: HashSet<&str> = HashSet::from([entry.distinct_id.as_str()]);
+ let extra_distinct_ids: Vec<String> = entry
+ .extra_distinct_ids
+ .iter()
+ .filter(|d| seen.insert(d.as_str()))
+ .cloned()
+ .collect();
+ PersonStub {
+ team_id: entry.team_id,
+ distinct_id: entry.distinct_id.clone(),
+ extra_distinct_ids,
+ created_at: entry_created_at(entry),
+ is_identified: entry.is_identified,
+ }
+}
diff --git a/rust/personhog-identity/src/service/mod.rs b/rust/personhog-identity/src/service/mod.rs
new file mode 100644
index 000000000000..b89003d8865c
--- /dev/null
+++ b/rust/personhog-identity/src/service/mod.rs
@@ -0,0 +1,102 @@
+//! The gRPC service surface. This module is dispatch-only: each RPC family
+//! lives in its own submodule (get_or_create today; resolution, claims,
+//! splits, and merge classification will follow the same pattern).
+
+pub mod error;
+pub mod get_or_create;
+pub mod validation;
+
+use std::sync::Arc;
+
+use tonic::{Request, Response, Status};
+
+use personhog_proto::personhog::identity::v1::person_hog_identity_server::PersonHogIdentity;
+use personhog_proto::personhog::identity::v1::{
+ GetOrCreatePersonByDistinctIdRequest, GetOrCreatePersonByDistinctIdResponse,
+ GetOrCreatePersonResult, GetOrCreatePersonsByDistinctIdsRequest,
+ GetOrCreatePersonsByDistinctIdsResponse,
+};
+
+use crate::leader::PropertyWriter;
+use crate::service::validation::{validate_batch_size, validate_entry, RequestLimits};
+use crate::storage::IdentityStorage;
+
+pub struct PersonHogIdentityService {
+ pub(crate) storage: Arc<dyn IdentityStorage>,
+ pub(crate) property_writer: Arc<dyn PropertyWriter>,
+ pub(crate) limits: RequestLimits,
+}
+
+impl PersonHogIdentityService {
+ pub fn new(
+ storage: Arc<dyn IdentityStorage>,
+ property_writer: Arc<dyn PropertyWriter>,
+ limits: RequestLimits,
+ ) -> Self {
+ Self {
+ storage,
+ property_writer,
+ limits,
+ }
+ }
+}
+
+#[tonic::async_trait]
+impl PersonHogIdentity for PersonHogIdentityService {
+ async fn get_or_create_person_by_distinct_id(
+ &self,
+ request: Request<GetOrCreatePersonByDistinctIdRequest>,
+ ) -> Result<Response<GetOrCreatePersonByDistinctIdResponse>, Status> {
+ let entry = request
+ .into_inner()
+ .entry
+ .ok_or_else(|| Status::invalid_argument("entry is required"))?;
+ validate_entry(&self.limits, &entry)?;
+
+ let mut results = self.get_or_create_entries(vec![entry]).await?;
+ let (person, created) = results.pop().expect("one entry yields one result")?;
+ Ok(Response::new(GetOrCreatePersonByDistinctIdResponse {
+ person: Some(person),
+ created,
+ }))
+ }
+
+ async fn get_or_create_persons_by_distinct_ids(
+ &self,
+ request: Request<GetOrCreatePersonsByDistinctIdsRequest>,
+ ) -> Result<Response<GetOrCreatePersonsByDistinctIdsResponse>, Status> {
+ let entries = request.into_inner().entries;
+ validate_batch_size(&self.limits, entries.len())?;
+
+ let identifiers: Vec<(i64, String)> = entries
+ .iter()
+ .map(|entry| (entry.team_id, entry.distinct_id.clone()))
+ .collect();
+ let outcomes = self.get_or_create_entries(entries).await?;
+
+ let results = identifiers
+ .into_iter()
+ .zip(outcomes)
+ .map(|((team_id, distinct_id), outcome)| match outcome {
+ Ok((person, created)) => GetOrCreatePersonResult {
+ team_id,
+ distinct_id,
+ person: Some(person),
+ created,
+ error: None,
+ },
+ Err(status) => GetOrCreatePersonResult {
+ team_id,
+ distinct_id,
+ person: None,
+ created: false,
+ error: Some(format!("{:?}: {}", status.code(), status.message())),
+ },
+ })
+ .collect();
+
+ Ok(Response::new(GetOrCreatePersonsByDistinctIdsResponse {
+ results,
+ }))
+ }
+}
diff --git a/rust/personhog-identity/src/service/validation.rs b/rust/personhog-identity/src/service/validation.rs
new file mode 100644
index 000000000000..83c05b86f42b
--- /dev/null
+++ b/rust/personhog-identity/src/service/validation.rs
@@ -0,0 +1,114 @@
+use tonic::Status;
+
+use personhog_proto::personhog::identity::v1::GetOrCreatePersonEntry;
+
+/// Request-shape limits, sourced from service configuration.
+#[derive(Debug, Clone)]
+pub struct RequestLimits {
+ /// Maximum entries per batch RPC.
+ pub max_batch_size: usize,
+ /// Maximum accepted distinct_id length in bytes. Must not exceed the
+ /// posthog_persondistinctid.distinct_id column limit (varchar(400)).
+ pub max_distinct_id_length: usize,
+ /// Maximum extra distinct ids per entry.
+ pub max_extra_distinct_ids: usize,
+}
+
+// tonic Status is a large Err variant; boxing here would diverge from the
+// tonic handler signatures these feed into.
+#[allow(clippy::result_large_err)]
+pub fn validate_batch_size(limits: &RequestLimits, len: usize) -> Result<(), Status> {
+ if len > limits.max_batch_size {
+ return Err(Status::invalid_argument(format!(
+ "batch size {len} exceeds maximum {}",
+ limits.max_batch_size
+ )));
+ }
+ Ok(())
+}
+
+#[allow(clippy::result_large_err)]
+pub fn validate_entry(
+ limits: &RequestLimits,
+ entry: &GetOrCreatePersonEntry,
+) -> Result<(), Status> {
+ // 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
+ // or write another tenant's rows.
+ if entry.team_id <= 0 || entry.team_id > i32::MAX as i64 {
+ return Err(Status::invalid_argument(
+ "team_id must be a positive 32-bit integer",
+ ));
+ }
+ validate_distinct_id(limits, &entry.distinct_id)?;
+ if entry.extra_distinct_ids.len() > limits.max_extra_distinct_ids {
+ return Err(Status::invalid_argument(format!(
+ "entry has {} extra distinct ids, exceeding maximum {}",
+ entry.extra_distinct_ids.len(),
+ limits.max_extra_distinct_ids
+ )));
+ }
+ for extra in &entry.extra_distinct_ids {
+ validate_distinct_id(limits, extra)?;
+ }
+ Ok(())
+}
+
+#[allow(clippy::result_large_err)]
+fn validate_distinct_id(limits: &RequestLimits, distinct_id: &str) -> Result<(), Status> {
+ if distinct_id.is_empty() {
+ return Err(Status::invalid_argument("distinct_id must not be empty"));
+ }
+ if distinct_id.len() > limits.max_distinct_id_length {
+ return Err(Status::invalid_argument(format!(
+ "distinct_id exceeds {} bytes",
+ limits.max_distinct_id_length
+ )));
+ }
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn entry(team_id: i64) -> GetOrCreatePersonEntry {
+ GetOrCreatePersonEntry {
+ team_id,
+ distinct_id: "user-1".to_string(),
+ ..Default::default()
+ }
+ }
+
+ #[test]
+ fn team_id_must_fit_the_int4_column_without_wrapping() {
+ let limits = RequestLimits {
+ max_batch_size: 10,
+ max_distinct_id_length: 400,
+ max_extra_distinct_ids: 5000,
+ };
+ for ok in [1, i32::MAX as i64] {
+ assert!(validate_entry(&limits, &entry(ok)).is_ok(), "{ok}");
+ }
+ // 2^32 + 1 wraps to team 1 under `as i32`; the rest are the
+ // boundary and sign cases around the valid range.
+ for bad in [0, -1, i32::MAX as i64 + 1, (1 << 32) + 1, i64::MAX] {
+ assert!(validate_entry(&limits, &entry(bad)).is_err(), "{bad}");
+ }
+ }
+
+ #[test]
+ fn extra_distinct_ids_are_capped_per_entry() {
+ let limits = RequestLimits {
+ max_batch_size: 10,
+ max_distinct_id_length: 400,
+ max_extra_distinct_ids: 3,
+ };
+ let with_extras = |n: usize| GetOrCreatePersonEntry {
+ extra_distinct_ids: (0..n).map(|i| format!("extra-{i}")).collect(),
+ ..entry(1)
+ };
+ assert!(validate_entry(&limits, &with_extras(3)).is_ok());
+ assert!(validate_entry(&limits, &with_extras(4)).is_err());
+ }
+}
diff --git a/rust/personhog-identity/src/storage/error.rs b/rust/personhog-identity/src/storage/error.rs
new file mode 100644
index 000000000000..b4aa008dbc11
--- /dev/null
+++ b/rust/personhog-identity/src/storage/error.rs
@@ -0,0 +1 @@
+pub use personhog_common::storage_error::{StorageError, StorageResult};
diff --git a/rust/personhog-identity/src/storage/mod.rs b/rust/personhog-identity/src/storage/mod.rs
new file mode 100644
index 000000000000..54506e620617
--- /dev/null
+++ b/rust/personhog-identity/src/storage/mod.rs
@@ -0,0 +1,34 @@
+pub mod error;
+pub mod postgres;
+pub mod types;
+
+use std::collections::HashMap;
+
+use async_trait::async_trait;
+
+pub use error::{StorageError, StorageResult};
+pub use types::{Person, PersonStub, StubOutcome};
+
+pub const DB_QUERY_DURATION: &str = "personhog_identity_db_query_duration_ms";
+
+/// Storage operations for the identity service. All queries run on the
+/// Postgres primary: identity resolution must never be stale, and stub
+/// creation is a sync-plane write.
+#[async_trait]
+pub trait IdentityStorage: Send + Sync {
+ /// Batch-resolve (team_id, distinct_id) keys to persons on the primary.
+ /// Returns a map keyed by (team_id, distinct_id); unresolved keys are absent.
+ async fn resolve_distinct_ids(
+ &self,
+ keys: &[(i64, String)],
+ ) -> StorageResult<HashMap<(i64, String), Person>>;
+
+ /// 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
+ /// erroring, so one key's race never fails the rest of the batch.
+ ///
+ /// Callers must dedupe stubs by (team_id, distinct_id); duplicate keys in
+ /// one call have unspecified per-row outcomes. Outcomes are in stub order.
+ async fn create_person_stubs(&self, stubs: &[PersonStub]) -> StorageResult<Vec<StubOutcome>>;
+}
diff --git a/rust/personhog-identity/src/storage/postgres.rs b/rust/personhog-identity/src/storage/postgres.rs
new file mode 100644
index 000000000000..64c76ec4d801
--- /dev/null
+++ b/rust/personhog-identity/src/storage/postgres.rs
@@ -0,0 +1,421 @@
+use std::collections::{HashMap, HashSet};
+
+use async_trait::async_trait;
+use chrono::{DateTime, Utc};
+use sqlx::postgres::PgPool;
+use uuid::Uuid;
+
+use personhog_common::grpc::{current_client_name, current_method_name};
+use personhog_common::persons::person_uuid;
+
+use crate::storage::error::StorageResult;
+use crate::storage::types::{Person, PersonStub, StubOutcome};
+use crate::storage::{IdentityStorage, DB_QUERY_DURATION};
+
+const POOL_LABEL: &str = "primary";
+
+pub struct PostgresIdentityStorage {
+ pub primary_pool: PgPool,
+}
+
+impl PostgresIdentityStorage {
+ pub fn new(primary_pool: PgPool) -> Self {
+ Self { primary_pool }
+ }
+
+ fn query_labels(operation: &str) -> [(String, String); 4] {
+ [
+ ("operation".to_string(), operation.to_string()),
+ ("pool".to_string(), POOL_LABEL.to_string()),
+ ("client".to_string(), current_client_name().to_string()),
+ ("method".to_string(), current_method_name().to_string()),
+ ]
+ }
+}
+
+#[async_trait]
+impl IdentityStorage for PostgresIdentityStorage {
+ async fn resolve_distinct_ids(
+ &self,
+ keys: &[(i64, String)],
+ ) -> StorageResult<HashMap<(i64, String), Person>> {
+ if keys.is_empty() {
+ return Ok(HashMap::new());
+ }
+
+ let labels = Self::query_labels("resolve_distinct_ids");
+ let _timer = common_metrics::timing_guard(DB_QUERY_DURATION, &labels);
+
+ 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 rows = sqlx::query!(
+ r#"
+ SELECT k.team_id as "key_team_id!", k.distinct_id as "key_distinct_id!",
+ p.id as "id!", p.uuid as "uuid!", p.team_id::bigint as "team_id!",
+ p.properties::text as "properties?",
+ p.properties_last_updated_at::text as "properties_last_updated_at?",
+ p.properties_last_operation::text as "properties_last_operation?",
+ p.created_at as "created_at!", p.version, p.is_identified as "is_identified!",
+ CASE WHEN p.is_user_id IS NULL THEN NULL ELSE (p.is_user_id != 0) END as is_user_id,
+ p.last_seen_at
+ FROM unnest($1::int[], $2::text[]) AS k(team_id, distinct_id)
+ JOIN posthog_persondistinctid pdi
+ ON pdi.team_id = k.team_id AND pdi.distinct_id = k.distinct_id
+ JOIN posthog_person p
+ ON p.team_id = pdi.team_id AND p.id = pdi.person_id
+ "#,
+ &team_ids,
+ &distinct_ids
+ )
+ .fetch_all(&self.primary_pool)
+ .await?;
+
+ let mut resolved = HashMap::with_capacity(rows.len());
+ for row in rows {
+ resolved.insert(
+ (i64::from(row.key_team_id), row.key_distinct_id),
+ Person {
+ id: row.id,
+ uuid: row.uuid,
+ team_id: row.team_id,
+ properties: row.properties,
+ properties_last_updated_at: row.properties_last_updated_at,
+ properties_last_operation: row.properties_last_operation,
+ created_at: row.created_at,
+ version: row.version,
+ is_identified: row.is_identified,
+ is_user_id: row.is_user_id,
+ last_seen_at: row.last_seen_at,
+ },
+ );
+ }
+ Ok(resolved)
+ }
+
+ async fn create_person_stubs(&self, stubs: &[PersonStub]) -> StorageResult<Vec<StubOutcome>> {
+ if stubs.is_empty() {
+ return Ok(Vec::new());
+ }
+
+ let labels = Self::query_labels("create_person_stubs");
+ let _timer = common_metrics::timing_guard(DB_QUERY_DURATION, &labels);
+
+ let uuids: Vec<Uuid> = stubs
+ .iter()
+ .map(|s| person_uuid(s.team_id, &s.distinct_id))
+ .collect();
+ let team_ids: Vec<i32> = stubs.iter().map(|s| s.team_id as i32).collect();
+
+ // Every multi-row statement below binds arrays sorted by its conflict
+ // key: row locks are taken in array order, so concurrent batches
+ // (main vs overflow) touching the same keys in different orders would
+ // otherwise deadlock.
+ let mut order: Vec<usize> = (0..stubs.len()).collect();
+ order.sort_by_key(|&i| (team_ids[i], uuids[i]));
+ let sorted_created_ats: Vec<DateTime<Utc>> =
+ order.iter().map(|&i| stubs[i].created_at).collect();
+ let sorted_team_ids: Vec<i32> = order.iter().map(|&i| team_ids[i]).collect();
+ let sorted_is_identified: Vec<bool> =
+ order.iter().map(|&i| stubs[i].is_identified).collect();
+ let sorted_uuids: Vec<Uuid> = order.iter().map(|&i| uuids[i]).collect();
+
+ let mut tx = self.primary_pool.begin().await?;
+
+ // 1. Multi-row stub insert. Concurrent creates for one distinct id
+ // derive the same uuid, so exactly one insert wins per key; losers
+ // fetch the committed winner in a fresh statement snapshot below.
+ let inserted = sqlx::query_as!(
+ Person,
+ r#"
+ INSERT INTO posthog_person
+ (created_at, properties, properties_last_updated_at, properties_last_operation,
+ team_id, is_identified, uuid, version, last_seen_at)
+ SELECT u.created_at, '{}'::jsonb, '{}'::jsonb, '{}'::jsonb,
+ u.team_id, u.is_identified, u.uuid, 0, date_trunc('hour', u.created_at)
+ FROM unnest($1::timestamptz[], $2::int[], $3::bool[], $4::uuid[])
+ AS u(created_at, team_id, is_identified, uuid)
+ ON CONFLICT (team_id, uuid) DO NOTHING
+ RETURNING id, uuid, team_id::bigint as "team_id!", properties::text as "properties?",
+ properties_last_updated_at::text as "properties_last_updated_at?",
+ properties_last_operation::text as "properties_last_operation?",
+ created_at, version, is_identified,
+ CASE WHEN is_user_id IS NULL THEN NULL ELSE (is_user_id != 0) END as is_user_id,
+ last_seen_at
+ "#,
+ &sorted_created_ats,
+ &sorted_team_ids,
+ &sorted_is_identified,
+ &sorted_uuids
+ )
+ .fetch_all(&mut *tx)
+ .await?;
+
+ // (team_id, uuid) → (person, created-by-us)
+ let mut persons: HashMap<(i64, Uuid), (Person, bool)> = inserted
+ .into_iter()
+ .map(|p| ((p.team_id, p.uuid), (p, true)))
+ .collect();
+
+ // 2. Batch-fetch the committed winners for conflicted keys. This must
+ // be a separate statement: the insert's snapshot predates a concurrent
+ // winner's commit, a fresh statement snapshot sees it.
+ let conflicted: Vec<usize> = (0..stubs.len())
+ .filter(|&i| !persons.contains_key(&(stubs[i].team_id, uuids[i])))
+ .collect();
+ if !conflicted.is_empty() {
+ let conflicted_teams: Vec<i32> = conflicted.iter().map(|&i| team_ids[i]).collect();
+ let conflicted_uuids: Vec<Uuid> = conflicted.iter().map(|&i| uuids[i]).collect();
+ let winners = sqlx::query_as!(
+ Person,
+ r#"
+ SELECT p.id as "id!", p.uuid as "uuid!", p.team_id::bigint as "team_id!",
+ p.properties::text as "properties?",
+ p.properties_last_updated_at::text as "properties_last_updated_at?",
+ p.properties_last_operation::text as "properties_last_operation?",
+ p.created_at as "created_at!", p.version, p.is_identified as "is_identified!",
+ CASE WHEN p.is_user_id IS NULL THEN NULL ELSE (p.is_user_id != 0) END as is_user_id,
+ p.last_seen_at
+ FROM posthog_person p
+ JOIN unnest($1::int[], $2::uuid[]) AS k(team_id, uuid)
+ ON p.team_id = k.team_id AND p.uuid = k.uuid
+ "#,
+ &conflicted_teams,
+ &conflicted_uuids
+ )
+ .fetch_all(&mut *tx)
+ .await?;
+ for winner in winners {
+ persons.insert((winner.team_id, winner.uuid), (winner, false));
+ }
+ }
+
+ // 3. Extra distinct ids carry personless history forward: a distinct
+ // id already used personless needs its row at version 1 so ClickHouse
+ // emits an override re-pointing those events. The upsert also marks
+ // the personless row merged so concurrent personless events re-resolve.
+ // Deduped across stubs — DO UPDATE errors on same-command duplicates.
+ // The update is conditional on is_merged = false so RETURNING captures
+ // exactly what this transaction changed (insert vs flip), which step 6
+ // reverts for stubs whose rows are undone; already-merged rows return
+ // nothing and are never touched.
+ let mut personless_seen: HashSet<(i64, &str)> = HashSet::new();
+ let mut personless_pairs: Vec<(i32, String)> = Vec::new();
+ for stub in stubs {
+ for extra in &stub.extra_distinct_ids {
+ if personless_seen.insert((stub.team_id, extra.as_str())) {
+ personless_pairs.push((stub.team_id as i32, extra.clone()));
+ }
+ }
+ }
+ personless_pairs.sort();
+ let (personless_teams, personless_dids): (Vec<i32>, Vec<String>) =
+ personless_pairs.into_iter().unzip();
+ let mut personless_fresh: HashMap<(i64, String), bool> = HashMap::new();
+ if !personless_dids.is_empty() {
+ let rows = sqlx::query!(
+ r#"
+ INSERT INTO posthog_personlessdistinctid (distinct_id, is_merged, created_at, team_id)
+ SELECT d, true, now(), t FROM unnest($1::int[], $2::text[]) AS u(t, d)
+ ON CONFLICT (team_id, distinct_id) DO UPDATE SET is_merged = true
+ WHERE posthog_personlessdistinctid.is_merged = false
+ RETURNING team_id::bigint as "team_id!", distinct_id, (xmax = 0) as "inserted!"
+ "#,
+ &personless_teams,
+ &personless_dids
+ )
+ .fetch_all(&mut *tx)
+ .await?;
+ for row in rows {
+ personless_fresh.insert((row.team_id, row.distinct_id), row.inserted);
+ }
+ }
+
+ // 4. Multi-row distinct id insert. The primary distinct id derives the
+ // person uuid, so personless events already used the same uuid —
+ // always version 0. Conflicts keep the existing mapping (per-row): an
+ // extra that raced into another person's hands is a merge scenario,
+ // which is the pipeline's job — never re-pointed here, and not an
+ // error (a retry could never succeed).
+ // (team_id, distinct_id, person_id, version)
+ let mut pdi_rows: Vec<(i32, String, i64, i64)> = Vec::new();
+ for (i, stub) in stubs.iter().enumerate() {
+ let Some((person, _)) = persons.get(&(stub.team_id, uuids[i])) else {
+ continue; // winner vanished; resolved to LostRace below
+ };
+ pdi_rows.push((stub.team_id as i32, stub.distinct_id.clone(), person.id, 0));
+ for extra in &stub.extra_distinct_ids {
+ // Missing from the map = the personless row pre-existed
+ // already merged, so the distinct id has history: version 1.
+ let fresh = personless_fresh
+ .get(&(stub.team_id, extra.clone()))
+ .copied()
+ .unwrap_or(false);
+ pdi_rows.push((
+ stub.team_id as i32,
+ extra.clone(),
+ person.id,
+ if fresh { 0 } else { 1 },
+ ));
+ }
+ }
+ // Stable sort: batch order still picks the winner among same-command
+ // duplicate keys (an extra shared between stubs).
+ pdi_rows.sort_by(|a, b| (a.0, &a.1).cmp(&(b.0, &b.1)));
+ let pdi_teams: Vec<i32> = pdi_rows.iter().map(|r| r.0).collect();
+ let pdi_dids: Vec<String> = pdi_rows.iter().map(|r| r.1.clone()).collect();
+ let pdi_person_ids: Vec<i64> = pdi_rows.iter().map(|r| r.2).collect();
+ let pdi_versions: Vec<i64> = pdi_rows.iter().map(|r| r.3).collect();
+ let mut mapped: HashMap<(i64, String), i64> = HashMap::new();
+ if !pdi_dids.is_empty() {
+ let rows = sqlx::query!(
+ r#"
+ INSERT INTO posthog_persondistinctid (distinct_id, person_id, team_id, version)
+ SELECT d, p, t, v FROM unnest($1::text[], $2::bigint[], $3::int[], $4::bigint[])
+ AS u(d, p, t, v)
+ ON CONFLICT (team_id, distinct_id) DO NOTHING
+ RETURNING team_id::bigint as "team_id!", distinct_id, person_id
+ "#,
+ &pdi_dids,
+ &pdi_person_ids,
+ &pdi_teams,
+ &pdi_versions
+ )
+ .fetch_all(&mut *tx)
+ .await?;
+ for row in rows {
+ mapped.insert((row.team_id, row.distinct_id), row.person_id);
+ }
+ }
+
+ // 5. Per-stub outcomes. A stub whose primary mapping went elsewhere is
+ // a lost race: undo its rows (created this transaction, so nothing can
+ // reference them) so the stub doesn't linger orphaned. `released`
+ // marks stubs that leave no distinct id mappings behind (undone or
+ // never inserted), so step 6 can revert their personless marks.
+ let mut outcomes = Vec::with_capacity(stubs.len());
+ let mut released = vec![false; stubs.len()];
+ for (i, stub) in stubs.iter().enumerate() {
+ let Some((person, created)) = persons.get(&(stub.team_id, uuids[i])) else {
+ released[i] = true;
+ outcomes.push(StubOutcome::LostRace);
+ continue;
+ };
+ let primary_key = (stub.team_id, stub.distinct_id.clone());
+ if mapped.get(&primary_key) == Some(&person.id) {
+ outcomes.push(StubOutcome::Committed {
+ person: person.clone(),
+ created: *created,
+ });
+ continue;
+ }
+ if *created {
+ sqlx::query!(
+ "DELETE FROM posthog_persondistinctid WHERE team_id = $1 AND person_id = $2",
+ stub.team_id as i32,
+ person.id
+ )
+ .execute(&mut *tx)
+ .await?;
+ sqlx::query!(
+ "DELETE FROM posthog_person WHERE team_id = $1 AND id = $2",
+ stub.team_id as i32,
+ person.id
+ )
+ .execute(&mut *tx)
+ .await?;
+ released[i] = true;
+ outcomes.push(StubOutcome::LostRace);
+ continue;
+ }
+ // The person pre-existed and its primary mapping wasn't inserted by
+ // us — verify the existing mapping points at this person.
+ let existing = sqlx::query_scalar!(
+ "SELECT person_id FROM posthog_persondistinctid WHERE team_id = $1 AND distinct_id = $2",
+ stub.team_id as i32,
+ &stub.distinct_id
+ )
+ .fetch_optional(&mut *tx)
+ .await?;
+ if existing == Some(person.id) {
+ outcomes.push(StubOutcome::Committed {
+ person: person.clone(),
+ created: false,
+ });
+ } else {
+ outcomes.push(StubOutcome::LostRace);
+ }
+ }
+
+ // 6. Step 3 marked every extra distinct id merged, but a released
+ // stub's merge never happened. Revert exactly what this transaction
+ // changed (delete rows it inserted, unflip rows it flipped — the row
+ // lock held since step 3 guarantees the prior value was false), unless
+ // a surviving stub shares the extra: its mapping stands, so the mark
+ // must too. Lost races that keep a pre-existing person keep their
+ // extra mappings and are not released.
+ let mut kept_extras: HashSet<(i64, &str)> = HashSet::new();
+ for (i, stub) in stubs.iter().enumerate() {
+ if !released[i] {
+ for extra in &stub.extra_distinct_ids {
+ kept_extras.insert((stub.team_id, extra.as_str()));
+ }
+ }
+ }
+ let mut delete_teams: Vec<i32> = Vec::new();
+ let mut delete_dids: Vec<String> = Vec::new();
+ let mut unmark_teams: Vec<i32> = Vec::new();
+ let mut unmark_dids: Vec<String> = Vec::new();
+ for (i, stub) in stubs.iter().enumerate() {
+ if !released[i] {
+ continue;
+ }
+ for extra in &stub.extra_distinct_ids {
+ if kept_extras.contains(&(stub.team_id, extra.as_str())) {
+ continue;
+ }
+ match personless_fresh.remove(&(stub.team_id, extra.clone())) {
+ Some(true) => {
+ delete_teams.push(stub.team_id as i32);
+ delete_dids.push(extra.clone());
+ }
+ Some(false) => {
+ unmark_teams.push(stub.team_id as i32);
+ unmark_dids.push(extra.clone());
+ }
+ None => {} // pre-existed merged; step 3 changed nothing
+ }
+ }
+ }
+ if !delete_dids.is_empty() {
+ sqlx::query!(
+ r#"
+ DELETE FROM posthog_personlessdistinctid pl
+ USING unnest($1::int[], $2::text[]) AS u(t, d)
+ WHERE pl.team_id = u.t AND pl.distinct_id = u.d
+ "#,
+ &delete_teams,
+ &delete_dids
+ )
+ .execute(&mut *tx)
+ .await?;
+ }
+ if !unmark_dids.is_empty() {
+ sqlx::query!(
+ r#"
+ UPDATE posthog_personlessdistinctid pl
+ SET is_merged = false
+ FROM unnest($1::int[], $2::text[]) AS u(t, d)
+ WHERE pl.team_id = u.t AND pl.distinct_id = u.d
+ "#,
+ &unmark_teams,
+ &unmark_dids
+ )
+ .execute(&mut *tx)
+ .await?;
+ }
+
+ tx.commit().await?;
+ Ok(outcomes)
+ }
+}
diff --git a/rust/personhog-identity/src/storage/types.rs b/rust/personhog-identity/src/storage/types.rs
new file mode 100644
index 000000000000..97ea88a7982e
--- /dev/null
+++ b/rust/personhog-identity/src/storage/types.rs
@@ -0,0 +1,25 @@
+pub use personhog_common::persons::Person;
+
+/// A single stub-creation request: the primary distinct id derives the
+/// deterministic person UUID; extra distinct ids are mapped in the same
+/// transaction.
+#[derive(Debug, Clone)]
+pub struct PersonStub {
+ pub team_id: i64,
+ pub distinct_id: String,
+ pub extra_distinct_ids: Vec<String>,
+ pub created_at: chrono::DateTime<chrono::Utc>,
+ pub is_identified: bool,
+}
+
+/// Per-stub outcome of a stub-creation transaction.
+#[derive(Debug, Clone)]
+pub enum StubOutcome {
+ /// The transaction committed. `created` is false when the person row
+ /// already existed (a concurrent creator won the uuid insert) and only
+ /// distinct id rows were attached.
+ Committed { person: Person, created: bool },
+ /// The primary distinct id was concurrently mapped to a different person;
+ /// the transaction rolled back. The caller re-resolves to find the winner.
+ LostRace,
+}
diff --git a/rust/personhog-identity/tests/common/mod.rs b/rust/personhog-identity/tests/common/mod.rs
new file mode 100644
index 000000000000..4264848e9ac3
--- /dev/null
+++ b/rust/personhog-identity/tests/common/mod.rs
@@ -0,0 +1,79 @@
+use std::sync::Arc;
+
+use rand::Rng;
+use sqlx::postgres::PgPool;
+
+use personhog_identity::storage::postgres::PostgresIdentityStorage;
+
+pub struct TestContext {
+ pub pool: PgPool,
+ pub storage: Arc<PostgresIdentityStorage>,
+ pub team_id: i64,
+}
+
+impl TestContext {
+ pub async fn new() -> Self {
+ let database_url = std::env::var("DATABASE_URL").unwrap_or_else(|_| {
+ "postgres://posthog:posthog@localhost:5432/posthog_persons".to_string()
+ });
+ let pool = PgPool::connect(&database_url)
+ .await
+ .expect("Failed to connect to test database");
+ let storage = Arc::new(PostgresIdentityStorage::new(pool.clone()));
+ let team_id = rand::thread_rng().gen_range(1_000_000..100_000_000);
+ Self {
+ pool,
+ storage,
+ team_id,
+ }
+ }
+
+ /// Inserts a person with a random (non-deterministic) uuid plus a distinct
+ /// id row pointing at it. Returns the person id.
+ pub async fn insert_person_with_distinct_id(&self, distinct_id: &str) -> i64 {
+ let person_id: i64 = sqlx::query_scalar(
+ r#"
+ INSERT INTO posthog_person
+ (created_at, properties, properties_last_updated_at, properties_last_operation,
+ team_id, is_identified, uuid, version)
+ VALUES (now(), '{}'::jsonb, '{}'::jsonb, '{}'::jsonb, $1, false, gen_random_uuid(), 0)
+ RETURNING id
+ "#,
+ )
+ .bind(self.team_id as i32)
+ .fetch_one(&self.pool)
+ .await
+ .expect("Failed to insert person");
+
+ sqlx::query(
+ r#"
+ INSERT INTO posthog_persondistinctid (distinct_id, person_id, team_id, version)
+ VALUES ($1, $2, $3, 0)
+ "#,
+ )
+ .bind(distinct_id)
+ .bind(person_id)
+ .bind(self.team_id as i32)
+ .execute(&self.pool)
+ .await
+ .expect("Failed to insert distinct id");
+
+ person_id
+ }
+
+ pub async fn cleanup(&self) -> Result<(), sqlx::Error> {
+ sqlx::query("DELETE FROM posthog_persondistinctid WHERE team_id = $1")
+ .bind(self.team_id as i32)
+ .execute(&self.pool)
+ .await?;
+ sqlx::query("DELETE FROM posthog_personlessdistinctid WHERE team_id = $1")
+ .bind(self.team_id as i32)
+ .execute(&self.pool)
+ .await?;
+ sqlx::query("DELETE FROM posthog_person WHERE team_id = $1")
+ .bind(self.team_id as i32)
+ .execute(&self.pool)
+ .await?;
+ Ok(())
+ }
+}
diff --git a/rust/personhog-identity/tests/service_tests.rs b/rust/personhog-identity/tests/service_tests.rs
new file mode 100644
index 000000000000..5ab34575fce4
--- /dev/null
+++ b/rust/personhog-identity/tests/service_tests.rs
@@ -0,0 +1,294 @@
+mod common;
+
+use std::collections::VecDeque;
+use std::sync::{Arc, Mutex};
+
+use async_trait::async_trait;
+use common::TestContext;
+use tonic::{Code, Request, Status};
+
+use personhog_identity::leader::PropertyWriter;
+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,
+};
+use personhog_proto::personhog::types::v1::{
+ UpdatePersonPropertiesRequest, UpdatePersonPropertiesResponse,
+};
+
+/// Records calls and replays queued responses; defaults to an "updated, no
+/// person payload" ack when the queue is empty.
+#[derive(Default)]
+struct MockPropertyWriter {
+ calls: Mutex<Vec<UpdatePersonPropertiesRequest>>,
+ responses: Mutex<VecDeque<Result<UpdatePersonPropertiesResponse, Status>>>,
+}
+
+impl MockPropertyWriter {
+ fn queue(&self, response: Result<UpdatePersonPropertiesResponse, Status>) {
+ self.responses.lock().unwrap().push_back(response);
+ }
+
+ fn calls(&self) -> Vec<UpdatePersonPropertiesRequest> {
+ self.calls.lock().unwrap().clone()
+ }
+}
+
+#[async_trait]
+impl PropertyWriter for MockPropertyWriter {
+ async fn update_person_properties(
+ &self,
+ request: UpdatePersonPropertiesRequest,
+ ) -> Result<UpdatePersonPropertiesResponse, Status> {
+ self.calls.lock().unwrap().push(request);
+ self.responses
+ .lock()
+ .unwrap()
+ .pop_front()
+ .unwrap_or_else(|| {
+ Ok(UpdatePersonPropertiesResponse {
+ person: None,
+ updated: true,
+ })
+ })
+ }
+}
+
+struct ServiceTestContext {
+ ctx: TestContext,
+ writer: Arc<MockPropertyWriter>,
+ service: PersonHogIdentityService,
+}
+
+impl ServiceTestContext {
+ async fn new() -> Self {
+ Self::with_limits(RequestLimits {
+ max_batch_size: 250,
+ max_distinct_id_length: 400,
+ max_extra_distinct_ids: 5000,
+ })
+ .await
+ }
+
+ async fn with_limits(limits: RequestLimits) -> Self {
+ let ctx = TestContext::new().await;
+ let writer = Arc::new(MockPropertyWriter::default());
+ let service = PersonHogIdentityService::new(ctx.storage.clone(), writer.clone(), limits);
+ Self {
+ ctx,
+ writer,
+ service,
+ }
+ }
+
+ fn entry(&self, distinct_id: &str) -> GetOrCreatePersonEntry {
+ GetOrCreatePersonEntry {
+ team_id: self.ctx.team_id,
+ distinct_id: distinct_id.to_string(),
+ extra_distinct_ids: vec![],
+ event_name: "$identify".to_string(),
+ set_properties: Vec::new(),
+ set_once_properties: Vec::new(),
+ created_at: 0,
+ is_identified: false,
+ }
+ }
+
+ async fn get_or_create_single(
+ &self,
+ entry: GetOrCreatePersonEntry,
+ ) -> Result<(Option<i64>, bool), Status> {
+ let response = self
+ .service
+ .get_or_create_person_by_distinct_id(Request::new(
+ GetOrCreatePersonByDistinctIdRequest { entry: Some(entry) },
+ ))
+ .await?
+ .into_inner();
+ Ok((response.person.map(|p| p.id), response.created))
+ }
+}
+
+#[tokio::test]
+async fn creates_person_and_applies_initial_properties_through_leader() {
+ let t = ServiceTestContext::new().await;
+ let mut entry = t.entry("svc-user-1");
+ entry.set_properties = br#"{"plan":"free"}"#.to_vec();
+
+ let (person_id, created) = t
+ .get_or_create_single(entry)
+ .await
+ .expect("rpc should succeed");
+ assert!(created);
+ let person_id = person_id.expect("person should be returned");
+
+ let calls = t.writer.calls();
+ assert_eq!(calls.len(), 1);
+ assert_eq!(calls[0].team_id, t.ctx.team_id);
+ assert_eq!(calls[0].person_id, person_id);
+ assert_eq!(calls[0].event_name, "$identify");
+ assert_eq!(calls[0].set_properties, br#"{"plan":"free"}"#.to_vec());
+
+ t.ctx.cleanup().await.ok();
+}
+
+#[tokio::test]
+async fn create_without_properties_skips_the_leader() {
+ let t = ServiceTestContext::new().await;
+
+ let (_, created) = t
+ .get_or_create_single(t.entry("svc-user-2"))
+ .await
+ .expect("rpc should succeed");
+ assert!(created);
+ assert!(t.writer.calls().is_empty());
+
+ t.ctx.cleanup().await.ok();
+}
+
+#[tokio::test]
+async fn existing_person_is_returned_without_leader_call() {
+ let t = ServiceTestContext::new().await;
+ let existing_id = t.ctx.insert_person_with_distinct_id("svc-user-3").await;
+
+ let mut entry = t.entry("svc-user-3");
+ entry.set_properties = br#"{"plan":"pro"}"#.to_vec();
+ let (person_id, created) = t
+ .get_or_create_single(entry)
+ .await
+ .expect("rpc should succeed");
+
+ assert!(!created);
+ assert_eq!(person_id, Some(existing_id));
+ // The exists branch never applies properties — the caller does, through
+ // the normal UpdatePersonProperties path.
+ assert!(t.writer.calls().is_empty());
+
+ t.ctx.cleanup().await.ok();
+}
+
+#[tokio::test]
+async fn leader_failure_fails_the_key_but_keeps_the_stub_for_retry() {
+ let t = ServiceTestContext::new().await;
+ t.writer.queue(Err(Status::unavailable("leader down")));
+
+ let mut entry = t.entry("svc-user-4");
+ entry.set_properties = br#"{"a":1}"#.to_vec();
+ let status = t
+ .get_or_create_single(entry.clone())
+ .await
+ .expect_err("rpc should fail");
+ assert_eq!(status.code(), Code::Unavailable);
+
+ // The retried key resolves to the committed stub and reports created =
+ // false, so the caller applies properties through the update path.
+ let (_, created) = t
+ .get_or_create_single(entry)
+ .await
+ .expect("retry should succeed");
+ assert!(!created);
+
+ t.ctx.cleanup().await.ok();
+}
+
+#[tokio::test]
+async fn batch_returns_per_key_outcomes_in_order() {
+ let t = ServiceTestContext::new().await;
+ let existing_id = t
+ .ctx
+ .insert_person_with_distinct_id("svc-batch-existing")
+ .await;
+
+ let invalid = GetOrCreatePersonEntry {
+ distinct_id: String::new(),
+ ..t.entry("")
+ };
+ let response = t
+ .service
+ .get_or_create_persons_by_distinct_ids(Request::new(
+ GetOrCreatePersonsByDistinctIdsRequest {
+ entries: vec![
+ t.entry("svc-batch-existing"),
+ t.entry("svc-batch-new"),
+ invalid,
+ ],
+ },
+ ))
+ .await
+ .expect("batch rpc should succeed")
+ .into_inner();
+
+ assert_eq!(response.results.len(), 3);
+
+ assert_eq!(response.results[0].distinct_id, "svc-batch-existing");
+ assert!(!response.results[0].created);
+ assert_eq!(
+ response.results[0].person.as_ref().map(|p| p.id),
+ Some(existing_id)
+ );
+
+ assert_eq!(response.results[1].distinct_id, "svc-batch-new");
+ assert!(response.results[1].created);
+ assert!(response.results[1].person.is_some());
+
+ assert!(response.results[2].person.is_none());
+ assert!(response.results[2]
+ .error
+ .as_deref()
+ .unwrap()
+ .contains("distinct_id"));
+
+ t.ctx.cleanup().await.ok();
+}
+
+#[tokio::test]
+async fn duplicate_keys_in_batch_create_exactly_once() {
+ let t = ServiceTestContext::new().await;
+
+ let response = t
+ .service
+ .get_or_create_persons_by_distinct_ids(Request::new(
+ GetOrCreatePersonsByDistinctIdsRequest {
+ entries: vec![t.entry("svc-dup"), t.entry("svc-dup")],
+ },
+ ))
+ .await
+ .expect("batch rpc should succeed")
+ .into_inner();
+
+ assert_eq!(response.results.len(), 2);
+ assert!(response.results[0].created);
+ assert!(!response.results[1].created);
+ assert_eq!(
+ response.results[0].person.as_ref().map(|p| p.id),
+ response.results[1].person.as_ref().map(|p| p.id)
+ );
+
+ t.ctx.cleanup().await.ok();
+}
+
+#[tokio::test]
+async fn batch_over_limit_is_rejected() {
+ let t = ServiceTestContext::with_limits(RequestLimits {
+ max_batch_size: 2,
+ max_distinct_id_length: 400,
+ max_extra_distinct_ids: 5000,
+ })
+ .await;
+
+ let status = t
+ .service
+ .get_or_create_persons_by_distinct_ids(Request::new(
+ GetOrCreatePersonsByDistinctIdsRequest {
+ entries: vec![t.entry("a"), t.entry("b"), t.entry("c")],
+ },
+ ))
+ .await
+ .expect_err("batch should be rejected");
+ assert_eq!(status.code(), Code::InvalidArgument);
+
+ t.ctx.cleanup().await.ok();
+}
diff --git a/rust/personhog-identity/tests/storage_tests.rs b/rust/personhog-identity/tests/storage_tests.rs
new file mode 100644
index 000000000000..9deecc2ec5a3
--- /dev/null
+++ b/rust/personhog-identity/tests/storage_tests.rs
@@ -0,0 +1,479 @@
+mod common;
+
+use std::time::Duration;
+
+use chrono::{TimeZone, Utc};
+use common::TestContext;
+
+use personhog_common::persons::person_uuid;
+use personhog_identity::storage::{IdentityStorage, PersonStub, StubOutcome};
+
+/// Storage-assertion helpers used only by this test binary.
+impl TestContext {
+ async fn insert_personless_distinct_id(&self, distinct_id: &str, is_merged: bool) {
+ sqlx::query(
+ r#"
+ INSERT INTO posthog_personlessdistinctid (distinct_id, is_merged, created_at, team_id)
+ VALUES ($1, $2, now(), $3)
+ "#,
+ )
+ .bind(distinct_id)
+ .bind(is_merged)
+ .bind(self.team_id as i32)
+ .execute(&self.pool)
+ .await
+ .expect("Failed to insert personless distinct id");
+ }
+
+ async fn distinct_id_version(&self, distinct_id: &str) -> Option<i64> {
+ sqlx::query_scalar(
+ "SELECT version FROM posthog_persondistinctid WHERE team_id = $1 AND distinct_id = $2",
+ )
+ .bind(self.team_id as i32)
+ .bind(distinct_id)
+ .fetch_optional(&self.pool)
+ .await
+ .expect("Failed to fetch distinct id version")
+ .flatten()
+ }
+
+ async fn personless_is_merged(&self, distinct_id: &str) -> Option<bool> {
+ sqlx::query_scalar(
+ "SELECT is_merged FROM posthog_personlessdistinctid WHERE team_id = $1 AND distinct_id = $2",
+ )
+ .bind(self.team_id as i32)
+ .bind(distinct_id)
+ .fetch_optional(&self.pool)
+ .await
+ .expect("Failed to fetch personless row")
+ }
+
+ async fn person_count(&self) -> i64 {
+ sqlx::query_scalar("SELECT count(*) FROM posthog_person WHERE team_id = $1")
+ .bind(self.team_id as i32)
+ .fetch_one(&self.pool)
+ .await
+ .expect("Failed to count persons")
+ }
+}
+
+fn stub(ctx: &TestContext, distinct_id: &str, extras: &[&str]) -> PersonStub {
+ PersonStub {
+ team_id: ctx.team_id,
+ distinct_id: distinct_id.to_string(),
+ extra_distinct_ids: extras.iter().map(|s| s.to_string()).collect(),
+ created_at: Utc.with_ymd_and_hms(2026, 7, 20, 12, 34, 56).unwrap(),
+ is_identified: false,
+ }
+}
+
+#[tokio::test]
+async fn creates_stub_with_deterministic_uuid_and_version_zero() {
+ let ctx = TestContext::new().await;
+
+ let outcomes = ctx
+ .storage
+ .create_person_stubs(&[stub(&ctx, "user-1", &[])])
+ .await
+ .expect("create should succeed");
+
+ let [StubOutcome::Committed { person, created }] = &outcomes[..] else {
+ panic!("expected one committed outcome");
+ };
+ assert!(created);
+ assert_eq!(person.uuid, person_uuid(ctx.team_id, "user-1"));
+ assert_eq!(person.version, Some(0));
+ assert_eq!(person.properties.as_deref(), Some("{}"));
+ assert!(!person.is_identified);
+ assert_eq!(
+ person.created_at,
+ Utc.with_ymd_and_hms(2026, 7, 20, 12, 34, 56).unwrap()
+ );
+ assert_eq!(ctx.distinct_id_version("user-1").await, Some(0));
+
+ let resolved = ctx
+ .storage
+ .resolve_distinct_ids(&[(ctx.team_id, "user-1".to_string())])
+ .await
+ .expect("resolve should succeed");
+ assert_eq!(resolved[&(ctx.team_id, "user-1".to_string())].id, person.id);
+
+ ctx.cleanup().await.ok();
+}
+
+#[tokio::test]
+async fn retried_create_returns_existing_person_without_duplicating() {
+ let ctx = TestContext::new().await;
+
+ let first = ctx
+ .storage
+ .create_person_stubs(&[stub(&ctx, "user-2", &[])])
+ .await
+ .expect("first create should succeed");
+ let [StubOutcome::Committed {
+ person: first_person,
+ created: true,
+ }] = &first[..]
+ else {
+ panic!("expected created outcome");
+ };
+
+ let second = ctx
+ .storage
+ .create_person_stubs(&[stub(&ctx, "user-2", &[])])
+ .await
+ .expect("second create should succeed");
+ let [StubOutcome::Committed { person, created }] = &second[..] else {
+ panic!("expected committed outcome");
+ };
+ assert!(!created);
+ assert_eq!(person.id, first_person.id);
+ assert_eq!(ctx.person_count().await, 1);
+
+ ctx.cleanup().await.ok();
+}
+
+#[tokio::test]
+async fn extra_distinct_ids_carry_personless_history_as_version_one() {
+ let ctx = TestContext::new().await;
+ // "seen-before" was used personless; "fresh" was not.
+ ctx.insert_personless_distinct_id("seen-before", false)
+ .await;
+
+ let outcomes = ctx
+ .storage
+ .create_person_stubs(&[stub(&ctx, "primary", &["seen-before", "fresh"])])
+ .await
+ .expect("create should succeed");
+ let [StubOutcome::Committed { created: true, .. }] = &outcomes[..] else {
+ panic!("expected created outcome");
+ };
+
+ assert_eq!(ctx.distinct_id_version("primary").await, Some(0));
+ assert_eq!(ctx.distinct_id_version("seen-before").await, Some(1));
+ assert_eq!(ctx.distinct_id_version("fresh").await, Some(0));
+ // Both extras are marked merged so concurrent personless events re-resolve.
+ assert_eq!(ctx.personless_is_merged("seen-before").await, Some(true));
+ assert_eq!(ctx.personless_is_merged("fresh").await, Some(true));
+
+ ctx.cleanup().await.ok();
+}
+
+#[tokio::test]
+async fn create_loses_race_when_distinct_id_is_mapped_to_another_person() {
+ let ctx = TestContext::new().await;
+ // The distinct id is already mapped to a person whose uuid is not the
+ // deterministic one (e.g. it arrived via merge), so the stub insert
+ // succeeds but the mapping conflict must roll that stub back.
+ let existing_id = ctx.insert_person_with_distinct_id("taken").await;
+
+ let outcomes = ctx
+ .storage
+ .create_person_stubs(&[stub(&ctx, "taken", &[])])
+ .await
+ .expect("create should not error");
+ assert!(matches!(outcomes[..], [StubOutcome::LostRace]));
+
+ // No orphan stub row was left behind.
+ assert_eq!(ctx.person_count().await, 1);
+ let resolved = ctx
+ .storage
+ .resolve_distinct_ids(&[(ctx.team_id, "taken".to_string())])
+ .await
+ .expect("resolve should succeed");
+ assert_eq!(
+ resolved[&(ctx.team_id, "taken".to_string())].id,
+ existing_id
+ );
+
+ ctx.cleanup().await.ok();
+}
+
+#[tokio::test]
+async fn lost_race_undo_reverts_only_the_personless_marks_it_made() {
+ let ctx = TestContext::new().await;
+ // The loser's primary distinct id is already mapped elsewhere, so its
+ // whole stub rolls back — including the step that marked its extras
+ // merged. One extra per prior state: no row, unmerged row, merged row.
+ ctx.insert_person_with_distinct_id("undo-taken").await;
+ ctx.insert_personless_distinct_id("undo-flipped", false)
+ .await;
+ ctx.insert_personless_distinct_id("undo-merged", true).await;
+
+ let outcomes = ctx
+ .storage
+ .create_person_stubs(&[
+ stub(&ctx, "undo-winner", &["undo-shared"]),
+ stub(
+ &ctx,
+ "undo-taken",
+ &["undo-fresh", "undo-flipped", "undo-merged", "undo-shared"],
+ ),
+ ])
+ .await
+ .expect("create should not error");
+ assert!(
+ matches!(
+ outcomes[..],
+ [
+ StubOutcome::Committed { created: true, .. },
+ StubOutcome::LostRace
+ ]
+ ),
+ "expected committed + lost race, got {outcomes:?}"
+ );
+
+ // The undone stub's marks are reverted to their prior state…
+ assert_eq!(ctx.personless_is_merged("undo-fresh").await, None);
+ assert_eq!(ctx.personless_is_merged("undo-flipped").await, Some(false));
+ assert_eq!(ctx.personless_is_merged("undo-merged").await, Some(true));
+ // …but an extra shared with a committed stub keeps its mapping and mark.
+ assert_eq!(ctx.personless_is_merged("undo-shared").await, Some(true));
+ assert_eq!(ctx.distinct_id_version("undo-shared").await, Some(0));
+
+ ctx.cleanup().await.ok();
+}
+
+#[tokio::test]
+async fn batch_mixes_created_existing_and_lost_race_outcomes_per_row() {
+ let ctx = TestContext::new().await;
+ let taken_id = ctx.insert_person_with_distinct_id("mix-taken").await;
+ // "mix-existing" already has its deterministic stub from an earlier create.
+ let seeded = ctx
+ .storage
+ .create_person_stubs(&[stub(&ctx, "mix-existing", &[])])
+ .await
+ .expect("seed create should succeed");
+ let [StubOutcome::Committed {
+ person: seeded_person,
+ created: true,
+ }] = &seeded[..]
+ else {
+ panic!("expected seeded outcome");
+ };
+
+ let outcomes = ctx
+ .storage
+ .create_person_stubs(&[
+ stub(&ctx, "mix-new", &[]),
+ stub(&ctx, "mix-existing", &[]),
+ stub(&ctx, "mix-taken", &[]),
+ ])
+ .await
+ .expect("batch create should succeed");
+
+ let [StubOutcome::Committed {
+ person: new_person,
+ created: true,
+ }, StubOutcome::Committed {
+ person: existing_person,
+ created: false,
+ }, StubOutcome::LostRace] = &outcomes[..]
+ else {
+ panic!("expected created/existing/lost-race outcomes, got {outcomes:?}");
+ };
+
+ assert_eq!(new_person.uuid, person_uuid(ctx.team_id, "mix-new"));
+ assert_eq!(existing_person.id, seeded_person.id);
+ // The lost race left no orphan: taken + existing + new = 3 persons.
+ assert_eq!(ctx.person_count().await, 3);
+ let resolved = ctx
+ .storage
+ .resolve_distinct_ids(&[(ctx.team_id, "mix-taken".to_string())])
+ .await
+ .expect("resolve should succeed");
+ assert_eq!(
+ resolved[&(ctx.team_id, "mix-taken".to_string())].id,
+ taken_id
+ );
+
+ ctx.cleanup().await.ok();
+}
+
+#[tokio::test]
+async fn concurrent_creates_for_one_distinct_id_create_exactly_once() {
+ let ctx = TestContext::new().await;
+
+ let tasks: Vec<_> = (0..8)
+ .map(|_| {
+ let storage = ctx.storage.clone();
+ let stub = stub(&ctx, "race-key", &[]);
+ tokio::spawn(async move { storage.create_person_stubs(&[stub]).await })
+ })
+ .collect();
+
+ let mut created_count = 0;
+ let mut person_ids = Vec::new();
+ for task in tasks {
+ let outcomes = task
+ .await
+ .expect("task must not panic")
+ .expect("create should not error");
+ let [StubOutcome::Committed { person, created }] = &outcomes[..] else {
+ panic!("every racer must converge on the winner, got {outcomes:?}");
+ };
+ created_count += usize::from(*created);
+ person_ids.push(person.id);
+ }
+
+ assert_eq!(created_count, 1, "exactly one racer reports created = true");
+ assert!(person_ids.windows(2).all(|w| w[0] == w[1]));
+ assert_eq!(ctx.person_count().await, 1);
+
+ ctx.cleanup().await.ok();
+}
+
+/// The uncommitted-winner window: a concurrent creator has inserted the
+/// deterministic-uuid person but not yet committed. Our insert must block in
+/// the speculative-insert wait, and after the winner commits, the separate
+/// winner-fetch statement must see the row in its fresh snapshot — a
+/// same-statement fetch would miss it and lose the person entirely.
+#[tokio::test]
+async fn create_blocked_on_uncommitted_winner_resolves_to_it_after_commit() {
+ let ctx = TestContext::new().await;
+ let uuid = person_uuid(ctx.team_id, "held-key");
+
+ let mut held = ctx.pool.begin().await.expect("begin held tx");
+ let winner_id: i64 = sqlx::query_scalar(
+ r#"
+ INSERT INTO posthog_person
+ (created_at, properties, properties_last_updated_at, properties_last_operation,
+ team_id, is_identified, uuid, version)
+ VALUES (now(), '{}'::jsonb, '{}'::jsonb, '{}'::jsonb, $1, false, $2, 0)
+ RETURNING id
+ "#,
+ )
+ .bind(ctx.team_id as i32)
+ .bind(uuid)
+ .fetch_one(&mut *held)
+ .await
+ .expect("insert uncommitted winner");
+
+ let storage = ctx.storage.clone();
+ let racing_stub = stub(&ctx, "held-key", &[]);
+ let racer = tokio::spawn(async move { storage.create_person_stubs(&[racing_stub]).await });
+
+ // The racer's insert conflicts with the uncommitted row, so it must sit
+ // in the speculative-insert wait for as long as the transaction is open.
+ tokio::time::sleep(Duration::from_millis(300)).await;
+ assert!(
+ !racer.is_finished(),
+ "create must block on the uncommitted winner's insert"
+ );
+
+ held.commit().await.expect("commit winner");
+ let outcomes = racer
+ .await
+ .expect("task must not panic")
+ .expect("create should not error");
+ let [StubOutcome::Committed { person, created }] = &outcomes[..] else {
+ panic!("racer must resolve to the committed winner, got {outcomes:?}");
+ };
+ assert!(!created);
+ assert_eq!(person.id, winner_id);
+
+ // The winner had no distinct id row; the racer attached it.
+ assert_eq!(ctx.person_count().await, 1);
+ let resolved = ctx
+ .storage
+ .resolve_distinct_ids(&[(ctx.team_id, "held-key".to_string())])
+ .await
+ .expect("resolve should succeed");
+ assert_eq!(
+ resolved[&(ctx.team_id, "held-key".to_string())].id,
+ winner_id
+ );
+
+ ctx.cleanup().await.ok();
+}
+
+/// The uncommitted mapping-steal window: a concurrent writer (a merge, an
+/// add-distinct-id) has mapped the distinct id to a different person but not
+/// yet committed. Our stub insert succeeds (different uuid), the distinct id
+/// insert blocks on the unique index, and after the winner commits the whole
+/// stub must roll back as a lost race — leaving no orphan person behind.
+#[tokio::test]
+async fn create_blocked_on_uncommitted_mapping_rolls_back_as_lost_race() {
+ let ctx = TestContext::new().await;
+
+ let mut held = ctx.pool.begin().await.expect("begin held tx");
+ let other_id: i64 = sqlx::query_scalar(
+ r#"
+ INSERT INTO posthog_person
+ (created_at, properties, properties_last_updated_at, properties_last_operation,
+ team_id, is_identified, uuid, version)
+ VALUES (now(), '{}'::jsonb, '{}'::jsonb, '{}'::jsonb, $1, false, gen_random_uuid(), 0)
+ RETURNING id
+ "#,
+ )
+ .bind(ctx.team_id as i32)
+ .fetch_one(&mut *held)
+ .await
+ .expect("insert other person");
+ sqlx::query(
+ r#"
+ INSERT INTO posthog_persondistinctid (distinct_id, person_id, team_id, version)
+ VALUES ($1, $2, $3, 0)
+ "#,
+ )
+ .bind("stolen-key")
+ .bind(other_id)
+ .bind(ctx.team_id as i32)
+ .execute(&mut *held)
+ .await
+ .expect("map distinct id in held tx");
+
+ let storage = ctx.storage.clone();
+ let racing_stub = stub(&ctx, "stolen-key", &[]);
+ let racer = tokio::spawn(async move { storage.create_person_stubs(&[racing_stub]).await });
+
+ tokio::time::sleep(Duration::from_millis(300)).await;
+ assert!(
+ !racer.is_finished(),
+ "create must block on the uncommitted distinct id mapping"
+ );
+
+ held.commit().await.expect("commit mapping winner");
+ let outcomes = racer
+ .await
+ .expect("task must not panic")
+ .expect("create should not error");
+ assert!(
+ matches!(outcomes[..], [StubOutcome::LostRace]),
+ "stolen mapping must resolve to a lost race, got {outcomes:?}"
+ );
+
+ // The racer's stub was rolled back; only the mapping winner remains.
+ assert_eq!(ctx.person_count().await, 1);
+ let resolved = ctx
+ .storage
+ .resolve_distinct_ids(&[(ctx.team_id, "stolen-key".to_string())])
+ .await
+ .expect("resolve should succeed");
+ assert_eq!(
+ resolved[&(ctx.team_id, "stolen-key".to_string())].id,
+ other_id
+ );
+
+ ctx.cleanup().await.ok();
+}
+
+#[tokio::test]
+async fn resolve_returns_only_existing_keys() {
+ let ctx = TestContext::new().await;
+ let person_id = ctx.insert_person_with_distinct_id("known").await;
+
+ let resolved = ctx
+ .storage
+ .resolve_distinct_ids(&[
+ (ctx.team_id, "known".to_string()),
+ (ctx.team_id, "unknown".to_string()),
+ ])
+ .await
+ .expect("resolve should succeed");
+
+ assert_eq!(resolved.len(), 1);
+ assert_eq!(resolved[&(ctx.team_id, "known".to_string())].id, person_id);
+
+ ctx.cleanup().await.ok();
+}
diff --git a/rust/personhog-proto/build.rs b/rust/personhog-proto/build.rs
index 3a6a2144cd10..9e26996fb6fe 100644
--- a/rust/personhog-proto/build.rs
+++ b/rust/personhog-proto/build.rs
@@ -13,6 +13,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
format!("{proto_root}/personhog/types/v1/cohort.proto"),
format!("{proto_root}/personhog/types/v1/feature_flag.proto"),
// Services
+ format!("{proto_root}/personhog/identity/v1/identity.proto"),
format!("{proto_root}/personhog/leader/v1/leader.proto"),
format!("{proto_root}/personhog/replica/v1/replica.proto"),
format!("{proto_root}/personhog/service/v1/service.proto"),
diff --git a/rust/personhog-proto/src/lib.rs b/rust/personhog-proto/src/lib.rs
index ec83130b79aa..2f298076106e 100644
--- a/rust/personhog-proto/src/lib.rs
+++ b/rust/personhog-proto/src/lib.rs
@@ -4,6 +4,11 @@ pub mod personhog {
tonic::include_proto!("personhog.types.v1");
}
}
+ pub mod identity {
+ pub mod v1 {
+ tonic::include_proto!("personhog.identity.v1");
+ }
+ }
pub mod leader {
pub mod v1 {
tonic::include_proto!("personhog.leader.v1");
diff --git a/rust/personhog-test-harness/Cargo.toml b/rust/personhog-test-harness/Cargo.toml
index b268d874a0fb..939c2de92613 100644
--- a/rust/personhog-test-harness/Cargo.toml
+++ b/rust/personhog-test-harness/Cargo.toml
@@ -5,6 +5,7 @@ edition = "2021"
publish = false
[dependencies]
+personhog-common = { path = "../personhog-common" }
personhog-proto = { path = "../personhog-proto" }
common-metrics = { path = "../common/metrics" }
personhog-coordination = { path = "../personhog-coordination" }
diff --git a/rust/personhog-test-harness/README.md b/rust/personhog-test-harness/README.md
index 12aac33a46ab..c2cc7c2f994a 100644
--- a/rust/personhog-test-harness/README.md
+++ b/rust/personhog-test-harness/README.md
@@ -35,9 +35,31 @@ target/debug/personhog-test-harness gate --external-router-url http://127.0.0.1:
```
The spawned stack is isolated from the dev stack: its own port range (24xxx, kept below the ephemeral range so outbound connections cannot steal a listen port), its own etcd prefix (`/personhog-test-harness/`), and a per-run changelog topic (`personhog_test_harness_<run_id>`, deleted on teardown).
-Persons are seeded directly in Postgres for a reserved harness team id (SQL is the interim seeding mechanism until the create RPC's future is settled; `src/seed.rs` is the swap seam).
+Persons are seeded directly in Postgres for a reserved harness team id by default; `--create-via-identity` (below) creates them through the identity service instead.
Service logs land in `<bin-dir>/harness-logs/<run_id>/`.
+### Creating persons via the identity service
+
+`--create-via-identity` swaps SQL seeding for the personhog-identity get-or-create path: the spawned stack also runs `personhog-identity`, persons are created through `GetOrCreatePersonsByDistinctIds` (stub insert on the Postgres primary, then initial `$set` properties through the router to the owning leader), and the update traffic then targets the created persons.
+Each create ack is journaled like any other write, so the gate holds create visibility — the initial properties and the acked version — to the same invariant as update visibility, in strong reads and in Postgres.
+
+```bash
+# Create through identity, then update through the router
+target/debug/personhog-test-harness gate --create-via-identity \
+ --duration 10s --persons 100 --concurrency 10
+
+# The create path composes with chaos like any other run
+target/debug/personhog-test-harness gate --create-via-identity \
+ --leaders 3 --partitions 8 --duration 15s --kill-after 5s --scale-up-after 8s
+
+# Against an already-running stack, point at its identity service too
+# (the dev stack runs it at 50055)
+target/debug/personhog-test-harness gate --create-via-identity \
+ --external-router-url http://127.0.0.1:50054 \
+ --external-identity-url http://127.0.0.1:50055 \
+ --pg-target-table personhog_person_tmp
+```
+
Multiple local leaders work because each registers with a `host:port` pod name, which the router's address resolver dials as-is (bare pod names still resolve via DNS on the fleet-wide leader port).
### Chaos disruptions
diff --git a/rust/personhog-test-harness/src/cli.rs b/rust/personhog-test-harness/src/cli.rs
index 8a51e0fec2db..8eee0562f261 100644
--- a/rust/personhog-test-harness/src/cli.rs
+++ b/rust/personhog-test-harness/src/cli.rs
@@ -273,6 +273,22 @@ pub struct GateArgs {
#[arg(long, default_value_t = 30)]
pub leader_lease_ttl: i64,
+ /// Create the persons through the personhog-identity service
+ /// (GetOrCreatePersonsByDistinctIds with initial properties) instead of
+ /// seeding SQL directly. The create acks are journaled like any other
+ /// write, so the gate also asserts create visibility: the initial
+ /// properties must survive into strong reads and Postgres. A spawned
+ /// stack brings up its own identity service; with
+ /// --external-router-url, pass --external-identity-url too.
+ #[arg(long, default_value_t = false)]
+ pub create_via_identity: bool,
+
+ /// Identity service URL for --create-via-identity against an
+ /// already-running stack (the dev stack runs it at
+ /// http://127.0.0.1:50055). Ignored for spawned stacks.
+ #[arg(long)]
+ pub external_identity_url: Option<String>,
+
/// Leave the spawned stack running after the gate finishes (for
/// poking at it manually). Ignored with --external-router-url.
#[arg(long, default_value_t = false)]
diff --git a/rust/personhog-test-harness/src/client.rs b/rust/personhog-test-harness/src/client.rs
index cdbb4f2af19d..07ee00546da7 100644
--- a/rust/personhog-test-harness/src/client.rs
+++ b/rust/personhog-test-harness/src/client.rs
@@ -1,41 +1,32 @@
use std::time::Duration;
use anyhow::{Context, Result};
+use personhog_common::client::RouterClient;
use personhog_proto::personhog::{
- service::v1::person_hog_service_client::PersonHogServiceClient,
+ identity::v1::{
+ person_hog_identity_client::PersonHogIdentityClient, GetOrCreatePersonEntry,
+ GetOrCreatePersonResult, GetOrCreatePersonsByDistinctIdsRequest,
+ },
types::v1::{
- ConsistencyLevel, GetPersonRequest, Person, ReadOptions, UpdatePersonPropertiesRequest,
- UpdatePersonPropertiesResponse,
+ ConsistencyLevel, Person, UpdatePersonPropertiesRequest, UpdatePersonPropertiesResponse,
},
};
-use tonic::metadata::MetadataValue;
use tonic::transport::Channel;
use tonic::Request;
-/// Routing headers the leader-mode router requires on leader-bound calls.
-/// `UpdatePersonProperties` always routes to a leader; `GetPerson` routes to
-/// a leader only when `x-read-consistency: strong` is present.
-const TEAM_ID_HEADER: &str = "x-team-id";
-const PERSON_ID_HEADER: &str = "x-person-id";
-const READ_CONSISTENCY_HEADER: &str = "x-read-consistency";
+const REQUEST_TIMEOUT: Duration = Duration::from_secs(10);
+/// Harness wrapper over the shared router client: same wire behavior,
+/// anyhow-flavored results for scenario code.
#[derive(Clone)]
pub struct HarnessClient {
- inner: PersonHogServiceClient<Channel>,
+ inner: RouterClient,
}
impl HarnessClient {
pub async fn connect(url: &str) -> Result<Self> {
- let channel = Channel::from_shared(url.to_string())
- .context("invalid router URL")?
- .timeout(Duration::from_secs(10))
- .connect_timeout(Duration::from_secs(5))
- .tcp_nodelay(true)
- .connect_lazy();
-
- Ok(Self {
- inner: PersonHogServiceClient::new(channel),
- })
+ let inner = RouterClient::new(url, REQUEST_TIMEOUT).context("invalid router URL")?;
+ Ok(Self { inner })
}
pub async fn get_person(
@@ -44,30 +35,10 @@ impl HarnessClient {
person_id: i64,
consistency: ConsistencyLevel,
) -> Result<Option<Person>> {
- let mut request = Request::new(GetPersonRequest {
- team_id,
- person_id,
- read_options: Some(ReadOptions {
- consistency: consistency.into(),
- ..Default::default()
- }),
- });
- if consistency == ConsistencyLevel::Strong {
- stamp_routing_headers(&mut request, team_id, person_id)?;
- request.metadata_mut().insert(
- READ_CONSISTENCY_HEADER,
- MetadataValue::from_static("strong"),
- );
- }
-
- let resp = self
- .inner
- .clone()
- .get_person(request)
+ self.inner
+ .get_person(team_id, person_id, consistency)
.await
- .context("GetPerson failed")?;
-
- Ok(resp.into_inner().person)
+ .context("GetPerson failed")
}
pub async fn update_properties(
@@ -78,36 +49,53 @@ impl HarnessClient {
set_once_properties: serde_json::Value,
unset_properties: Vec<String>,
) -> Result<UpdatePersonPropertiesResponse> {
- let mut request = Request::new(UpdatePersonPropertiesRequest {
- team_id,
- person_id,
- event_name: "$set".to_string(),
- set_properties: serde_json::to_vec(&set_properties)?,
- set_once_properties: serde_json::to_vec(&set_once_properties)?,
- unset_properties,
- });
- stamp_routing_headers(&mut request, team_id, person_id)?;
+ self.inner
+ .update_person_properties(UpdatePersonPropertiesRequest {
+ team_id,
+ person_id,
+ event_name: "$set".to_string(),
+ set_properties: serde_json::to_vec(&set_properties)?,
+ set_once_properties: serde_json::to_vec(&set_once_properties)?,
+ unset_properties,
+ })
+ .await
+ .context("UpdatePersonProperties failed")
+ }
+}
+/// Client for the personhog-identity service — the get-or-create entry
+/// point. Called directly, not through the router, so no routing headers.
+#[derive(Clone)]
+pub struct IdentityClient {
+ inner: PersonHogIdentityClient<Channel>,
+}
+
+impl IdentityClient {
+ pub async fn connect(url: &str) -> Result<Self> {
+ let channel = Channel::from_shared(url.to_string())
+ .context("invalid identity URL")?
+ .timeout(REQUEST_TIMEOUT)
+ .connect_timeout(Duration::from_secs(5))
+ .tcp_nodelay(true)
+ .connect_lazy();
+
+ Ok(Self {
+ inner: PersonHogIdentityClient::new(channel),
+ })
+ }
+
+ pub async fn get_or_create_persons(
+ &self,
+ entries: Vec<GetOrCreatePersonEntry>,
+ ) -> Result<Vec<GetOrCreatePersonResult>> {
let resp = self
.inner
.clone()
- .update_person_properties(request)
+ .get_or_create_persons_by_distinct_ids(Request::new(
+ GetOrCreatePersonsByDistinctIdsRequest { entries },
+ ))
.await
- .context("UpdatePersonProperties failed")?;
-
- Ok(resp.into_inner())
+ .context("GetOrCreatePersonsByDistinctIds failed")?;
+ Ok(resp.into_inner().results)
}
}
-
-fn stamp_routing_headers<T>(request: &mut Request<T>, team_id: i64, person_id: i64) -> Result<()> {
- let metadata = request.metadata_mut();
- metadata.insert(
- TEAM_ID_HEADER,
- MetadataValue::try_from(team_id.to_string()).context("invalid team id header")?,
- );
- metadata.insert(
- PERSON_ID_HEADER,
- MetadataValue::try_from(person_id.to_string()).context("invalid person id header")?,
- );
- Ok(())
-}
diff --git a/rust/personhog-test-harness/src/scenarios/gate.rs b/rust/personhog-test-harness/src/scenarios/gate.rs
index 503adfa2ef5c..f39c99bd3f92 100644
--- a/rust/personhog-test-harness/src/scenarios/gate.rs
+++ b/rust/personhog-test-harness/src/scenarios/gate.rs
@@ -1,3 +1,4 @@
+use std::collections::HashMap;
use std::fmt;
use std::path::{Path, PathBuf};
use std::sync::atomic::AtomicBool;
@@ -7,8 +8,10 @@ use std::time::{Duration, Instant};
use anyhow::{bail, Context, Result};
use sqlx::postgres::PgPool;
+use personhog_proto::personhog::identity::v1::GetOrCreatePersonEntry;
+
use crate::cli::GateArgs;
-use crate::client::HarnessClient;
+use crate::client::{HarnessClient, IdentityClient};
use crate::report::print_report;
use crate::scenarios::{blast, consistency};
use crate::seed;
@@ -127,6 +130,18 @@ pub async fn run(args: GateArgs) -> Result<()> {
if args.external_router_url.is_some() && (!chaos.is_empty() || args.kill_handoff_target) {
bail!("chaos flags require a spawned stack; they cannot target --external-router-url");
}
+ if args.create_via_identity
+ && args.external_router_url.is_some()
+ && args.external_identity_url.is_none()
+ {
+ bail!("--create-via-identity with --external-router-url needs --external-identity-url");
+ }
+ // The identity service writes the real posthog_person table (its distinct
+ // id FKs require it); a stack targeting another table would recover
+ // created persons from a table they were never written to.
+ if args.create_via_identity && args.pg_target_table != "posthog_person" {
+ bail!("--create-via-identity requires --pg-target-table posthog_person");
+ }
if (args.router_kill_after.is_some() || args.router_shutdown_after.is_some())
&& args.routers < 3
{
@@ -158,6 +173,7 @@ pub async fn run(args: GateArgs) -> Result<()> {
cache_memory_capacity: args.cache_capacity,
recovery_pool_size: args.recovery_pool_size,
leader_lease_ttl: args.leader_lease_ttl,
+ spawn_identity: args.create_via_identity,
})
.await?,
)
@@ -178,14 +194,33 @@ pub async fn run(args: GateArgs) -> Result<()> {
// A crashed prior run may have left rows behind; the team id belongs to
// the harness, so start from a clean slate.
seed::cleanup_team(&pool, &args.pg_target_table, args.team_id).await?;
- let person_ids = Arc::new(
- seed::seed_persons(&pool, &args.pg_target_table, args.team_id, args.persons).await?,
- );
- println!(
- "Seeded {} persons for team {}",
- person_ids.len(),
- args.team_id
- );
+ let state = PersonState::new();
+ // A spawned stack always uses its own identity service — the gate's
+ // assertions target that stack, so an external identity service pointed
+ // elsewhere would only produce confusing failures.
+ let identity_url = match (&args.external_identity_url, &stack) {
+ _ if !args.create_via_identity => None,
+ (_, Some(stack)) => stack.identity_url.clone(),
+ (Some(url), None) => Some(url.clone()),
+ (None, None) => unreachable!("validated above"),
+ };
+ let person_ids = match &identity_url {
+ Some(url) => {
+ let ids = create_persons_via_identity(url, args.team_id, args.persons, &state).await?;
+ println!(
+ "Created {} persons via identity for team {}",
+ ids.len(),
+ args.team_id
+ );
+ Arc::new(ids)
+ }
+ None => {
+ let ids = seed::seed_persons(&pool, &args.pg_target_table, args.team_id, args.persons)
+ .await?;
+ println!("Seeded {} persons for team {}", ids.len(), args.team_id);
+ Arc::new(ids)
+ }
+ };
println!(
"Driving traffic for {} with concurrency {}...",
@@ -193,7 +228,6 @@ pub async fn run(args: GateArgs) -> Result<()> {
args.concurrency
);
let collector = Arc::new(StatsCollector::new());
- let state = PersonState::new();
let traffic = {
let client = client.clone();
let person_ids = person_ids.clone();
@@ -370,6 +404,75 @@ pub async fn run(args: GateArgs) -> Result<()> {
Ok(())
}
+/// Create the traffic-target persons through the identity service's batch
+/// get-or-create, with one seed property per person. The create ack covers
+/// both planes (stub committed in Postgres, initial properties durable in
+/// the changelog), so each ack is journaled like any other write — the
+/// end-of-run strong reads and the Postgres check then hold create
+/// visibility to the same invariant as update visibility.
+async fn create_persons_via_identity(
+ identity_url: &str,
+ team_id: i64,
+ count: u32,
+ state: &PersonState,
+) -> Result<Vec<i64>> {
+ /// The identity service caps batches at 250 entries by default.
+ const CREATE_BATCH_SIZE: u32 = 250;
+
+ let client = IdentityClient::connect(identity_url).await?;
+ let mut person_ids = Vec::with_capacity(count as usize);
+ let mut start = 0u32;
+ while start < count {
+ let end = (start + CREATE_BATCH_SIZE).min(count);
+ let entries: Vec<GetOrCreatePersonEntry> = (start..end)
+ .map(|i| {
+ let distinct_id = format!("harness-gate-{team_id}-{i}");
+ GetOrCreatePersonEntry {
+ team_id,
+ distinct_id: distinct_id.clone(),
+ extra_distinct_ids: vec![],
+ event_name: "$set".to_string(),
+ set_properties: serde_json::to_vec(
+ &serde_json::json!({ "harness_seed": distinct_id }),
+ )
+ .expect("seed properties serialize"),
+ set_once_properties: Vec::new(),
+ created_at: 0,
+ is_identified: false,
+ }
+ })
+ .collect();
+
+ for result in client.get_or_create_persons(entries).await? {
+ if let Some(error) = &result.error {
+ bail!(
+ "identity create failed for distinct id {}: {error}",
+ result.distinct_id
+ );
+ }
+ let person = result
+ .person
+ .with_context(|| format!("no person for distinct id {}", result.distinct_id))?;
+ if !result.created {
+ bail!(
+ "distinct id {} already existed — the harness team must start clean",
+ result.distinct_id
+ );
+ }
+ let seed_properties = HashMap::from([(
+ "harness_seed".to_string(),
+ serde_json::json!(result.distinct_id),
+ )]);
+ state
+ .record_write(person.id, person.version, seed_properties)
+ .await;
+ person_ids.push(person.id);
+ }
+ start = end;
+ }
+ Ok(person_ids)
+}
+
#[cfg(test)]
mod tests {
use clap::Parser;
diff --git a/rust/personhog-test-harness/src/seed.rs b/rust/personhog-test-harness/src/seed.rs
index a4eab6fcc7ea..4f2651ad85ea 100644
--- a/rust/personhog-test-harness/src/seed.rs
+++ b/rust/personhog-test-harness/src/seed.rs
@@ -14,9 +14,9 @@ use sqlx::postgres::PgPool;
/// on rows, so the first insert brings the harness team into existence and
/// a team-wide delete removes every trace of it.
///
-/// This writes SQL instead of calling CreatePerson because the create RPC's
-/// future is still being settled; this function is the seam where the RPC
-/// swaps in.
+/// This SQL path is the default; the gate's --create-via-identity flag
+/// swaps in the personhog-identity GetOrCreatePersonsByDistinctIds RPC
+/// instead.
pub async fn seed_persons(
pool: &PgPool,
table: &str,
@@ -46,14 +46,25 @@ pub async fn seed_persons(
Ok(ids)
}
-/// Delete all of `team_id`'s rows from `table`. The harness owns its team
-/// ids outright, so a team-wide delete is the whole cleanup. Nothing
-/// writes distinct-id rows today (traffic is id-keyed), so nothing cleans
-/// them — that changes together when seeding grows a mechanism that
-/// writes them.
+/// Delete all of `team_id`'s rows from `table`, plus the distinct id and
+/// personless rows the identity-service create path writes. The harness
+/// owns its team ids outright, so team-wide deletes are the whole cleanup.
+/// Distinct id rows go first: their FK references the person rows.
pub async fn cleanup_team(pool: &PgPool, table: &str, team_id: i64) -> Result<u64> {
validate_table_name(table)?;
let team: i32 = team_id.try_into().context("team_id out of i32 range")?;
+
+ sqlx::query("DELETE FROM posthog_persondistinctid WHERE team_id = $1")
+ .bind(team)
+ .execute(pool)
+ .await
+ .context("deleting distinct ids")?;
+ sqlx::query("DELETE FROM posthog_personlessdistinctid WHERE team_id = $1")
+ .bind(team)
+ .execute(pool)
+ .await
+ .context("deleting personless distinct ids")?;
+
let deleted = sqlx::query(&format!("DELETE FROM {table} WHERE team_id = $1"))
.bind(team)
.execute(pool)
diff --git a/rust/personhog-test-harness/src/stack/mod.rs b/rust/personhog-test-harness/src/stack/mod.rs
index 911b943e9c74..28f43f6192a0 100644
--- a/rust/personhog-test-harness/src/stack/mod.rs
+++ b/rust/personhog-test-harness/src/stack/mod.rs
@@ -25,9 +25,11 @@ use process::ServiceProcess;
/// during bring-up, every service opens outbound sockets in the same
/// instant the listeners bind.
const REPLICA_GRPC_PORT: u16 = 24051;
+const IDENTITY_GRPC_PORT: u16 = 24052;
const ROUTER_GRPC_BASE_PORT: u16 = 24054;
const LEADER_GRPC_BASE_PORT: u16 = 24060;
const REPLICA_METRICS_PORT: u16 = 24151;
+const IDENTITY_METRICS_PORT: u16 = 24152;
const WRITER_METRICS_PORT: u16 = 24153;
const ROUTER_METRICS_BASE_PORT: u16 = 24154;
const LEADER_METRICS_BASE_PORT: u16 = 24160;
@@ -57,6 +59,10 @@ pub struct StackConfig {
/// etcd lease TTL for leaders, in seconds. Bounds how long a crashed
/// (unrevoked) leader stays the registered owner.
pub leader_lease_ttl: i64,
+ /// Also spawn the personhog-identity service, pointed at the traffic
+ /// router for its initial-properties writes. Only needed when the run
+ /// creates persons through the identity path.
+ pub spawn_identity: bool,
}
/// A locally-spawned personhog stack: replica, writer, N leaders, and M
@@ -81,6 +87,8 @@ pub struct Stack {
store: PersonhogStore,
topic: String,
pub router_url: String,
+ /// Set when the stack spawned a personhog-identity service.
+ pub identity_url: Option<String>,
pub log_dir: PathBuf,
}
@@ -96,18 +104,21 @@ impl Stack {
fs::create_dir_all(&log_dir)
.with_context(|| format!("creating log dir {}", log_dir.display()))?;
- let binaries = [
+ let mut binaries = vec![
"personhog-replica",
"personhog-router",
"personhog-leader",
"personhog-writer",
];
- for bin in binaries {
+ if config.spawn_identity {
+ binaries.push("personhog-identity");
+ }
+ for bin in &binaries {
let path = config.bin_dir.join(bin);
if !path.exists() {
bail!(
"{} not found — build the stack first:\n cargo build -p personhog-replica \
- -p personhog-router -p personhog-leader -p personhog-writer",
+ -p personhog-router -p personhog-leader -p personhog-writer -p personhog-identity",
path.display()
);
}
@@ -205,6 +216,26 @@ impl Stack {
let traffic_router_port = ROUTER_GRPC_BASE_PORT + (config.routers - 1) as u16;
let router_url = format!("http://127.0.0.1:{traffic_router_port}");
+ // Identity resolves and creates on the Postgres primary and pushes
+ // initial properties through the traffic router; it holds no etcd
+ // state, so it can come up alongside the routers.
+ let identity_url = if config.spawn_identity {
+ infra.push(ServiceProcess::spawn(
+ "identity",
+ &config.bin_dir.join("personhog-identity"),
+ &[
+ ("GRPC_ADDRESS", format!("127.0.0.1:{IDENTITY_GRPC_PORT}")),
+ ("PRIMARY_DATABASE_URL", config.persons_db_url.clone()),
+ ("ROUTER_URL", router_url.clone()),
+ ("METRICS_PORT", IDENTITY_METRICS_PORT.to_string()),
+ ],
+ &log_dir,
+ )?);
+ Some(format!("http://127.0.0.1:{IDENTITY_GRPC_PORT}"))
+ } else {
+ None
+ };
+
let mut stack = Self {
config,
infra,
@@ -216,6 +247,7 @@ impl Stack {
store,
topic,
router_url,
+ identity_url,
log_dir,
};
@@ -627,6 +659,13 @@ impl Stack {
let addr = format!("127.0.0.1:{}", ROUTER_GRPC_BASE_PORT + i as u16);
wait_tcp(&addr, Duration::from_secs(10)).await?;
}
+ if self.identity_url.is_some() {
+ wait_tcp(
+ &format!("127.0.0.1:{IDENTITY_GRPC_PORT}"),
+ Duration::from_secs(10),
+ )
+ .await?;
+ }
tracing::info!(
router = %self.router_url,
elapsed_ms = start.elapsed().as_millis() as u64,