:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(personhog): MergePersons RPC on the lifecycle service (#79228)
Nick Best1c9bfb95bed4
diff --git a/nodejs/src/common/generated/personhog/personhog/identity/v1/identity_pb.ts b/nodejs/src/common/generated/personhog/personhog/identity/v1/identity_pb.tsindex 8bc3f851c288..4171021233cb 100644--- a/nodejs/src/common/generated/personhog/personhog/identity/v1/identity_pb.ts+++ b/nodejs/src/common/generated/personhog/personhog/identity/v1/identity_pb.ts@@ -1,8 +1,8 @@// @generated by protoc-gen-es v2.11.0 with parameter "target=ts"// @generated from file personhog/identity/v1/identity.proto (package personhog.identity.v1, syntax proto3)import type { Message } from '@bufbuild/protobuf'-import type { GenFile, GenMessage, GenService } from '@bufbuild/protobuf/codegenv2'-import { fileDesc, messageDesc, serviceDesc } from '@bufbuild/protobuf/codegenv2'+import type { GenEnum, GenFile, GenMessage, GenService } from '@bufbuild/protobuf/codegenv2'+import { enumDesc, fileDesc, messageDesc, serviceDesc } from '@bufbuild/protobuf/codegenv2'import type { Person, PersonDistinctIds } from '../../types/v1/person_pb'import { file_personhog_types_v1_person } from '../../types/v1/person_pb'@@ -13,7 +13,7 @@ import { file_personhog_types_v1_person } from '../../types/v1/person_pb'export const file_personhog_identity_v1_identity: GenFile =/*@__PURE__*/fileDesc(- 'CiRwZXJzb25ob2cvaWRlbnRpdHkvdjEvaWRlbnRpdHkucHJvdG8SFXBlcnNvbmhvZy5pZGVudGl0eS52MSLOAQoWR2V0T3JDcmVhdGVQZXJzb25FbnRyeRIPCgd0ZWFtX2lkGAEgASgDEhMKC2Rpc3RpbmN0X2lkGAIgASgJEhoKEmV4dHJhX2Rpc3RpbmN0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yc29ucxI2LnBlcnNvbmhvZy5pZGVudGl0eS52MS5HZXREaXN0aW5jdElkc0ZvclBlcnNvbnNSZXF1ZXN0GjcucGVyc29uaG9nLmlkZW50aXR5LnYxLkdldERpc3RpbmN0SWRzRm9yUGVyc29uc1Jlc3BvbnNlEmcKDE1lcmdlUGVyc29ucxIqLnBlcnNvbmhvZy5pZGVudGl0eS52MS5NZXJnZVBlcnNvbnNSZXF1ZXN0GisucGVyc29uaG9nLmlkZW50aXR5LnYxLk1lcmdlUGVyc29uc1Jlc3BvbnNlYgZwcm90bzM',[file_personhog_types_v1_person])@@ -385,10 +385,255 @@ export const GetDistinctIdsForPersonsResponseSchema: GenMessage<GetDistinctIdsFomessageDesc(file_personhog_identity_v1_identity, 11)/**- * 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.+ * One source pair of a MergePersons call.+ *+ * @generated from message personhog.identity.v1.MergeSource+ */+export type MergeSource = Message<'personhog.identity.v1.MergeSource'> & {+ /**+ * @generated from field: string source_distinct_id = 1;+ */+ sourceDistinctId: string++ /**+ * The $identify event that contributed this pair. Carried for warning+ * correlation on the caller's side; the merge itself never reads it.+ *+ * @generated from field: string event_uuid = 2;+ */+ eventUuid: string+}++/**+ * Describes the message personhog.identity.v1.MergeSource.+ * Use `create(MergeSourceSchema)` to create a new message.+ */+export const MergeSourceSchema: GenMessage<MergeSource> =+ /*@__PURE__*/+ messageDesc(file_personhog_identity_v1_identity, 12)++/**+ * MergePersonsRequest merges every source distinct id's person into the+ * target distinct id's person. Sources are ordered and deduped by the+ * caller; order defines property precedence (earlier pairs beat later+ * pairs, the target beats all).+ *+ * @generated from message personhog.identity.v1.MergePersonsRequest+ */+export type MergePersonsRequest = Message<'personhog.identity.v1.MergePersonsRequest'> & {+ /**+ * @generated from field: int64 team_id = 1;+ */+ teamId: bigint++ /**+ * @generated from field: string target_distinct_id = 2;+ */+ targetDistinctId: string++ /**+ * Max 250 sources per request. Duplicate source distinct ids are+ * rejected; a source equal to the target classifies as a no-op, not an+ * error.+ *+ * @generated from field: repeated personhog.identity.v1.MergeSource sources = 3;+ */+ sources: MergeSource[]++ /**+ * JSON-encoded maps from the merge event: $set overrides on conflict,+ * $set_once fills only still-absent keys. Applied to the survivor.+ *+ * @generated from field: bytes event_set = 4;+ */+ eventSet: Uint8Array++ /**+ * @generated from field: bytes event_set_once = 5;+ */+ eventSetOnce: Uint8Array++ /**+ * Caller-generated operation id (UUID string), typically the executing+ * event's uuid. A retried call carrying the same op_id returns the+ * recorded outcome of the original run instead of merging again, so+ * callers must reuse the op_id across retries.+ *+ * @generated from field: string op_id = 6;+ */+ opId: string++ /**+ * $merge_dangerously legally merges already-identified sources;+ * $identify does not. Off by default.+ *+ * @generated from field: bool allow_identified_sources = 7;+ */+ allowIdentifiedSources: boolean++ /**+ * Per-source distinct-id count guard: a source person with more distinct+ * ids than this is skipped (SKIPPED_MOVE_LIMIT) for the caller's+ * merge-mode policy to handle. Required, at least 1; unlimited is not a+ * supported mode.+ *+ * @generated from field: optional int64 move_limit = 8;+ */+ moveLimit?: bigint+}++/**+ * Describes the message personhog.identity.v1.MergePersonsRequest.+ * Use `create(MergePersonsRequestSchema)` to create a new message.+ */+export const MergePersonsRequestSchema: GenMessage<MergePersonsRequest> =+ /*@__PURE__*/+ messageDesc(file_personhog_identity_v1_identity, 13)++/**+ * @generated from message personhog.identity.v1.MergeSourceResult+ */+export type MergeSourceResult = Message<'personhog.identity.v1.MergeSourceResult'> & {+ /**+ * @generated from field: string source_distinct_id = 1;+ */+ sourceDistinctId: string++ /**+ * @generated from field: personhog.identity.v1.MergeSourceOutcome outcome = 2;+ */+ outcome: MergeSourceOutcome+}++/**+ * Describes the message personhog.identity.v1.MergeSourceResult.+ * Use `create(MergeSourceResultSchema)` to create a new message.+ */+export const MergeSourceResultSchema: GenMessage<MergeSourceResult> =+ /*@__PURE__*/+ messageDesc(file_personhog_identity_v1_identity, 14)++/**+ * @generated from message personhog.identity.v1.MergePersonsResponse+ */+export type MergePersonsResponse = Message<'personhog.identity.v1.MergePersonsResponse'> & {+ /**+ * Echo of the request op_id.+ *+ * @generated from field: string op_id = 1;+ */+ opId: string++ /**+ * The surviving person's document. Authoritative (the folded document+ * the leader produced) when a merge ran; the resolved person otherwise.+ * Absent when the operation aborted without merging anything.+ *+ * @generated from field: optional personhog.types.v1.Person survivor = 2;+ */+ survivor?: Person++ /**+ * One result per requested source, same order as the request.+ *+ * @generated from field: repeated personhog.identity.v1.MergeSourceResult results = 3;+ */+ results: MergeSourceResult[]+}++/**+ * Describes the message personhog.identity.v1.MergePersonsResponse.+ * Use `create(MergePersonsResponseSchema)` to create a new message.+ */+export const MergePersonsResponseSchema: GenMessage<MergePersonsResponse> =+ /*@__PURE__*/+ messageDesc(file_personhog_identity_v1_identity, 15)++/**+ * @generated from enum personhog.identity.v1.MergeSourceOutcome+ */+export enum MergeSourceOutcome {+ /**+ * @generated from enum value: MERGE_SOURCE_OUTCOME_UNSPECIFIED = 0;+ */+ UNSPECIFIED = 0,++ /**+ * The source person was merged into the survivor and destroyed.+ *+ * @generated from enum value: MERGE_SOURCE_OUTCOME_MERGED = 1;+ */+ MERGED = 1,++ /**+ * The source distinct id already resolves to the survivor. Nothing to do.+ *+ * @generated from enum value: MERGE_SOURCE_OUTCOME_NOOP_SAME_PERSON = 2;+ */+ NOOP_SAME_PERSON = 2,++ /**+ * The source distinct id had no person, so it was attached to the+ * survivor with a plain mapping insert. Reserved for the personless-free+ * world; nothing returns it yet (unresolved sources are ERROR for now).+ *+ * @generated from enum value: MERGE_SOURCE_OUTCOME_ATTACHED = 3;+ */+ ATTACHED = 3,++ /**+ * The source distinct id is on the illegal-id list ('anonymous',+ * 'undefined', ...). Never merged.+ *+ * @generated from enum value: MERGE_SOURCE_OUTCOME_SKIPPED_ILLEGAL = 4;+ */+ SKIPPED_ILLEGAL = 4,++ /**+ * The source person is already identified and the request did not set+ * allow_identified_sources.+ *+ * @generated from enum value: MERGE_SOURCE_OUTCOME_SKIPPED_ALREADY_IDENTIFIED = 5;+ */+ SKIPPED_ALREADY_IDENTIFIED = 5,++ /**+ * Another live lifecycle operation holds this person (or the source+ * resolved differently between classification and claim). Retryable.+ *+ * @generated from enum value: MERGE_SOURCE_OUTCOME_SKIPPED_CONFLICT = 6;+ */+ SKIPPED_CONFLICT = 6,++ /**+ * The source person has more distinct ids than the request's move_limit.+ *+ * @generated from enum value: MERGE_SOURCE_OUTCOME_SKIPPED_MOVE_LIMIT = 7;+ */+ SKIPPED_MOVE_LIMIT = 7,++ /**+ * The pair could not be handled; details in server logs. Currently also+ * the outcome for sources that resolve to no person (unresolved-source+ * attach is not implemented yet).+ *+ * @generated from enum value: MERGE_SOURCE_OUTCOME_ERROR = 8;+ */+ ERROR = 8,+}++/**+ * Describes the enum personhog.identity.v1.MergeSourceOutcome.+ */+export const MergeSourceOutcomeSchema: GenEnum<MergeSourceOutcome> =+ /*@__PURE__*/+ enumDesc(file_personhog_identity_v1_identity, 0)++/**+ * PersonHogIdentity owns the identity graph: distinct id resolution,+ * get-or-create orchestration, and merge 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@@ -398,6 +643,11 @@ export const GetDistinctIdsForPersonsResponseSchema: GenMessage<GetDistinctIdsFo* UpdatePersonProperties path — the event remains the durable source of the* initial properties.*+ * MergePersons semantics: the RPC drives the merge to completion before+ * responding. Most merges settle inline (same-person, illegal source); only+ * distinct-person pairs run the durable lifecycle saga. Retries with the same+ * op_id return the recorded outcome.+ ** @generated from service personhog.identity.v1.PersonHogIdentity*/export const PersonHogIdentity: GenService<{@@ -441,4 +691,20 @@ export const PersonHogIdentity: GenService<{input: typeof GetDistinctIdsForPersonsRequestSchemaoutput: typeof GetDistinctIdsForPersonsResponseSchema}+ /**+ * Merge source persons into the target distinct id's person. The+ * service resolves and classifies every pair: same-person pairs settle+ * inline, distinct-person pairs run the durable merge saga (fence the+ * sources, fold their sealed documents into the target, repoint distinct+ * ids, tombstone the sources, produce death documents). An unresolved+ * TARGET refuses the call FAILED_PRECONDITION; an illegal target+ * distinct id refuses it INVALID_ARGUMENT before any durable work.+ *+ * @generated from rpc personhog.identity.v1.PersonHogIdentity.MergePersons+ */+ mergePersons: {+ methodKind: 'unary'+ input: typeof MergePersonsRequestSchema+ output: typeof MergePersonsResponseSchema+ }}> = /*@__PURE__*/ serviceDesc(file_personhog_identity_v1_identity, 0)diff --git a/nodejs/src/common/generated/personhog/personhog/lifecycle/v1/lifecycle_pb.ts b/nodejs/src/common/generated/personhog/personhog/lifecycle/v1/lifecycle_pb.tsindex 61fbebabd330..7614335b6f53 100644--- a/nodejs/src/common/generated/personhog/personhog/lifecycle/v1/lifecycle_pb.ts+++ b/nodejs/src/common/generated/personhog/personhog/lifecycle/v1/lifecycle_pb.ts@@ -143,9 +143,9 @@ export const DeletePersonOutcomeSchema: GenEnum<DeletePersonOutcome> =enumDesc(file_personhog_lifecycle_v1_lifecycle, 0)/**- * PersonHogLifecycle runs person-destroying operations (delete now, merge- * case 3 later) as durable sagas: all saga state lives in the lifecycle_op- * tables on the persons primary, the service itself stays stateless.+ * PersonHogLifecycle runs person-destroying operations as durable sagas:+ * all saga state lives in the lifecycle_op tables on the persons primary,+ * the service itself stays stateless.** Ack semantics: the RPC drives the saga to Completed before responding —* an OK response means the operation's sync-plane work is committed and thediff --git a/proto/personhog/identity/v1/identity.proto b/proto/personhog/identity/v1/identity.protoindex 53c3b5b093d8..4e8d5d48c456 100644--- a/proto/personhog/identity/v1/identity.proto+++ b/proto/personhog/identity/v1/identity.proto@@ -111,10 +111,91 @@ message GetDistinctIdsForPersonsResponse {repeated personhog.types.v1.PersonDistinctIds person_distinct_ids = 1;}-// PersonHogIdentity owns the identity graph: distinct id resolution and-// get-or-create orchestration across the sync plane (Postgres primary) and-// the async plane (leader-owned properties). Ingestion calls this service-// directly; it is not fronted by the router.+// One source pair of a MergePersons call.+message MergeSource {+ string source_distinct_id = 1;+ // The $identify event that contributed this pair. Carried for warning+ // correlation on the caller's side; the merge itself never reads it.+ string event_uuid = 2;+}++// MergePersonsRequest merges every source distinct id's person into the+// target distinct id's person. Sources are ordered and deduped by the+// caller; order defines property precedence (earlier pairs beat later+// pairs, the target beats all).+message MergePersonsRequest {+ int64 team_id = 1;+ string target_distinct_id = 2;+ // Max 250 sources per request. Duplicate source distinct ids are+ // rejected; a source equal to the target classifies as a no-op, not an+ // error.+ repeated MergeSource sources = 3;+ // JSON-encoded maps from the merge event: $set overrides on conflict,+ // $set_once fills only still-absent keys. Applied to the survivor.+ bytes event_set = 4;+ bytes event_set_once = 5;+ // Caller-generated operation id (UUID string), typically the executing+ // event's uuid. A retried call carrying the same op_id returns the+ // recorded outcome of the original run instead of merging again, so+ // callers must reuse the op_id across retries.+ string op_id = 6;+ // $merge_dangerously legally merges already-identified sources;+ // $identify does not. Off by default.+ bool allow_identified_sources = 7;+ // Per-source distinct-id count guard: a source person with more distinct+ // ids than this is skipped (SKIPPED_MOVE_LIMIT) for the caller's+ // merge-mode policy to handle. Required, at least 1; unlimited is not a+ // supported mode.+ optional int64 move_limit = 8;+}++enum MergeSourceOutcome {+ MERGE_SOURCE_OUTCOME_UNSPECIFIED = 0;+ // The source person was merged into the survivor and destroyed.+ MERGE_SOURCE_OUTCOME_MERGED = 1;+ // The source distinct id already resolves to the survivor. Nothing to do.+ MERGE_SOURCE_OUTCOME_NOOP_SAME_PERSON = 2;+ // The source distinct id had no person, so it was attached to the+ // survivor with a plain mapping insert. Reserved for the personless-free+ // world; nothing returns it yet (unresolved sources are ERROR for now).+ MERGE_SOURCE_OUTCOME_ATTACHED = 3;+ // The source distinct id is on the illegal-id list ('anonymous',+ // 'undefined', ...). Never merged.+ MERGE_SOURCE_OUTCOME_SKIPPED_ILLEGAL = 4;+ // The source person is already identified and the request did not set+ // allow_identified_sources.+ MERGE_SOURCE_OUTCOME_SKIPPED_ALREADY_IDENTIFIED = 5;+ // Another live lifecycle operation holds this person (or the source+ // resolved differently between classification and claim). Retryable.+ MERGE_SOURCE_OUTCOME_SKIPPED_CONFLICT = 6;+ // The source person has more distinct ids than the request's move_limit.+ MERGE_SOURCE_OUTCOME_SKIPPED_MOVE_LIMIT = 7;+ // The pair could not be handled; details in server logs. Currently also+ // the outcome for sources that resolve to no person (unresolved-source+ // attach is not implemented yet).+ MERGE_SOURCE_OUTCOME_ERROR = 8;+}++message MergeSourceResult {+ string source_distinct_id = 1;+ MergeSourceOutcome outcome = 2;+}++message MergePersonsResponse {+ // Echo of the request op_id.+ string op_id = 1;+ // The surviving person's document. Authoritative (the folded document+ // the leader produced) when a merge ran; the resolved person otherwise.+ // Absent when the operation aborted without merging anything.+ optional personhog.types.v1.Person survivor = 2;+ // One result per requested source, same order as the request.+ repeated MergeSourceResult results = 3;+}++// PersonHogIdentity owns the identity graph: distinct id resolution,+// get-or-create orchestration, and merge 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@@ -123,6 +204,11 @@ message GetDistinctIdsForPersonsResponse {// (created = false) and the caller applies properties through the normal// UpdatePersonProperties path — the event remains the durable source of the// initial properties.+//+// MergePersons semantics: the RPC drives the merge to completion before+// responding. Most merges settle inline (same-person, illegal source); only+// distinct-person pairs run the durable lifecycle saga. Retries with the same+// op_id return the recorded outcome.service PersonHogIdentity {rpc GetOrCreatePersonByDistinctId(GetOrCreatePersonByDistinctIdRequest) returns (GetOrCreatePersonByDistinctIdResponse);rpc GetOrCreatePersonsByDistinctIds(GetOrCreatePersonsByDistinctIdsRequest) returns (GetOrCreatePersonsByDistinctIdsResponse);@@ -134,4 +220,12 @@ service PersonHogIdentity {// Person-id to distinct-ids expansion on the primary; the strong twin// of the router RPC of the same name (which reads the replica).rpc GetDistinctIdsForPersons(GetDistinctIdsForPersonsRequest) returns (GetDistinctIdsForPersonsResponse);+ // Merge source persons into the target distinct id's person. The+ // service resolves and classifies every pair: same-person pairs settle+ // inline, distinct-person pairs run the durable merge saga (fence the+ // sources, fold their sealed documents into the target, repoint distinct+ // ids, tombstone the sources, produce death documents). An unresolved+ // TARGET refuses the call FAILED_PRECONDITION; an illegal target+ // distinct id refuses it INVALID_ARGUMENT before any durable work.+ rpc MergePersons(MergePersonsRequest) returns (MergePersonsResponse);}diff --git a/proto/personhog/lifecycle/v1/lifecycle.proto b/proto/personhog/lifecycle/v1/lifecycle.protoindex e9aa73cabd9c..7c5fca2863f8 100644--- a/proto/personhog/lifecycle/v1/lifecycle.proto+++ b/proto/personhog/lifecycle/v1/lifecycle.proto@@ -39,9 +39,9 @@ message DeletePersonsResponse {repeated DeletePersonResult results = 2;}-// PersonHogLifecycle runs person-destroying operations (delete now, merge-// case 3 later) as durable sagas: all saga state lives in the lifecycle_op-// tables on the persons primary, the service itself stays stateless.+// PersonHogLifecycle runs person-destroying operations as durable sagas:+// all saga state lives in the lifecycle_op tables on the persons primary,+// the service itself stays stateless.//// Ack semantics: the RPC drives the saga to Completed before responding —// an OK response means the operation's sync-plane work is committed and thediff --git a/rust/personhog-identity/README.md b/rust/personhog-identity/README.mdindex 5577952f438d..af56159b2fd5 100644--- a/rust/personhog-identity/README.md+++ b/rust/personhog-identity/README.md@@ -7,7 +7,7 @@ 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.+`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 (two-person merges, deletes) belong to the lifecycle manager.## How get-or-create worksdiff --git a/rust/personhog-identity/src/lifecycle/merge.rs b/rust/personhog-identity/src/lifecycle/merge.rsindex 4e434754aabe..87073208b906 100644--- a/rust/personhog-identity/src/lifecycle/merge.rs+++ b/rust/personhog-identity/src/lifecycle/merge.rs@@ -15,9 +15,9 @@//! CAS, so every leader call is convergent under repetition: a re-run//! step re-issues the call and lands in the same state.//!-//! The driver receives the classified case-3 set of a MergePersons call:-//! source distinct ids that resolved to persons distinct from the-//! target. That classification is advisory. The claim step re-resolves+//! The driver receives a MergePersons call's classified two-person set:+//! source distinct ids that resolved to a live person distinct from the+//! target's. That classification is advisory. The claim step re-resolves//! everything authoritatively inside its own transaction, because the//! world can change between the handler and the saga.//!@@ -50,7 +50,7 @@ use personhog_proto::personhog::types::v1::{use crate::config::IdentityTables;use crate::leader::LifecycleLeader;use crate::lifecycle::engine::{- advance_step_in_tx, complete_op_in_tx, OpDriver, OpRow, SagaError, Tx, STEP_ABORTED,+ advance_step_in_tx, complete_op_in_tx, Engine, OpDriver, OpRow, SagaError, Tx, STEP_ABORTED,STEP_COMPLETED,};@@ -91,8 +91,9 @@ impl MergeStep {}}-/// The frozen `lifecycle_op.request` payload for a merge op: the case-3-/// set the handler classified, plus the merge event's property payloads.+/// The frozen `lifecycle_op.request` payload for a merge op: the+/// two-person set the handler classified, plus the merge event's+/// property payloads./// `sources` order is property precedence (earlier beats later).#[derive(Debug, Clone, Serialize, Deserialize)]pub struct MergeRequest {@@ -248,6 +249,64 @@ impl MergeDriver {}}+/// Everything the merge entrance may do with merge op rows: probe for an+/// existing op (the attach-first path) and drive a frozen request to its+/// terminal row. Identity work — resolution, classification, inline+/// settlement — lives in [`crate::service::merge`]; this seam keeps the+/// lifecycle side blind to it, and is where a future service split would+/// put the wire.+pub struct MergeOpExecutor {+ engine: Arc<Engine>,+ driver: MergeDriver,+}++impl MergeOpExecutor {+ pub fn new(engine: Arc<Engine>, driver: MergeDriver) -> Self {+ Self { engine, driver }+ }++ /// The op row for this id, if one exists.+ // tonic Status is a large Err variant; boxing would diverge from the+ // handler signatures this feeds into.+ #[allow(clippy::result_large_err)]+ pub async fn find(&self, op_id: Uuid) -> Result<Option<OpRow>, Status> {+ sqlx::query_as!(+ OpRow,+ r#"+ SELECT op_id, op_type, team_id::bigint as "team_id!", step, attempt,+ request as "request: Value", outcome as "outcome: Value", completed_at+ FROM lifecycle_op+ WHERE op_id = $1+ "#,+ op_id+ )+ .fetch_optional(self.engine.pool())+ .await+ .map_err(|e| Status::internal(format!("database error: {e}")))+ }++ /// Drive the op to terminal with the given frozen request (a resumed+ /// row's own request, or a freshly frozen one) and return the row.+ // See `find` for why result_large_err is allowed.+ #[allow(clippy::result_large_err)]+ pub async fn execute(+ &self,+ op_id: Uuid,+ team_id: i64,+ frozen: &Value,+ ) -> Result<OpRow, Status> {+ self.engine+ .execute(&self.driver, op_id, team_id, frozen)+ .await+ .map_err(|err| {+ if matches!(err, SagaError::Db(_) | SagaError::CorruptState(_)) {+ tracing::error!(op_id = %op_id, error = %err, "MergePersons failed");+ }+ Status::from(err)+ })+ }+}+#[async_trait]impl OpDriver for MergeDriver {fn op_type(&self) -> &'static str {diff --git a/rust/personhog-identity/src/lifecycle/mod.rs b/rust/personhog-identity/src/lifecycle/mod.rsindex 0c86c36fa192..c6d2fa01ca35 100644--- a/rust/personhog-identity/src/lifecycle/mod.rs+++ b/rust/personhog-identity/src/lifecycle/mod.rs@@ -1,13 +1,11 @@-//! Lifecycle sagas: person-destroying operations (delete now, merge case 3-//! later) run as durable sagas with all state in the lifecycle_op tables on-//! the persons primary. Self-contained on purpose — no imports from the-//! get-or-create side; anything shared belongs in personhog-common.+//! Lifecycle sagas: person-destroying operations run as durable sagas with+//! all state in the lifecycle_op tables on the persons primary. The merge+//! saga's step handler lives in [`merge`]; the entrance that drives it+//! lives in [`crate::service::merge`].//!//! The [`engine`] carries everything op types share (op persistence, lease,-//! drive loop, sweeper, GC); [`delete`] carries the delete saga's step-//! handlers. The service here is dispatch-only: validate, hand the request-//! to the engine, and translate the recorded outcome back to the proto-//! contract.+//! drive loop, sweeper, GC); [`delete`] and [`merge`] carry their sagas'+//! step handlers.pub mod delete;pub mod engine;diff --git a/rust/personhog-identity/src/lifecycle/validation.rs b/rust/personhog-identity/src/lifecycle/validation.rsindex ff4839480d0f..af4642ee1b9b 100644--- a/rust/personhog-identity/src/lifecycle/validation.rs+++ b/rust/personhog-identity/src/lifecycle/validation.rs@@ -1,12 +1,65 @@+use std::collections::HashSet;+use std::sync::LazyLock;+use tonic::Status;use uuid::Uuid;+use personhog_proto::personhog::identity::v1::MergePersonsRequest;use personhog_proto::personhog::lifecycle::v1::DeletePersonsRequest;/// Maximum person ids per DeletePersons request. Matches the identity/// get-or-create batch cap; GDPR jobs chunk above this.pub const MAX_DELETE_BATCH_SIZE: usize = 250;+/// Maximum sources per MergePersons request — the same per-op cap.+pub const MAX_MERGE_BATCH_SIZE: usize = 250;++const MAX_DISTINCT_ID_LENGTH: usize = 400;++// Mirrors ingestion's isDistinctIdIllegal (nodejs/src/common/persons/+// person-utils.ts): generic ids that stem from a bug or mistake must never+// drive a merge. Some are illegal in any casing, others only exactly as+// cased ('NaN' but not 'nan'), and both sets also match wrapped in single+// or double quotes.+const BARE_CASE_INSENSITIVE_ILLEGAL_IDS: &[&str] = &[+ "anonymous",+ "guest",+ "distinctid",+ "distinct_id",+ "id",+ "not_authenticated",+ "email",+ "undefined",+ "true",+ "false",+];+const BARE_CASE_SENSITIVE_ILLEGAL_IDS: &[&str] = &[+ "[object Object]",+ "NaN",+ "None",+ "none",+ "null",+ "0",+ "undefined",+];++fn with_quoted(ids: &[&str]) -> HashSet<String> {+ ids.iter()+ .flat_map(|id| [id.to_string(), format!("'{id}'"), format!("\"{id}\"")])+ .collect()+}++static CASE_INSENSITIVE_ILLEGAL_IDS: LazyLock<HashSet<String>> =+ LazyLock::new(|| with_quoted(BARE_CASE_INSENSITIVE_ILLEGAL_IDS));+static CASE_SENSITIVE_ILLEGAL_IDS: LazyLock<HashSet<String>> =+ LazyLock::new(|| with_quoted(BARE_CASE_SENSITIVE_ILLEGAL_IDS));++pub fn is_distinct_id_illegal(id: &str) -> bool {+ id.trim().is_empty()+ || CASE_INSENSITIVE_ILLEGAL_IDS.contains(&id.to_lowercase())+ || CASE_SENSITIVE_ILLEGAL_IDS.contains(id)+}+// tonic Status is a large Err variant; boxing here would diverge from the// tonic handler signatures these feed into.#[allow(clippy::result_large_err)]@@ -37,3 +90,60 @@ pub fn validate_delete_persons(request: &DeletePersonsRequest) -> Result<Uuid, SUuid::parse_str(&request.op_id).map_err(|_| Status::invalid_argument("op_id must be a valid UUID"))}++// See validate_delete_persons for why result_large_err is allowed.+#[allow(clippy::result_large_err)]+/// Validates the request and returns the parsed op_id and move_limit.+/// Illegal SOURCE distinct ids are per-source outcomes, not request+/// errors — only the target's legality gates the whole call (nothing can+/// merge into a bug).+pub fn validate_merge_persons(request: &MergePersonsRequest) -> Result<(Uuid, i64), Status> {+ if request.team_id <= 0 || request.team_id > i32::MAX as i64 {+ return Err(Status::invalid_argument(+ "team_id must be a positive 32-bit integer",+ ));+ }+ if request.target_distinct_id.len() > MAX_DISTINCT_ID_LENGTH {+ return Err(Status::invalid_argument(format!(+ "target_distinct_id exceeds {MAX_DISTINCT_ID_LENGTH} characters"+ )));+ }+ if is_distinct_id_illegal(&request.target_distinct_id) {+ return Err(Status::invalid_argument(+ "target_distinct_id is an illegal distinct id",+ ));+ }+ if request.sources.is_empty() {+ return Err(Status::invalid_argument("sources must not be empty"));+ }+ if request.sources.len() > MAX_MERGE_BATCH_SIZE {+ return Err(Status::invalid_argument(format!(+ "batch size {} exceeds maximum {MAX_MERGE_BATCH_SIZE}",+ request.sources.len()+ )));+ }+ let mut seen = HashSet::with_capacity(request.sources.len());+ for source in &request.sources {+ if source.source_distinct_id.len() > MAX_DISTINCT_ID_LENGTH {+ return Err(Status::invalid_argument(format!(+ "a source distinct id exceeds {MAX_DISTINCT_ID_LENGTH} characters"+ )));+ }+ if !seen.insert(source.source_distinct_id.as_str()) {+ return Err(Status::invalid_argument(format!(+ "duplicate source distinct id: the caller must dedupe (\"{}\")",+ source.source_distinct_id+ )));+ }+ }+ // Unlimited is not a supported mode: the flip's repoint would be an+ // unbounded statement under statement_timeout.+ let move_limit = match request.move_limit {+ Some(limit) if limit >= 1 => limit,+ Some(_) => return Err(Status::invalid_argument("move_limit must be positive")),+ None => return Err(Status::invalid_argument("move_limit is required")),+ };+ let op_id = Uuid::parse_str(&request.op_id)+ .map_err(|_| Status::invalid_argument("op_id must be a valid UUID"))?;+ Ok((op_id, move_limit))+}diff --git a/rust/personhog-identity/src/main.rs b/rust/personhog-identity/src/main.rsindex 8eb8a7b66951..949bda34490b 100644--- a/rust/personhog-identity/src/main.rs+++ b/rust/personhog-identity/src/main.rs@@ -23,8 +23,9 @@ use personhog_identity::config::Config;use personhog_identity::leader::LifecycleLeader;use personhog_identity::lifecycle::delete::DeleteDriver;use personhog_identity::lifecycle::engine::Engine;-use personhog_identity::lifecycle::merge::MergeDriver;+use personhog_identity::lifecycle::merge::{MergeDriver, MergeOpExecutor};use personhog_identity::lifecycle::PersonHogLifecycleService;+use personhog_identity::service::merge::MergeEntrance;use personhog_identity::service::PersonHogIdentityService;use personhog_identity::storage::postgres::PostgresIdentityStorage;@@ -233,11 +234,24 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {});}- let service = PersonHogIdentityService::new(storage, property_writer, config.request_limits());// Separate proto service co-served on the same server so lifecycle// callers are insulated from any future split.+ let merge_entrance = MergeEntrance::new(+ storage.clone(),+ property_writer.clone(),+ MergeOpExecutor::new(+ engine.clone(),+ MergeDriver::new(property_writer.clone(), config.tables()),+ ),+ );let lifecycle_service =PersonHogLifecycleService::new(engine, lifecycle_leader, config.tables());+ let service = PersonHogIdentityService::new(+ storage,+ property_writer,+ config.request_limits(),+ merge_entrance,+ );let grpc_addr = config.grpc_address;let keepalive_interval = config.grpc_keepalive_interval();diff --git a/rust/personhog-identity/src/service/merge.rs b/rust/personhog-identity/src/service/merge.rsnew file mode 100644index 000000000000..70094d5daac4--- /dev/null+++ b/rust/personhog-identity/src/service/merge.rs@@ -0,0 +1,363 @@+//! The MergePersons entrance: request validation, identity resolution,+//! classification, inline settlement, and response assembly. This is+//! identity work — the pairs that never need a saga settle here — and the+//! lifecycle side stays blind to it: the entrance reaches the durable op+//! machinery only through [`MergeOpExecutor`], handing over a frozen+//! request and receiving a terminal op row.++use std::collections::HashMap;+use std::sync::Arc;++use serde_json::Value;+use tonic::Status;++use personhog_proto::personhog::identity::v1::{+ MergePersonsRequest, MergePersonsResponse, MergeSourceOutcome, MergeSourceResult,+};+use personhog_proto::personhog::types::v1::{Person as ProtoPerson, UpdatePersonPropertiesRequest};++use crate::leader::PropertyWriter;+use crate::lifecycle::engine::OpRow;+use crate::lifecycle::merge::{+ MergeOpExecutor, MergeOutcome, MergeRequest, MergeSourceEntry, OP_TYPE_MERGE, OUTCOME_ERROR,+ OUTCOME_MERGED, OUTCOME_NOOP_SAME_PERSON, OUTCOME_SKIPPED_ALREADY_IDENTIFIED,+ OUTCOME_SKIPPED_CONFLICT, OUTCOME_SKIPPED_MOVE_LIMIT,+};+use crate::lifecycle::validation::{is_distinct_id_illegal, validate_merge_persons};+use crate::storage::IdentityStorage;++/// The handler-decided outcome for a source that never reaches the saga.+const OUTCOME_SKIPPED_ILLEGAL: &str = "skipped_illegal";++/// The full MergePersons flow, owned by the identity side of the crate.+pub struct MergeEntrance {+ storage: Arc<dyn IdentityStorage>,+ property_writer: Arc<dyn PropertyWriter>,+ ops: MergeOpExecutor,+}++impl MergeEntrance {+ pub fn new(+ storage: Arc<dyn IdentityStorage>,+ property_writer: Arc<dyn PropertyWriter>,+ ops: MergeOpExecutor,+ ) -> Self {+ Self {+ storage,+ property_writer,+ ops,+ }+ }++ // tonic Status is a large Err variant; boxing would diverge from the+ // handler signatures this feeds into.+ #[allow(clippy::result_large_err)]+ pub async fn handle(+ &self,+ request: MergePersonsRequest,+ ) -> Result<MergePersonsResponse, Status> {+ let (op_id, move_limit) = validate_merge_persons(&request)?;+ let event_set = parse_json_map(&request.event_set, "event_set")?;+ let event_set_once = parse_json_map(&request.event_set_once, "event_set_once")?;+ let original = merge_original(&request, &event_set, &event_set_once);++ // Attach-first: classification below is time-dependent (a retry+ // after the merge committed would re-classify every merged pair as+ // a no-op and freeze a different request), so an existing op is+ // compared on the ORIGINAL call and driven with its own frozen+ // request — never re-classified. Two racing FIRST calls can still+ // classify divergently and the insert loser then sees the engine's+ // full-request mismatch; that surfaces as FAILED_PRECONDITION once+ // and self-heals — the next retry attaches here.+ if let Some(row) = self.ops.find(op_id).await? {+ if row.op_type != OP_TYPE_MERGE+ || row.team_id != request.team_id+ || row.request.get("original") != Some(&original)+ {+ return Err(Status::failed_precondition(format!(+ "op_id {op_id} was already used for a different request"+ )));+ }+ let frozen = row.request.clone();+ let row = self.ops.execute(op_id, row.team_id, &frozen).await?;+ return merge_response(&row);+ }++ // Classify: resolve everything once on the primary, settle what+ // never needs the saga, collect the two-person set (the only+ // destructive shape). The saga re-resolves+ // authoritatively at claim time; this pass only decides shape.+ let mut keys: Vec<(i64, String)> =+ vec![(request.team_id, request.target_distinct_id.clone())];+ keys.extend(+ request+ .sources+ .iter()+ .map(|s| (request.team_id, s.source_distinct_id.clone())),+ );+ let resolved = self+ .storage+ .resolve_distinct_ids(&keys)+ .await+ .map_err(|e| Status::internal(format!("resolution failed: {e}")))?;++ let target_key = (request.team_id, request.target_distinct_id.clone());+ let Some(target_person) = resolved.get(&target_key) else {+ // Unresolved-target merges (attach the target to a resolved+ // source's person, or birth a fresh target) are not+ // implemented yet; the caller keeps them on its own path.+ return Err(Status::failed_precondition(+ "target distinct id resolves to no person; \+ create it first (unresolved-target merges are not implemented)",+ ));+ };+ let target_person = target_person.clone();++ let mut inline_results: HashMap<String, String> = HashMap::new();+ let mut saga_sources: Vec<MergeSourceEntry> = Vec::new();+ for source in &request.sources {+ let did = &source.source_distinct_id;+ if is_distinct_id_illegal(did) {+ inline_results.insert(did.clone(), OUTCOME_SKIPPED_ILLEGAL.to_string());+ continue;+ }+ match resolved.get(&(request.team_id, did.clone())) {+ None => {+ // Unresolved-source attach is not implemented yet.+ inline_results.insert(did.clone(), OUTCOME_ERROR.to_string());+ }+ Some(person) if person.id == target_person.id => {+ inline_results.insert(did.clone(), OUTCOME_NOOP_SAME_PERSON.to_string());+ }+ Some(_) => saga_sources.push(MergeSourceEntry {+ distinct_id: did.clone(),+ event_uuid: source.event_uuid.clone(),+ }),+ }+ }++ if saga_sources.is_empty() {+ // Nothing to destroy, so no op row. Inline settlement is+ // idempotent: a retry re-executes against the current world,+ // the same at-least-once semantics as event redelivery — and+ // the only semantics available, since recorded outcomes are+ // GC'd after retention and a late replay re-classifies+ // regardless. The op row resumes interrupted destruction; it+ // is not a dedupe of idempotent work. The event's properties+ // still reach the survivor.+ let pushed = self+ .push_event_properties(&request, target_person.id)+ .await?;+ let results = request+ .sources+ .iter()+ .map(|s| MergeSourceResult {+ source_distinct_id: s.source_distinct_id.clone(),+ outcome: outcome_enum(+ inline_results+ .get(&s.source_distinct_id)+ .map(String::as_str)+ .unwrap_or(OUTCOME_ERROR),+ )+ .into(),+ })+ .collect();+ return Ok(MergePersonsResponse {+ op_id: op_id.to_string(),+ survivor: Some(pushed.unwrap_or_else(|| target_person.into())),+ results,+ });+ }++ // The saga: freeze the classified request (the driver's shape) plus+ // the original call (retry comparison) and the inline outcomes (so+ // a retried finished op reproduces the full per-did answer).+ let merge_request = MergeRequest {+ target_distinct_id: request.target_distinct_id.clone(),+ sources: saga_sources,+ event_set,+ event_set_once,+ allow_identified_sources: request.allow_identified_sources,+ move_limit,+ };+ let mut frozen = serde_json::to_value(&merge_request)+ .map_err(|e| Status::internal(format!("failed to freeze request: {e}")))?;+ frozen["original"] = original;+ frozen["inline_results"] = serde_json::to_value(&inline_results)+ .map_err(|e| Status::internal(format!("failed to freeze inline results: {e}")))?;++ let row = self.ops.execute(op_id, request.team_id, &frozen).await?;+ merge_response(&row)+ }++ /// Apply the merge event's $set/$set_once to the survivor when no saga+ /// runs (the fold carries them when one does). The ack means the+ /// properties are durable in the changelog.+ async fn push_event_properties(+ &self,+ request: &MergePersonsRequest,+ person_id: i64,+ ) -> Result<Option<ProtoPerson>, Status> {+ if request.event_set.is_empty() && request.event_set_once.is_empty() {+ return Ok(None);+ }+ let response = self+ .property_writer+ .update_person_properties(UpdatePersonPropertiesRequest {+ team_id: request.team_id,+ person_id,+ event_name: "$identify".to_string(),+ set_properties: request.event_set.clone(),+ set_once_properties: request.event_set_once.clone(),+ unset_properties: Vec::new(),+ is_identified: None,+ last_seen_at: None,+ })+ .await?;+ Ok(response.person)+ }+}++/// Decode a JSON-map wire field (empty bytes mean an empty map).+// See `MergeEntrance::handle` for why result_large_err is allowed.+#[allow(clippy::result_large_err)]+fn parse_json_map(bytes: &[u8], field: &str) -> Result<Value, Status> {+ if bytes.is_empty() {+ return Ok(Value::Object(serde_json::Map::new()));+ }+ let value: Value = serde_json::from_slice(bytes)+ .map_err(|e| Status::invalid_argument(format!("invalid {field} JSON: {e}")))?;+ if !value.is_object() {+ return Err(Status::invalid_argument(format!(+ "{field} must be a JSON object"+ )));+ }+ Ok(value)+}++/// The canonical form of a MergePersons call, embedded in the frozen op+/// request as `original`. Classification is time-dependent, so a retry must+/// be compared against what was originally ASKED, not what was classified —+/// this is what keeps a legitimate retry from tripping the engine's+/// request-equality guard after the merge already moved the world.+fn merge_original(+ request: &MergePersonsRequest,+ event_set: &Value,+ event_set_once: &Value,+) -> Value {+ serde_json::json!({+ "target_distinct_id": request.target_distinct_id,+ "sources": request+ .sources+ .iter()+ .map(|s| serde_json::json!({+ "distinct_id": s.source_distinct_id,+ "event_uuid": s.event_uuid,+ }))+ .collect::<Vec<_>>(),+ "event_set": event_set,+ "event_set_once": event_set_once,+ "allow_identified_sources": request.allow_identified_sources,+ "move_limit": request.move_limit,+ })+}++fn outcome_enum(outcome: &str) -> MergeSourceOutcome {+ match outcome {+ OUTCOME_MERGED => MergeSourceOutcome::Merged,+ OUTCOME_NOOP_SAME_PERSON => MergeSourceOutcome::NoopSamePerson,+ OUTCOME_SKIPPED_ILLEGAL => MergeSourceOutcome::SkippedIllegal,+ OUTCOME_SKIPPED_ALREADY_IDENTIFIED => MergeSourceOutcome::SkippedAlreadyIdentified,+ OUTCOME_SKIPPED_CONFLICT => MergeSourceOutcome::SkippedConflict,+ OUTCOME_SKIPPED_MOVE_LIMIT => MergeSourceOutcome::SkippedMoveLimit,+ OUTCOME_ERROR => MergeSourceOutcome::Error,+ _ => MergeSourceOutcome::Unspecified,+ }+}++/// The survivor document recorded by the saga, converted to the wire+/// person. The fold's `created_at` is already epoch millis — the leader+/// plane's wire unit — so it passes through unscaled.+fn survivor_to_proto(survivor: &Value, team_id: i64) -> ProtoPerson {+ ProtoPerson {+ id: survivor["id"].as_i64().unwrap_or_default(),+ uuid: survivor["uuid"].as_str().unwrap_or_default().to_string(),+ team_id,+ properties: serde_json::to_vec(&survivor["properties"]).unwrap_or_default(),+ created_at: survivor["created_at"].as_i64().unwrap_or_default(),+ version: survivor["version"].as_i64().unwrap_or_default(),+ is_identified: survivor["is_identified"].as_bool().unwrap_or(true),+ ..Default::default()+ }+}++/// Assemble the response for an op that ran the saga: inline outcomes from+/// the frozen request, saga outcomes from the recorded terminal outcome,+/// in the original request's source order.+// See `MergeEntrance::handle` for why result_large_err is allowed.+#[allow(clippy::result_large_err)]+fn merge_response(row: &OpRow) -> Result<MergePersonsResponse, Status> {+ let Some(outcome) = &row.outcome else {+ return Err(Status::internal(format!(+ "op {} is terminal but has no recorded outcome",+ row.op_id+ )));+ };+ let outcome: MergeOutcome = serde_json::from_value(outcome.clone())+ .map_err(|e| Status::internal(format!("op {} outcome is malformed: {e}", row.op_id)))?;+ let saga_results: HashMap<&str, &str> = outcome+ .results+ .iter()+ .map(|r| (r.distinct_id.as_str(), r.outcome.as_str()))+ .collect();+ let inline_results: HashMap<String, String> = row+ .request+ .get("inline_results")+ .cloned()+ .map(serde_json::from_value)+ .transpose()+ .map_err(|e| {+ Status::internal(format!(+ "op {} inline results are malformed: {e}",+ row.op_id+ ))+ })?+ .unwrap_or_default();+ let original_sources: Vec<String> = row+ .request+ .get("original")+ .and_then(|o| o.get("sources"))+ .and_then(|s| s.as_array())+ .map(|sources| {+ sources+ .iter()+ .filter_map(|s| s.get("distinct_id").and_then(|d| d.as_str()))+ .map(str::to_string)+ .collect()+ })+ .unwrap_or_default();++ let results = original_sources+ .iter()+ .map(|did| {+ let outcome = inline_results+ .get(did)+ .map(String::as_str)+ .or_else(|| saga_results.get(did.as_str()).copied())+ .unwrap_or(OUTCOME_ERROR);+ MergeSourceResult {+ source_distinct_id: did.clone(),+ outcome: outcome_enum(outcome).into(),+ }+ })+ .collect();++ Ok(MergePersonsResponse {+ op_id: row.op_id.to_string(),+ survivor: outcome+ .survivor+ .as_ref()+ .map(|s| survivor_to_proto(s, row.team_id)),+ results,+ })+}diff --git a/rust/personhog-identity/src/service/mod.rs b/rust/personhog-identity/src/service/mod.rsindex 4e3a647b176e..0981b0fca230 100644--- a/rust/personhog-identity/src/service/mod.rs+++ b/rust/personhog-identity/src/service/mod.rs@@ -1,9 +1,12 @@//! 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).+//! lives in its own submodule (get_or_create and the merge entrance today;+//! resolution, claims, and splits will follow the same pattern). [`merge`]+//! carries MergePersons' identity work — validation, resolution,+//! classification, inline settlement.pub mod error;pub mod get_or_create;+pub mod merge;pub mod validation;use std::sync::Arc;@@ -16,11 +19,13 @@ use personhog_proto::personhog::identity::v1::{GetOrCreatePersonByDistinctIdRequest, GetOrCreatePersonByDistinctIdResponse,GetOrCreatePersonResult, GetOrCreatePersonsByDistinctIdsRequest,GetOrCreatePersonsByDistinctIdsResponse, GetPersonByDistinctIdResult,- GetPersonsByDistinctIdsRequest, GetPersonsByDistinctIdsResponse,+ GetPersonsByDistinctIdsRequest, GetPersonsByDistinctIdsResponse, MergePersonsRequest,+ MergePersonsResponse,};use personhog_proto::personhog::types::v1::{DistinctIdWithVersion, PersonDistinctIds};use crate::leader::PropertyWriter;+use crate::service::merge::MergeEntrance;use crate::service::validation::{validate_batch_size, validate_entry, validate_team_id, RequestLimits,};@@ -30,6 +35,7 @@ pub struct PersonHogIdentityService {pub(crate) storage: Arc<dyn IdentityStorage>,pub(crate) property_writer: Arc<dyn PropertyWriter>,pub(crate) limits: RequestLimits,+ merge: MergeEntrance,}impl PersonHogIdentityService {@@ -37,11 +43,13 @@ impl PersonHogIdentityService {storage: Arc<dyn IdentityStorage>,property_writer: Arc<dyn PropertyWriter>,limits: RequestLimits,+ merge: MergeEntrance,) -> Self {Self {storage,property_writer,limits,+ merge,}}}@@ -190,4 +198,13 @@ impl PersonHogIdentity for PersonHogIdentityService {person_distinct_ids,}))}++ async fn merge_persons(+ &self,+ request: Request<MergePersonsRequest>,+ ) -> Result<Response<MergePersonsResponse>, Status> {+ Ok(Response::new(+ self.merge.handle(request.into_inner()).await?,+ ))+ }}diff --git a/rust/personhog-identity/tests/common/mod.rs b/rust/personhog-identity/tests/common/mod.rsindex 1dcb0acac97b..1ff940144fbe 100644--- a/rust/personhog-identity/tests/common/mod.rs+++ b/rust/personhog-identity/tests/common/mod.rs@@ -208,3 +208,79 @@ impl TestContext {Ok(())}}++/// Leader-surface stubs for test binaries whose flows never reach the+/// leader: an accidental call surfaces as a clean unimplemented error+/// instead of a hang or a panic mid-transaction.+pub struct UnusedLeader;++#[async_trait::async_trait]+impl personhog_identity::leader::PropertyWriter for UnusedLeader {+ async fn update_person_properties(+ &self,+ _request: personhog_proto::personhog::types::v1::UpdatePersonPropertiesRequest,+ ) -> Result<personhog_proto::personhog::types::v1::UpdatePersonPropertiesResponse, tonic::Status>+ {+ Err(tonic::Status::unimplemented("not exercised by this test"))+ }+}++#[async_trait::async_trait]+impl personhog_identity::leader::LifecycleLeader for UnusedLeader {+ async fn fence_person(+ &self,+ _request: personhog_proto::personhog::types::v1::FencePersonRequest,+ ) -> Result<personhog_proto::personhog::types::v1::FencePersonResponse, tonic::Status> {+ Err(tonic::Status::unimplemented("not exercised by this test"))+ }++ async fn release_fence(+ &self,+ _request: personhog_proto::personhog::types::v1::ReleaseFenceRequest,+ ) -> Result<personhog_proto::personhog::types::v1::ReleaseFenceResponse, tonic::Status> {+ Err(tonic::Status::unimplemented("not exercised by this test"))+ }++ async fn fold_person_document(+ &self,+ _request: personhog_proto::personhog::types::v1::FoldPersonDocumentRequest,+ ) -> Result<personhog_proto::personhog::types::v1::FoldPersonDocumentResponse, tonic::Status>+ {+ Err(tonic::Status::unimplemented("not exercised by this test"))+ }+}++/// IdentityStorage stub for validation-only test binaries: any call means+/// validation failed to reject first.+pub struct UnusedStorage;++#[async_trait::async_trait]+impl personhog_identity::storage::IdentityStorage for UnusedStorage {+ async fn resolve_distinct_ids(+ &self,+ _keys: &[(i64, String)],+ ) -> personhog_identity::storage::StorageResult<+ std::collections::HashMap<(i64, String), personhog_identity::storage::Person>,+ > {+ panic!("not exercised by this test")+ }++ async fn get_distinct_ids_for_persons(+ &self,+ _team_id: i64,+ _person_ids: &[i64],+ _limit_per_person: Option<i64>,+ ) -> personhog_identity::storage::StorageResult<+ Vec<personhog_identity::storage::DistinctIdMapping>,+ > {+ panic!("not exercised by this test")+ }++ async fn create_person_stubs(+ &self,+ _stubs: &[personhog_identity::storage::PersonStub],+ ) -> personhog_identity::storage::StorageResult<Vec<personhog_identity::storage::StubOutcome>>+ {+ panic!("not exercised by this test")+ }+}diff --git a/rust/personhog-identity/tests/common/sim_leader.rs b/rust/personhog-identity/tests/common/sim_leader.rsindex 1767a33ba183..8e1a10fc151a 100644--- a/rust/personhog-identity/tests/common/sim_leader.rs+++ b/rust/personhog-identity/tests/common/sim_leader.rs@@ -31,10 +31,11 @@ use tonic::Status;use uuid::Uuid;use personhog_common::grpc::semantic_refusal;-use personhog_identity::leader::LifecycleLeader;+use personhog_identity::leader::{LifecycleLeader, PropertyWriter};use personhog_proto::personhog::types::v1::{FencePersonRequest, FencePersonResponse, FoldPersonDocumentRequest, FoldPersonDocumentResponse,LifecycleOpType, Person, ReleaseFenceRequest, ReleaseFenceResponse, ReleaseOutcome,+ UpdatePersonPropertiesRequest, UpdatePersonPropertiesResponse,};/// Which RPC a scripted failure applies to.@@ -43,6 +44,7 @@ pub enum Rpc {Fence,Fold,Release,+ PropertyPush,}/// A person's live fence in the simulated leader.@@ -84,6 +86,9 @@ pub enum LeaderCall {ReleaseAborted {person_id: i64,},+ PropertyPush {+ person_id: i64,+ },}/// Metadata keys carried on fenced-write rejections; must stay in sync@@ -228,7 +233,7 @@ impl SimLeader {uuid: uuid.to_string(),team_id,properties: serde_json::to_vec(&properties).unwrap(),- created_at: created_at.timestamp(),+ created_at: created_at.timestamp_millis(),version,is_identified,last_seen_at: self.last_seen.lock().unwrap().get(&person_id).copied(),@@ -519,3 +524,36 @@ impl LifecycleLeader for SimLeader {})}}++/// The RPC's inline path pushes the merge event's properties through the+/// ordinary write surface; the sim applies the same admission rules as+/// any other write, so a push to a fenced or destroyed person fails the+/// test.+#[async_trait]+impl PropertyWriter for SimLeader {+ async fn update_person_properties(+ &self,+ request: UpdatePersonPropertiesRequest,+ ) -> Result<UpdatePersonPropertiesResponse, Status> {+ if let Some(status) = self.take_scripted(Rpc::PropertyPush, request.person_id) {+ return Err(status);+ }+ if let Some(fence) = self.fence_for(request.person_id) {+ return Err(fenced_status(&fence));+ }+ if self.deaths.lock().unwrap().contains_key(&request.person_id) {+ return Err(Status::not_found("person is destroyed"));+ }+ let person = self+ .live_person(request.team_id, request.person_id)+ .await+ .ok_or_else(|| Status::not_found("person is destroyed"))?;+ self.record(LeaderCall::PropertyPush {+ person_id: request.person_id,+ });+ Ok(UpdatePersonPropertiesResponse {+ person: Some(person),+ updated: true,+ })+ }+}diff --git a/rust/personhog-identity/tests/lifecycle_delete_tests.rs b/rust/personhog-identity/tests/lifecycle_delete_tests.rsindex b020533bc238..7a99f0826421 100644--- a/rust/personhog-identity/tests/lifecycle_delete_tests.rs+++ b/rust/personhog-identity/tests/lifecycle_delete_tests.rs@@ -21,14 +21,12 @@ use personhog_proto::personhog::lifecycle::v1::{DeletePersonOutcome, DeletePerso/// Storage-assertion helpers used only by this test binary.impl TestContext {fn lifecycle_service(&self) -> PersonHogLifecycleService {- PersonHogLifecycleService::new(- Arc::new(self.engine()),- Arc::new(SimLeader::new(- self.pool.clone(),- self.tables.person.clone(),- )),- self.tables.clone(),- )+ let engine = Arc::new(self.engine());+ let leader = Arc::new(SimLeader::new(+ self.pool.clone(),+ self.tables.person.clone(),+ ));+ PersonHogLifecycleService::new(engine, leader.clone(), self.tables.clone())}/// (is_deleted, version, properties) of a person row.diff --git a/rust/personhog-identity/tests/lifecycle_merge_tests.rs b/rust/personhog-identity/tests/lifecycle_merge_tests.rsindex 8a5f35329963..28edb1be624c 100644--- a/rust/personhog-identity/tests/lifecycle_merge_tests.rs+++ b/rust/personhog-identity/tests/lifecycle_merge_tests.rs@@ -1498,5 +1498,528 @@ async fn merge_works_on_a_configured_person_table() {.cleanup_real_namespace().await.expect("cleanup real namespace");+}++// ============================================================+// The MergePersons RPC: classification, inline settlement, and the+// attach-first retry contract+// ============================================================++use personhog_identity::lifecycle::merge::MergeOpExecutor;+use personhog_identity::service::merge::MergeEntrance;+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::{+ MergePersonsRequest, MergePersonsResponse, MergeSource, MergeSourceOutcome,+};+use tonic::Request;++impl MergeHarness {+ fn service(&self) -> PersonHogIdentityService {+ let engine = Arc::new(self.ctx.engine());+ PersonHogIdentityService::new(+ self.ctx.storage.clone(),+ self.leader.clone(),+ RequestLimits {+ max_batch_size: 250,+ max_distinct_id_length: 400,+ max_extra_distinct_ids: 10,+ },+ MergeEntrance::new(+ self.ctx.storage.clone(),+ self.leader.clone(),+ MergeOpExecutor::new(+ engine,+ MergeDriver::new(self.leader.clone(), self.ctx.tables.clone()),+ ),+ ),+ )+ }+}++fn rpc_request(team_id: i64, target: &str, sources: &[&str], op_id: Uuid) -> MergePersonsRequest {+ MergePersonsRequest {+ team_id,+ target_distinct_id: target.to_string(),+ sources: sources+ .iter()+ .map(|did| MergeSource {+ source_distinct_id: did.to_string(),+ event_uuid: Uuid::now_v7().to_string(),+ })+ .collect(),+ event_set: Vec::new(),+ event_set_once: Vec::new(),+ op_id: op_id.to_string(),+ allow_identified_sources: false,+ move_limit: Some(1_000),+ }+}++fn rpc_outcomes(response: &MergePersonsResponse) -> Vec<(String, MergeSourceOutcome)> {+ response+ .results+ .iter()+ .map(|r| (r.source_distinct_id.clone(), r.outcome()))+ .collect()+}++#[tokio::test]+async fn the_rpc_runs_the_saga_and_a_retry_returns_the_recorded_answer() {+ let h = MergeHarness::new().await;+ let service = h.service();+ let target = h.ctx.insert_person_with_distinct_id("rpc-target").await;+ let source = h.ctx.insert_person_with_distinct_id("rpc-source").await;+ h.set_person(source, r#"{"plan": "free"}"#, 4, false).await;++ let op_id = Uuid::now_v7();+ let request = rpc_request(h.ctx.team_id, "rpc-target", &["rpc-source"], op_id);+ let response = service+ .merge_persons(Request::new(request.clone()))+ .await+ .expect("merge succeeds")+ .into_inner();++ assert_eq!(+ rpc_outcomes(&response),+ vec![("rpc-source".to_string(), MergeSourceOutcome::Merged)]+ );+ let survivor = response.survivor.expect("survivor present");+ assert_eq!(survivor.id, target);+ assert!(survivor.is_identified);+ let calls_after_first = h.leader.calls().len();++ // The retry arrives AFTER the merge moved the world: the source did now+ // resolves to the target, so re-classification would answer+ // noop_same_person — and a naive handler would freeze that different+ // request and be rejected by the engine's equality guard. Attach-first+ // returns the recorded answer instead: same outcome, no new leader work.+ let retry = service+ .merge_persons(Request::new(request))+ .await+ .expect("the retry attaches")+ .into_inner();+ assert_eq!(+ rpc_outcomes(&retry),+ vec![("rpc-source".to_string(), MergeSourceOutcome::Merged)]+ );+ assert_eq!(retry.survivor.expect("survivor present").id, target);+ assert_eq!(+ h.leader.calls().len(),+ calls_after_first,+ "a retry of a finished op re-runs nothing"+ );++ h.ctx.cleanup().await.expect("cleanup");+}++#[tokio::test]+async fn inline_cases_settle_without_an_op_row_and_push_the_event_properties() {+ let h = MergeHarness::new().await;+ let service = h.service();+ let target = h.ctx.insert_person_with_distinct_id("inline-target").await;+ h.add_distinct_id(target, "inline-alias").await;++ let op_id = Uuid::now_v7();+ let mut request = rpc_request(+ h.ctx.team_id,+ "inline-target",+ &["inline-alias", "anonymous", "inline-unresolved"],+ op_id,+ );+ request.event_set = serde_json::to_vec(&json!({"plan": "pro"})).unwrap();+ let response = service+ .merge_persons(Request::new(request))+ .await+ .expect("inline call succeeds")+ .into_inner();++ assert_eq!(+ rpc_outcomes(&response),+ vec![+ (+ "inline-alias".to_string(),+ MergeSourceOutcome::NoopSamePerson+ ),+ ("anonymous".to_string(), MergeSourceOutcome::SkippedIllegal),+ ("inline-unresolved".to_string(), MergeSourceOutcome::Error),+ ]+ );+ let survivor = response.survivor.expect("survivor present");+ assert_eq!(survivor.id, target);+ // The survivor's created_at unit must not depend on which branch+ // produced it: the leader already answers epoch millis, so the+ // response must pass it through unscaled.+ let target_created_ms: i64 = sqlx::query_scalar(+ "SELECT floor(extract(epoch from created_at) * 1000)::bigint \+ FROM posthog_person WHERE team_id = $1 AND id = $2",+ )+ .bind(h.ctx.team_id as i32)+ .bind(target)+ .fetch_one(&h.ctx.pool)+ .await+ .unwrap();+ assert_eq!(survivor.created_at, target_created_ms);+ // The event's $set reached the survivor through the leader...+ assert_eq!(+ h.leader.calls(),+ vec![LeaderCall::PropertyPush { person_id: target }]+ );+ // ...and no durable op exists: nothing was destroyed, so retries just+ // re-classify.+ let op_count: i64 = sqlx::query_scalar("SELECT count(*) FROM lifecycle_op WHERE op_id = $1")+ .bind(op_id)+ .fetch_one(&h.ctx.pool)+ .await+ .unwrap();+ assert_eq!(op_count, 0);++ h.ctx.cleanup().await.expect("cleanup");+}++#[tokio::test]+async fn a_mixed_call_folds_inline_and_saga_outcomes_in_request_order() {+ let h = MergeHarness::new().await;+ let service = h.service();+ let target = h.ctx.insert_person_with_distinct_id("mixed-target").await;+ h.add_distinct_id(target, "mixed-alias").await;+ let source = h.ctx.insert_person_with_distinct_id("mixed-source").await;++ let response = service+ .merge_persons(Request::new(rpc_request(+ h.ctx.team_id,+ "mixed-target",+ &["mixed-alias", "mixed-source"],+ Uuid::now_v7(),+ )))+ .await+ .expect("merge succeeds")+ .into_inner();++ assert_eq!(+ rpc_outcomes(&response),+ vec![+ (+ "mixed-alias".to_string(),+ MergeSourceOutcome::NoopSamePerson+ ),+ ("mixed-source".to_string(), MergeSourceOutcome::Merged),+ ]+ );+ let (source_deleted, _, _) = h.person_state(source).await;+ assert!(source_deleted);++ h.ctx.cleanup().await.expect("cleanup");+}++#[tokio::test]+async fn an_op_id_reused_with_a_different_request_is_rejected() {+ let h = MergeHarness::new().await;+ let service = h.service();+ h.ctx.insert_person_with_distinct_id("reuse-target").await;+ h.ctx.insert_person_with_distinct_id("reuse-source").await;+ h.ctx.insert_person_with_distinct_id("reuse-other").await;++ let op_id = Uuid::now_v7();+ service+ .merge_persons(Request::new(rpc_request(+ h.ctx.team_id,+ "reuse-target",+ &["reuse-source"],+ op_id,+ )))+ .await+ .expect("first call succeeds");++ let status = service+ .merge_persons(Request::new(rpc_request(+ h.ctx.team_id,+ "reuse-target",+ &["reuse-other"],+ op_id,+ )))+ .await+ .expect_err("a different request must not attach");+ assert_eq!(status.code(), Code::FailedPrecondition);++ h.ctx.cleanup().await.expect("cleanup");+}++#[tokio::test]+async fn invalid_merge_requests_are_rejected_before_any_work() {+ let h = MergeHarness::new().await;+ let service = h.service();+ let team_id = h.ctx.team_id;+ let op = Uuid::now_v7();++ let cases: Vec<(&str, MergePersonsRequest, Code)> = vec![+ (+ "zero team",+ rpc_request(0, "t", &["s"], op),+ Code::InvalidArgument,+ ),+ (+ "illegal target",+ rpc_request(team_id, "anonymous", &["s"], op),+ Code::InvalidArgument,+ ),+ (+ "no sources",+ rpc_request(team_id, "t", &[], op),+ Code::InvalidArgument,+ ),+ (+ "duplicate sources",+ rpc_request(team_id, "t", &["s", "s"], op),+ Code::InvalidArgument,+ ),+ (+ "bad op_id",+ MergePersonsRequest {+ op_id: "not-a-uuid".to_string(),+ ..rpc_request(team_id, "t", &["s"], op)+ },+ Code::InvalidArgument,+ ),+ (+ "non-object event_set",+ MergePersonsRequest {+ event_set: serde_json::to_vec(&json!(["not", "a", "map"])).unwrap(),+ ..rpc_request(team_id, "t", &["s"], op)+ },+ Code::InvalidArgument,+ ),+ (+ "missing move_limit",+ MergePersonsRequest {+ move_limit: None,+ ..rpc_request(team_id, "t", &["s"], op)+ },+ Code::InvalidArgument,+ ),+ (+ "non-positive move_limit",+ MergePersonsRequest {+ move_limit: Some(0),+ ..rpc_request(team_id, "t", &["s"], op)+ },+ Code::InvalidArgument,+ ),+ (+ "unresolved target",+ rpc_request(team_id, "never-created-target", &["s"], op),+ Code::FailedPrecondition,+ ),+ ];+ for (label, request, expected) in cases {+ let status = service+ .merge_persons(Request::new(request))+ .await+ .expect_err(label);+ assert_eq!(status.code(), expected, "{label}");+ }+ assert!(h.leader.calls().is_empty());++ h.ctx.cleanup().await.expect("cleanup");+}++#[tokio::test]+async fn a_move_limited_source_skips_while_the_rest_merge_through_the_rpc() {+ let h = MergeHarness::new().await;+ let service = h.service();+ let target = h+ .ctx+ .insert_person_with_distinct_id("rpc-limit-target")+ .await;+ let small = h+ .ctx+ .insert_person_with_distinct_id("rpc-limit-small")+ .await;+ let big = h.ctx.insert_person_with_distinct_id("rpc-limit-big").await;+ h.add_distinct_id(big, "rpc-limit-big-2").await;++ let mut request = rpc_request(+ h.ctx.team_id,+ "rpc-limit-target",+ &["rpc-limit-small", "rpc-limit-big"],+ Uuid::now_v7(),+ );+ request.move_limit = Some(1);+ let response = service+ .merge_persons(Request::new(request))+ .await+ .expect("merge succeeds")+ .into_inner();++ assert_eq!(+ rpc_outcomes(&response),+ vec![+ ("rpc-limit-small".to_string(), MergeSourceOutcome::Merged),+ (+ "rpc-limit-big".to_string(),+ MergeSourceOutcome::SkippedMoveLimit+ ),+ ]+ );+ assert_eq!(response.survivor.as_ref().expect("survivor").id, target);+ let (small_deleted, _, _) = h.person_state(small).await;+ assert!(small_deleted);+ let (big_deleted, _, _) = h.person_state(big).await;+ assert!(!big_deleted, "a move-limited source must stay untouched");++ h.ctx.cleanup().await.expect("cleanup");+}++#[tokio::test]+async fn an_identified_source_aborts_through_the_rpc_with_no_survivor() {+ let h = MergeHarness::new().await;+ let service = h.service();+ let _target = h+ .ctx+ .insert_person_with_distinct_id("rpc-ident-target")+ .await;+ let source = h+ .ctx+ .insert_person_with_distinct_id("rpc-ident-source")+ .await;+ h.set_person(source, r#"{"plan": "pro"}"#, 3, true).await;++ let op_id = Uuid::now_v7();+ let request = rpc_request(+ h.ctx.team_id,+ "rpc-ident-target",+ &["rpc-ident-source"],+ op_id,+ );+ let response = service+ .merge_persons(Request::new(request.clone()))+ .await+ .expect("an aborted op still answers OK")+ .into_inner();++ // The skip is an answer, not an error — and an aborted op carries no+ // survivor document.+ assert_eq!(+ rpc_outcomes(&response),+ vec![(+ "rpc-ident-source".to_string(),+ MergeSourceOutcome::SkippedAlreadyIdentified+ )]+ );+ assert!(response.survivor.is_none());+ let (source_deleted, _, _) = h.person_state(source).await;+ assert!(!source_deleted);++ // The abort is recorded: a retry reproduces the answer instead of+ // re-running classification.+ let retry = service+ .merge_persons(Request::new(request))+ .await+ .expect("retry succeeds")+ .into_inner();+ assert!(retry.survivor.is_none());+ assert_eq!(+ rpc_outcomes(&retry),+ vec![(+ "rpc-ident-source".to_string(),+ MergeSourceOutcome::SkippedAlreadyIdentified+ )]+ );++ h.ctx.cleanup().await.expect("cleanup");+}++#[tokio::test]+async fn allow_identified_sources_merges_an_identified_source() {+ let h = MergeHarness::new().await;+ let service = h.service();+ let target = h+ .ctx+ .insert_person_with_distinct_id("rpc-dang-target")+ .await;+ let source = h+ .ctx+ .insert_person_with_distinct_id("rpc-dang-source")+ .await;+ h.set_person(source, r#"{"plan": "pro"}"#, 3, true).await;++ let mut request = rpc_request(+ h.ctx.team_id,+ "rpc-dang-target",+ &["rpc-dang-source"],+ Uuid::now_v7(),+ );+ request.allow_identified_sources = true;+ let response = service+ .merge_persons(Request::new(request))+ .await+ .expect("merge succeeds")+ .into_inner();++ assert_eq!(+ rpc_outcomes(&response),+ vec![("rpc-dang-source".to_string(), MergeSourceOutcome::Merged)]+ );+ assert_eq!(response.survivor.as_ref().expect("survivor").id, target);+ let (source_deleted, _, _) = h.person_state(source).await;+ assert!(source_deleted);++ h.ctx.cleanup().await.expect("cleanup");+}++#[tokio::test]+async fn a_failed_property_push_errors_the_call_and_the_retry_settles() {+ let h = MergeHarness::new().await;+ let service = h.service();+ let target = h+ .ctx+ .insert_person_with_distinct_id("rpc-pushfail-target")+ .await;+ h.add_distinct_id(target, "rpc-pushfail-alias").await;++ let op_id = Uuid::now_v7();+ let mut request = rpc_request(+ h.ctx.team_id,+ "rpc-pushfail-target",+ &["rpc-pushfail-alias"],+ op_id,+ );+ request.event_set = serde_json::to_vec(&json!({"plan": "pro"})).unwrap();+ h.leader.fail_next(+ Rpc::PropertyPush,+ target,+ Status::unavailable("leader down"),+ );++ // The push failure must fail the whole call — never an OK response+ // whose properties silently went nowhere.+ let status = service+ .merge_persons(Request::new(request.clone()))+ .await+ .expect_err("a failed push fails the call");+ assert_eq!(status.code(), Code::Unavailable);+ let op_count: i64 = sqlx::query_scalar("SELECT count(*) FROM lifecycle_op WHERE op_id = $1")+ .bind(op_id)+ .fetch_one(&h.ctx.pool)+ .await+ .unwrap();+ assert_eq!(op_count, 0);++ // The retry re-classifies and settles the same pairs.+ let retry = service+ .merge_persons(Request::new(request))+ .await+ .expect("retry succeeds")+ .into_inner();+ assert_eq!(+ rpc_outcomes(&retry),+ vec![(+ "rpc-pushfail-alias".to_string(),+ MergeSourceOutcome::NoopSamePerson+ )]+ );+ assert_eq!(retry.survivor.as_ref().expect("survivor").id, target);+h.ctx.cleanup().await.expect("cleanup");}diff --git a/rust/personhog-identity/tests/service_tests.rs b/rust/personhog-identity/tests/service_tests.rsindex 6494a6cd3da3..fbcab397bb7c 100644--- a/rust/personhog-identity/tests/service_tests.rs+++ b/rust/personhog-identity/tests/service_tests.rs@@ -8,6 +8,8 @@ use common::TestContext;use tonic::{Code, Request, Status};use personhog_identity::leader::PropertyWriter;+use personhog_identity::lifecycle::merge::{MergeDriver, MergeOpExecutor};+use personhog_identity::service::merge::MergeEntrance;use personhog_identity::service::validation::RequestLimits;use personhog_identity::service::PersonHogIdentityService;use personhog_proto::personhog::identity::v1::person_hog_identity_server::PersonHogIdentity;@@ -76,7 +78,17 @@ impl ServiceTestContext {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);+ let engine = Arc::new(ctx.engine());+ let merge = MergeEntrance::new(+ ctx.storage.clone(),+ writer.clone(),+ MergeOpExecutor::new(+ engine,+ MergeDriver::new(Arc::new(common::UnusedLeader), ctx.tables.clone()),+ ),+ );+ let service =+ PersonHogIdentityService::new(ctx.storage.clone(), writer.clone(), limits, merge);Self {ctx,writer,