: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): establish unresolved merge targets in MergePersons (#81382)
Nick Bestf49883e00ba9
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 4171021233cb..6315f577054f 100644--- a/nodejs/src/common/generated/personhog/personhog/identity/v1/identity_pb.ts+++ b/nodejs/src/common/generated/personhog/personhog/identity/v1/identity_pb.ts@@ -13,7 +13,7 @@ import { file_personhog_types_v1_person } from '../../types/v1/person_pb'export const file_personhog_identity_v1_identity: GenFile =/*@__PURE__*/fileDesc(- 'CiRwZXJzb25ob2cvaWRlbnRpdHkvdjEvaWRlbnRpdHkucHJvdG8SFXBlcnNvbmhvZy5pZGVudGl0eS52MSLOAQoWR2V0T3JDcmVhdGVQZXJzb25FbnRyeRIPCgd0ZWFtX2lkGAEgASgDEhMKC2Rpc3RpbmN0X2lkGAIgASgJEhoKEmV4dHJhX2Rpc3RpbmN0X2lkcxgDIAMoCRISCgpldmVudF9uYW1lGAQgASgJEhYKDnNldF9wcm9wZXJ0aWVzGAUgASgMEhsKE3NldF9vbmNlX3Byb3BlcnRpZXMYBiABKAwSEgoKY3JlYXRlZF9hdBgHIAEoAxIVCg1pc19pZGVudGlmaWVkGAggASgIImQKJEdldE9yQ3JlYXRlUGVyc29uQnlEaXN0aW5jdElkUmVxdWVzdBI8CgVlbnRyeRgBIAEoCzItLnBlcnNvbmhvZy5pZGVudGl0eS52MS5HZXRPckNyZWF0ZVBlcnNvbkVudHJ5ImQKJUdldE9yQ3JlYXRlUGVyc29uQnlEaXN0aW5jdElkUmVzcG9uc2USK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ZXNwb25zZRKLAQoYR2V0RGlzdGluY3RJZHNGb3JQZXJzb25zEjYucGVyc29uaG9nLmlkZW50aXR5LnYxLkdldERpc3RpbmN0SWRzRm9yUGVyc29uc1JlcXVlc3QaNy5wZXJzb25ob2cuaWRlbnRpdHkudjEuR2V0RGlzdGluY3RJZHNGb3JQZXJzb25zUmVzcG9uc2USZwoMTWVyZ2VQZXJzb25zEioucGVyc29uaG9nLmlkZW50aXR5LnYxLk1lcmdlUGVyc29uc1JlcXVlc3QaKy5wZXJzb25ob2cuaWRlbnRpdHkudjEuTWVyZ2VQZXJzb25zUmVzcG9uc2ViBnByb3RvMw',[file_personhog_types_v1_person])@@ -480,6 +480,14 @@ export type MergePersonsRequest = Message<'personhog.identity.v1.MergePersonsReq* @generated from field: optional int64 move_limit = 8;*/moveLimit?: bigint++ /**+ * Merge event created_at, epoch millis. Used as the survivor's+ * created_at when it predates the current value.+ *+ * @generated from field: int64 created_at = 9;+ */+ createdAt: bigint}/**@@ -527,7 +535,8 @@ export type MergePersonsResponse = Message<'personhog.identity.v1.MergePersonsRe/*** 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.+ * An aborted operation still answers the person the event's writes were+ * delivered to; absent only when the target no longer resolves.** @generated from field: optional personhog.types.v1.Person survivor = 2;*/diff --git a/proto/personhog/identity/v1/identity.proto b/proto/personhog/identity/v1/identity.protoindex 4e8d5d48c456..fb4388bc0aa5 100644--- a/proto/personhog/identity/v1/identity.proto+++ b/proto/personhog/identity/v1/identity.proto@@ -147,6 +147,9 @@ message MergePersonsRequest {// merge-mode policy to handle. Required, at least 1; unlimited is not a// supported mode.optional int64 move_limit = 8;+ // Merge event created_at, epoch millis. Used as the survivor's+ // created_at when it predates the current value.+ int64 created_at = 9;}enum MergeSourceOutcome {@@ -186,7 +189,8 @@ message MergePersonsResponse {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.+ // An aborted operation still answers the person the event's writes were+ // delivered to; absent only when the target no longer resolves.optional personhog.types.v1.Person survivor = 2;// One result per requested source, same order as the request.repeated MergeSourceResult results = 3;diff --git a/rust/Cargo.lock b/rust/Cargo.lockindex a8157bbb93b2..db0482fc0a88 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -8486,6 +8486,7 @@ dependencies = ["envconfig","futures","lifecycle",+ "metrics-exporter-prometheus","personhog-common","personhog-proto","rand 0.8.5",diff --git a/rust/personhog-identity/.sqlx/query-a405d45d85f1d2f405205b42a7fab52c9ebd8421453af66d5c13c6fdd7adf87d.json b/rust/personhog-identity/.sqlx/query-781b6c270dbdb936f7dc64fd7a007b130117f50235c066ee72705f5f3f5a8694.jsonsimilarity index 76%rename from rust/personhog-identity/.sqlx/query-a405d45d85f1d2f405205b42a7fab52c9ebd8421453af66d5c13c6fdd7adf87d.jsonrename to rust/personhog-identity/.sqlx/query-781b6c270dbdb936f7dc64fd7a007b130117f50235c066ee72705f5f3f5a8694.jsonindex 99607b642919..e3b0740aea15 100644--- a/rust/personhog-identity/.sqlx/query-a405d45d85f1d2f405205b42a7fab52c9ebd8421453af66d5c13c6fdd7adf87d.json+++ b/rust/personhog-identity/.sqlx/query-781b6c270dbdb936f7dc64fd7a007b130117f50235c066ee72705f5f3f5a8694.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT op_id, op_type, team_id::bigint as \"team_id!\", step, attempt,\n request as \"request: Value\", outcome as \"outcome: Value\", completed_at\n FROM lifecycle_op\n WHERE op_id = $1\n ",+ "query": "\n SELECT op_id, op_type, team_id::bigint as \"team_id!\", step, attempt,\n request as \"request: Value\", outcome as \"outcome: Value\",\n created_at, completed_at\n FROM lifecycle_op\n WHERE op_id = $1\n ","describe": {"columns": [{@@ -40,6 +40,11 @@},{"ordinal": 7,+ "name": "created_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 8,"name": "completed_at","type_info": "Timestamptz"}@@ -57,8 +62,9 @@false,false,true,+ false,true]},- "hash": "a405d45d85f1d2f405205b42a7fab52c9ebd8421453af66d5c13c6fdd7adf87d"+ "hash": "781b6c270dbdb936f7dc64fd7a007b130117f50235c066ee72705f5f3f5a8694"}diff --git a/rust/personhog-identity/Cargo.toml b/rust/personhog-identity/Cargo.tomlindex 9e3198fd851f..82fda5754cbb 100644--- a/rust/personhog-identity/Cargo.toml+++ b/rust/personhog-identity/Cargo.toml@@ -17,6 +17,7 @@ axum = { workspace = true }chrono = { workspace = true }envconfig = { workspace = true }futures = { workspace = true }+metrics-exporter-prometheus = { workspace = true }serde = { workspace = true }serde_json = { workspace = true }sqlx = { workspace = true }diff --git a/rust/personhog-identity/src/lifecycle/engine.rs b/rust/personhog-identity/src/lifecycle/engine.rsindex 77ca8b12131c..90d954fe2a5c 100644--- a/rust/personhog-identity/src/lifecycle/engine.rs+++ b/rust/personhog-identity/src/lifecycle/engine.rs@@ -31,6 +31,7 @@ pub const STEP_COMPLETED: &str = "completed";pub const STEP_ABORTED: &str = "aborted";const OPS_COMPLETED_TOTAL: &str = "personhog_lifecycle_ops_completed_total";+const OP_DURATION_MS: &str = "personhog_lifecycle_op_duration_ms";const SWEEPER_RESUMED_TOTAL: &str = "personhog_lifecycle_sweeper_resumed_total";const STEP_FAILURES_TOTAL: &str = "personhog_lifecycle_step_failures_total";const OPS_PARKED_TOTAL: &str = "personhog_lifecycle_ops_parked_total";@@ -139,6 +140,7 @@ pub struct OpRow {pub attempt: i32,pub request: Value,pub outcome: Option<Value>,+ pub created_at: DateTime<Utc>,pub completed_at: Option<DateTime<Utc>>,}@@ -303,7 +305,7 @@ impl Engine {"op {op_id} vanished while being driven")));};- if row.completed_at.is_some() {+ if let Some(completed_at) = row.completed_at {if claim_attempt.is_some() {// We drove it over the line (vs attaching to an op that// was already done).@@ -315,6 +317,13 @@ impl Engine {],1,);+ // Creation to terminal commit, so a sweeper-resumed op+ // reports its full lifetime, not the last drive's.+ common_metrics::histogram(+ OP_DURATION_MS,+ &[("op_type".to_string(), row.op_type.clone())],+ (completed_at - row.created_at).num_milliseconds() as f64,+ );}return Ok(row);}@@ -438,7 +447,8 @@ impl Engine {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+ request as "request: Value", outcome as "outcome: Value",+ created_at, completed_atFROM lifecycle_opWHERE op_id = $1"#,diff --git a/rust/personhog-identity/src/lifecycle/merge.rs b/rust/personhog-identity/src/lifecycle/merge.rsindex 87073208b906..65bc84375cc4 100644--- a/rust/personhog-identity/src/lifecycle/merge.rs+++ b/rust/personhog-identity/src/lifecycle/merge.rs@@ -180,6 +180,17 @@ fn record_transition(from: &str, to: &str) {);}+/// Count settled per-source outcomes. Shared by the saga's terminal record+/// and the entrance's inline settlement, so the counter covers every+/// requested source — not just the ones that entered the saga.+pub(crate) fn record_outcome_count(outcome: &str, count: u64) {+ common_metrics::inc(+ OUTCOMES_TOTAL,+ &[("outcome".to_string(), outcome.to_string())],+ count,+ );+}+fn record_outcomes(outcome: &Value) {let Ok(parsed) = serde_json::from_value::<MergeOutcome>(outcome.clone()) else {return;@@ -194,11 +205,7 @@ fn record_outcomes(outcome: &Value) {] {let count = parsed.results.iter().filter(|r| r.outcome == label).count();if count > 0 {- common_metrics::inc(- OUTCOMES_TOTAL,- &[("outcome".to_string(), label.to_string())],- count as u64,- );+ record_outcome_count(label, count as u64);}}}@@ -274,7 +281,8 @@ impl MergeOpExecutor {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+ request as "request: Value", outcome as "outcome: Value",+ created_at, completed_atFROM lifecycle_opWHERE op_id = $1"#,diff --git a/rust/personhog-identity/src/lifecycle/validation.rs b/rust/personhog-identity/src/lifecycle/validation.rsindex af4642ee1b9b..c474070b93dc 100644--- a/rust/personhog-identity/src/lifecycle/validation.rs+++ b/rust/personhog-identity/src/lifecycle/validation.rs@@ -143,6 +143,9 @@ pub fn validate_merge_persons(request: &MergePersonsRequest) -> Result<(Uuid, i6Some(_) => return Err(Status::invalid_argument("move_limit must be positive")),None => return Err(Status::invalid_argument("move_limit is required")),};+ if request.created_at < 0 {+ return Err(Status::invalid_argument("created_at must not be negative"));+ }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 949bda34490b..0901f3b21293 100644--- a/rust/personhog-identity/src/main.rs+++ b/rust/personhog-identity/src/main.rs@@ -3,9 +3,9 @@ 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 metrics_exporter_prometheus::{Matcher, PrometheusBuilder};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;@@ -116,7 +116,39 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {}),).route("/_liveness", get(move || async move { liveness.check() }));- let metrics_router = setup_metrics_routes(health_router);+ const BUCKETS: &[f64] = &[+ 1.0, 5.0, 10.0, 50.0, 100.0, 250.0, 500.0, 1000.0, 2000.0, 5000.0, 10000.0,+ ];+ // Lifecycle ops span "settled in one drive" (tens of ms) to+ // "abandoned, parked, or leader-blocked and resumed by the sweeper"+ // (minutes to an hour); the default latency ladder tops out at 10s+ // and would collapse every resumed op into +Inf.+ const OP_DURATION_BUCKETS: &[f64] = &[+ 10.0, 50.0, 100.0, 250.0, 500.0, 1000.0, 2500.0, 5000.0, 10000.0, 30000.0, 60000.0,+ 300000.0, 1800000.0, 3600000.0,+ ];+ // Source counts, not latency; the request cap is 250.+ const MERGE_SOURCES_BUCKETS: &[f64] = &[1.0, 2.0, 3.0, 5.0, 10.0, 25.0, 50.0, 100.0, 250.0];+ let recorder_handle = PrometheusBuilder::new()+ .add_global_label("service", "personhog-identity")+ .set_buckets(BUCKETS)+ .unwrap()+ .set_buckets_for_metric(+ Matcher::Full("personhog_lifecycle_op_duration_ms".into()),+ OP_DURATION_BUCKETS,+ )+ .unwrap()+ .set_buckets_for_metric(+ Matcher::Full("personhog_identity_merge_sources_per_call".into()),+ MERGE_SOURCES_BUCKETS,+ )+ .unwrap()+ .install_recorder()+ .expect("Failed to install metrics recorder");+ let metrics_router = health_router.route(+ "/metrics",+ get(move || std::future::ready(recorder_handle.render())),+ );let bind = format!("0.0.0.0:{metrics_port}");let listener = tokio::net::TcpListener::bind(&bind)diff --git a/rust/personhog-identity/src/service/merge.rs b/rust/personhog-identity/src/service/merge.rsindex e07282c316de..ca09532f9ea6 100644--- a/rust/personhog-identity/src/service/merge.rs+++ b/rust/personhog-identity/src/service/merge.rs@@ -8,6 +8,7 @@use std::collections::HashMap;use std::sync::Arc;+use chrono::{DateTime, Utc};use serde_json::Value;use tonic::Status;@@ -19,17 +20,19 @@ use personhog_proto::personhog::types::v1::{Person as ProtoPerson, UpdatePersonPuse 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,+ record_outcome_count, 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::{AttachOutcome, IdentityStorage};+use crate::storage::{AttachOutcome, IdentityStorage, Person, PersonStub, StubOutcome};/// Handler-decided outcomes that never reach the saga.const OUTCOME_SKIPPED_ILLEGAL: &str = "skipped_illegal";const OUTCOME_ATTACHED: &str = "attached";+const MERGE_SOURCES_PER_CALL: &str = "personhog_identity_merge_sources_per_call";+/// The full MergePersons flow, owned by the identity side of the crate.pub struct MergeEntrance {storage: Arc<dyn IdentityStorage>,@@ -58,6 +61,7 @@ impl MergeEntrance {request: MergePersonsRequest,) -> Result<MergePersonsResponse, Status> {let (op_id, move_limit) = validate_merge_persons(&request)?;+ common_metrics::histogram(MERGE_SOURCES_PER_CALL, &[], request.sources.len() as f64);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);@@ -81,7 +85,8 @@ impl MergeEntrance {}let frozen = row.request.clone();let row = self.ops.execute(op_id, row.team_id, &frozen).await?;- return merge_response(&row);+ let delivered = self.deliver_aborted_writes(&request, &row).await?;+ return merge_response(&row, delivered);}// Classify: resolve everything once on the primary, settle what@@ -103,16 +108,10 @@ impl MergeEntrance {.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 = match resolved.get(&target_key) {+ Some(target) => target.clone(),+ None => self.establish_target(&request, &resolved).await?,};- let target_person = target_person.clone();let mut inline_results: HashMap<String, String> = HashMap::new();let mut attach: Vec<String> = Vec::new();@@ -159,6 +158,19 @@ impl MergeEntrance {}}+ // Inline outcomes never reach the saga's terminal record, so they+ // are counted here at settlement. A retried call that re-classifies+ // re-counts — the same at-least-once semantics as the response+ // itself (see below); a retry that attaches to an existing op+ // returns above and never re-counts.+ let mut inline_counts: HashMap<&str, u64> = HashMap::new();+ for outcome in inline_results.values() {+ *inline_counts.entry(outcome.as_str()).or_default() += 1;+ }+ for (outcome, count) in inline_counts {+ record_outcome_count(outcome, count);+ }+if saga_sources.is_empty() {// Nothing to destroy, so no op row. Inline settlement is// idempotent: a retry re-executes against the current world,@@ -169,8 +181,14 @@ impl MergeEntrance {// is not a dedupe of idempotent work (an attached source// re-answers noop_same_person). The event's properties still// reach the survivor.+ // An identify that actually joined identities makes the+ // survivor identified; a call whose every pair was skipped+ // proves nothing.+ let flip_identified = inline_results+ .values()+ .any(|o| o == OUTCOME_ATTACHED || o == OUTCOME_NOOP_SAME_PERSON);let pushed = self- .push_event_properties(&request, target_person.id)+ .push_event_properties(&request, &target_person, flip_identified).await?;let results = request.sources@@ -211,35 +229,191 @@ impl MergeEntrance {.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)+ let delivered = self.deliver_aborted_writes(&request, &row).await?;+ merge_response(&row, delivered)}- /// 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.+ /// An aborted saga never folds, so the merge event's writes (its+ /// $set/$set_once and the identified flip) would otherwise reach+ /// nobody. Ingestion applies both to the target even when it refuses a+ /// merge (person-merge-service.ts sets updateIsIdentified before it+ /// looks at the source), so the RPC must too: deliver them against+ /// whatever the target distinct id resolves to now. The frozen request+ /// is not consulted for the person, because the op that caused the+ /// abort may have settled the target away since. A push failure errors+ /// the call rather than answering OK with lost writes; the retry+ /// attaches to the aborted op and re-drives this delivery.+ async fn deliver_aborted_writes(+ &self,+ request: &MergePersonsRequest,+ row: &OpRow,+ ) -> Result<Option<ProtoPerson>, Status> {+ let aborted = row+ .outcome+ .as_ref()+ .and_then(|o| o.get("aborted"))+ .and_then(Value::as_bool)+ .unwrap_or(false);+ if !aborted {+ return Ok(None);+ }+ let key = (request.team_id, request.target_distinct_id.clone());+ let mut resolved = self+ .storage+ .resolve_distinct_ids(std::slice::from_ref(&key))+ .await+ .map_err(|e| Status::internal(format!("target re-resolution failed: {e}")))?;+ // A target that no longer resolves was destroyed after the abort;+ // the writes have no person to land on, and the caller's retry+ // semantics (re-deliver the event) cover the gap.+ let Some(survivor) = resolved.remove(&key) else {+ return Ok(None);+ };+ // A saga only exists for legal resolved pairs, and ingestion marks+ // the target identified for any legal pair regardless of the merge+ // outcome, so the flip always accompanies the delivery.+ let pushed = self.push_event_properties(request, &survivor, true).await?;+ Ok(Some(pushed.unwrap_or_else(|| survivor.into())))+ }++ /// Apply the merge event's $set/$set_once and the identified flip to+ /// the survivor when no saga runs (the fold carries both when one+ /// does). The ack means the changes are durable in the changelog.+ /// Skipped entirely when there is nothing to change — a repeat+ /// identify of an already-identified survivor with no new properties+ /// costs no leader round trip.async fn push_event_properties(&self,request: &MergePersonsRequest,- person_id: i64,+ survivor: &Person,+ flip_identified: bool,) -> Result<Option<ProtoPerson>, Status> {- if request.event_set.is_empty() && request.event_set_once.is_empty() {+ let flip = flip_identified && !survivor.is_identified;+ if request.event_set.is_empty() && request.event_set_once.is_empty() && !flip {return Ok(None);}let response = self.property_writer.update_person_properties(UpdatePersonPropertiesRequest {team_id: request.team_id,- person_id,+ person_id: survivor.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,+ is_identified: flip.then_some(true),last_seen_at: None,}).await?;Ok(response.person)}++ /// The unresolved-target half of the merge contract: the target+ /// distinct id resolves to no person, so the call must establish the+ /// survivor before anything can classify against it. The first+ /// eligible resolved source's person survives and the target distinct+ /// id attaches to it; when no eligible source resolves, the target+ /// person is born fresh, its uuid derived from the target distinct id+ /// so the id's implied-person events already point at it. Both writes+ /// are idempotent, so a crash between establishment and settlement+ /// re-drives through re-classification: the established target then+ /// simply resolves.+ async fn establish_target(+ &self,+ request: &MergePersonsRequest,+ resolved: &HashMap<(i64, String), Person>,+ ) -> Result<Person, Status> {+ let target_did = &request.target_distinct_id;++ // Eligibility applies the identified-source policy here, not just+ // in the saga: surviving would attach the target to the source's+ // person and settle the pair as a same-person no-op, so the saga's+ // refusal would never run and any identify request could alias its+ // unresolved target onto a known identified person. An ineligible+ // source instead classifies against the birthed target, where the+ // saga refuses it as skipped_already_identified.+ let first_resolved = request+ .sources+ .iter()+ .filter(|s| !is_distinct_id_illegal(&s.source_distinct_id))+ .filter_map(|s| resolved.get(&(request.team_id, s.source_distinct_id.clone())))+ .find(|person| request.allow_identified_sources || !person.is_identified);+ if let Some(survivor) = first_resolved {+ let attached = self+ .storage+ .attach_distinct_ids(+ request.team_id,+ survivor.id,+ std::slice::from_ref(target_did),+ )+ .await+ .map_err(|e| Status::internal(format!("target attach failed: {e}")))?;+ return match attached.get(target_did) {+ Some(AttachOutcome::Attached { .. }) => Ok(survivor.clone()),+ // The target distinct id got mapped concurrently; that+ // mapping wins and its person is the survivor.+ Some(AttachOutcome::AlreadyMapped { .. }) => {+ self.resolve_target_after_race(request).await+ }+ // The survivor row vanished under the attach (a racing+ // lifecycle op committed). Nothing durable happened for+ // this op, so the retry re-classifies against the settled+ // world.+ None => Err(Status::unavailable(+ "survivor was destroyed by a concurrent operation; retry",+ )),+ };+ }++ // No eligible source resolves: birth the target person. Born+ // unidentified even when a legal source will settle: the leader's+ // changelog is the downstream person feed and the leader only+ // records changes, so the settlement flip is what writes the+ // newborn's first changelog document. A stub born already+ // identified would make that flip a no-op and leave the person+ // invisible downstream; a crash before the flip self-heals, since+ // the still-unidentified row re-arms it on the retry.+ let created_at = if request.created_at == 0 {+ Utc::now()+ } else {+ DateTime::from_timestamp_millis(request.created_at)+ .ok_or_else(|| Status::invalid_argument("created_at is out of range"))?+ };+ let outcomes = self+ .storage+ .create_person_stubs(&[PersonStub {+ team_id: request.team_id,+ distinct_id: target_did.clone(),+ extra_distinct_ids: Vec::new(),+ created_at,+ is_identified: false,+ }])+ .await+ .map_err(|e| Status::internal(format!("target creation failed: {e}")))?;+ match outcomes.into_iter().next() {+ Some(StubOutcome::Committed { person, .. }) => Ok(person),+ Some(StubOutcome::LostRace) | None => self.resolve_target_after_race(request).await,+ }+ }++ /// Re-resolve the target distinct id after losing an establishment+ /// race. The winner's person is as good a survivor as ours would have+ /// been; a mapping that vanished again mid-race sends the caller back+ /// around.+ async fn resolve_target_after_race(+ &self,+ request: &MergePersonsRequest,+ ) -> Result<Person, Status> {+ let key = (request.team_id, request.target_distinct_id.clone());+ let mut resolved = self+ .storage+ .resolve_distinct_ids(std::slice::from_ref(&key))+ .await+ .map_err(|e| Status::internal(format!("target re-resolution failed: {e}")))?;+ resolved.remove(&key).ok_or_else(|| {+ Status::unavailable("target resolution raced a concurrent operation; retry")+ })+ }}/// Decode a JSON-map wire field (empty bytes mean an empty map).@@ -283,6 +457,7 @@ fn merge_original("event_set_once": event_set_once,"allow_identified_sources": request.allow_identified_sources,"move_limit": request.move_limit,+ "created_at": request.created_at,})}@@ -318,10 +493,15 @@ fn survivor_to_proto(survivor: &Value, team_id: i64) -> ProtoPerson {/// 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.+/// in the original request's source order. An aborted outcome records no+/// survivor; `delivered` fills it with the person the aborted delivery+/// wrote to, so the caller still learns the event's person.// See `MergeEntrance::handle` for why result_large_err is allowed.#[allow(clippy::result_large_err)]-fn merge_response(row: &OpRow) -> Result<MergePersonsResponse, Status> {+fn merge_response(+ row: &OpRow,+ delivered: Option<ProtoPerson>,+) -> Result<MergePersonsResponse, Status> {let Some(outcome) = &row.outcome else {return Err(Status::internal(format!("op {} is terminal but has no recorded outcome",@@ -382,7 +562,8 @@ fn merge_response(row: &OpRow) -> Result<MergePersonsResponse, Status> {survivor: outcome.survivor.as_ref()- .map(|s| survivor_to_proto(s, row.team_id)),+ .map(|s| survivor_to_proto(s, row.team_id))+ .or(delivered),results,})}diff --git a/rust/personhog-identity/tests/common/mod.rs b/rust/personhog-identity/tests/common/mod.rsindex 43686ff5f412..e8d92b0e5648 100644--- a/rust/personhog-identity/tests/common/mod.rs+++ b/rust/personhog-identity/tests/common/mod.rs@@ -295,3 +295,107 @@ impl personhog_identity::storage::IdentityStorage for UnusedStorage {panic!("not exercised by this test")}}++/// Wraps the real storage to inject the target-establishment races that+/// cannot be produced deterministically otherwise. Each injection fires+/// once, and the "concurrent winner" side effect is committed through the+/// real storage so the entrance's re-resolution finds what a genuine race+/// would have left behind.+pub struct RacingStorage {+ inner: Arc<PostgresIdentityStorage>,+ /// attach_distinct_ids: map the ids to THIS person instead (the+ /// concurrent winner) and answer AlreadyMapped.+ pub hijack_attach_to: std::sync::Mutex<Option<i64>>,+ /// attach_distinct_ids: attach nothing (the person vanished under a+ /// racing lifecycle op).+ pub vanish_attach: std::sync::Mutex<bool>,+ /// create_person_stubs: commit the stub as a concurrent winner and+ /// answer LostRace.+ pub lose_create_race: std::sync::Mutex<bool>,+}++impl RacingStorage {+ pub fn new(inner: Arc<PostgresIdentityStorage>) -> Self {+ Self {+ inner,+ hijack_attach_to: std::sync::Mutex::new(None),+ vanish_attach: std::sync::Mutex::new(false),+ lose_create_race: std::sync::Mutex::new(false),+ }+ }+}++#[async_trait::async_trait]+impl personhog_identity::storage::IdentityStorage for RacingStorage {+ async fn resolve_distinct_ids(+ &self,+ keys: &[(i64, String)],+ ) -> personhog_identity::storage::StorageResult<+ std::collections::HashMap<(i64, String), personhog_identity::storage::Person>,+ > {+ self.inner.resolve_distinct_ids(keys).await+ }++ 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>,+ > {+ self.inner+ .get_distinct_ids_for_persons(team_id, person_ids, limit_per_person)+ .await+ }++ async fn create_person_stubs(+ &self,+ stubs: &[personhog_identity::storage::PersonStub],+ ) -> personhog_identity::storage::StorageResult<Vec<personhog_identity::storage::StubOutcome>>+ {+ let lose = std::mem::take(&mut *self.lose_create_race.lock().unwrap());+ if lose {+ self.inner.create_person_stubs(stubs).await?;+ return Ok(stubs+ .iter()+ .map(|_| personhog_identity::storage::StubOutcome::LostRace)+ .collect());+ }+ self.inner.create_person_stubs(stubs).await+ }++ async fn attach_distinct_ids(+ &self,+ team_id: i64,+ person_id: i64,+ distinct_ids: &[String],+ ) -> personhog_identity::storage::StorageResult<+ std::collections::HashMap<String, personhog_identity::storage::AttachOutcome>,+ > {+ let vanish = std::mem::take(&mut *self.vanish_attach.lock().unwrap());+ if vanish {+ return Ok(std::collections::HashMap::new());+ }+ let winner = self.hijack_attach_to.lock().unwrap().take();+ if let Some(winner) = winner {+ self.inner+ .attach_distinct_ids(team_id, winner, distinct_ids)+ .await?;+ return Ok(distinct_ids+ .iter()+ .map(|d| {+ (+ d.clone(),+ personhog_identity::storage::AttachOutcome::AlreadyMapped {+ person_id: winner,+ },+ )+ })+ .collect());+ }+ self.inner+ .attach_distinct_ids(team_id, person_id, distinct_ids)+ .await+ }+}diff --git a/rust/personhog-identity/tests/common/sim_leader.rs b/rust/personhog-identity/tests/common/sim_leader.rsindex 8e1a10fc151a..7bbafe3bf143 100644--- a/rust/personhog-identity/tests/common/sim_leader.rs+++ b/rust/personhog-identity/tests/common/sim_leader.rs@@ -88,6 +88,7 @@ pub enum LeaderCall {},PropertyPush {person_id: i64,+ is_identified: Option<bool>,},}@@ -544,12 +545,16 @@ impl PropertyWriter for SimLeader {if self.deaths.lock().unwrap().contains_key(&request.person_id) {return Err(Status::not_found("person is destroyed"));}- let person = self+ let mut person = self.live_person(request.team_id, request.person_id).await.ok_or_else(|| Status::not_found("person is destroyed"))?;+ // The real leader OR-merges the flip and answers with the updated+ // person; the flip reaches Postgres through the changelog, not here.+ person.is_identified = person.is_identified || request.is_identified == Some(true);self.record(LeaderCall::PropertyPush {person_id: request.person_id,+ is_identified: request.is_identified,});Ok(UpdatePersonPropertiesResponse {person: Some(person),diff --git a/rust/personhog-identity/tests/lifecycle_merge_tests.rs b/rust/personhog-identity/tests/lifecycle_merge_tests.rsindex 27eb188c1ac3..5b7f18d98b73 100644--- a/rust/personhog-identity/tests/lifecycle_merge_tests.rs+++ b/rust/personhog-identity/tests/lifecycle_merge_tests.rs@@ -17,6 +17,7 @@ use chrono::Utc;use common::sim_leader::{LeaderCall, Rpc, SimLeader, FENCED_METADATA_KEY};use common::TestContext;use personhog_common::grpc::semantic_refusal;+use personhog_common::persons::person_uuid;use serde_json::json;use sqlx::postgres::PgPool;use tonic::{Code, Status};@@ -1509,6 +1510,7 @@ 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_identity::storage::IdentityStorage;use personhog_proto::personhog::identity::v1::person_hog_identity_server::PersonHogIdentity;use personhog_proto::personhog::identity::v1::{MergePersonsRequest, MergePersonsResponse, MergeSource, MergeSourceOutcome,@@ -1516,6 +1518,27 @@ use personhog_proto::personhog::identity::v1::{use tonic::Request;impl MergeHarness {+ fn service_with_storage(&self, storage: Arc<dyn IdentityStorage>) -> PersonHogIdentityService {+ let engine = Arc::new(self.ctx.engine());+ PersonHogIdentityService::new(+ storage.clone(),+ self.leader.clone(),+ RequestLimits {+ max_batch_size: 250,+ max_distinct_id_length: 400,+ max_extra_distinct_ids: 10,+ },+ MergeEntrance::new(+ storage,+ self.leader.clone(),+ MergeOpExecutor::new(+ engine,+ MergeDriver::new(self.leader.clone(), self.ctx.tables.clone()),+ ),+ ),+ )+ }+fn service(&self) -> PersonHogIdentityService {let engine = Arc::new(self.ctx.engine());PersonHogIdentityService::new(@@ -1554,6 +1577,7 @@ fn rpc_request(team_id: i64, target: &str, sources: &[&str], op_id: Uuid) -> Merop_id: op_id.to_string(),allow_identified_sources: false,move_limit: Some(1_000),+ created_at: 0,}}@@ -1665,10 +1689,14 @@ async fn inline_cases_settle_without_an_op_row_and_push_the_event_properties() {.await.unwrap();assert_eq!(survivor.created_at, target_created_ms);- // The event's $set reached the survivor through the leader...+ // The event's $set reached the survivor through the leader, carrying+ // the identified flip: pairs settled, so the survivor is identified...assert_eq!(h.leader.calls(),- vec![LeaderCall::PropertyPush { person_id: target }]+ vec![LeaderCall::PropertyPush {+ person_id: target,+ is_identified: Some(true),+ }]);// ...and no durable op exists: nothing was destroyed, so retries just// re-classify.@@ -1836,9 +1864,12 @@ async fn invalid_merge_requests_are_rejected_before_any_work() {Code::InvalidArgument,),(- "unresolved target",- rpc_request(team_id, "never-created-target", &["s"], op),- Code::FailedPrecondition,+ "negative created_at",+ MergePersonsRequest {+ created_at: -1,+ ..rpc_request(team_id, "t", &["s"], op)+ },+ Code::InvalidArgument,),];for (label, request, expected) in cases {@@ -1853,6 +1884,289 @@ async fn invalid_merge_requests_are_rejected_before_any_work() {h.ctx.cleanup().await.expect("cleanup");}+#[tokio::test]+async fn an_unresolved_target_attaches_to_the_first_resolved_sources_person() {+ let h = MergeHarness::new().await;+ let service = h.service();+ let survivor = h.ctx.insert_person_with_distinct_id("flip-source").await;++ let response = service+ .merge_persons(Request::new(rpc_request(+ h.ctx.team_id,+ "flip-target",+ &["flip-personless", "flip-source"],+ Uuid::now_v7(),+ )))+ .await+ .expect("target attach succeeds")+ .into_inner();++ assert_eq!(+ response.survivor.as_ref().expect("survivor present").id,+ survivor+ );+ assert_eq!(+ rpc_outcomes(&response),+ vec![+ ("flip-personless".to_string(), MergeSourceOutcome::Attached),+ (+ "flip-source".to_string(),+ MergeSourceOutcome::NoopSamePerson+ ),+ ]+ );+ // The target distinct id and the personless source both attached to the+ // surviving person, with version 1 (an override row is always written).+ assert_eq!(h.pdi_state("flip-target").await, (survivor, false, 1));+ assert_eq!(h.pdi_state("flip-personless").await, (survivor, false, 1));+ // Pairs settled, so the survivor is identified via one leader push.+ assert_eq!(+ h.leader.calls(),+ vec![LeaderCall::PropertyPush {+ person_id: survivor,+ is_identified: Some(true),+ }]+ );++ h.ctx.cleanup().await.expect("cleanup");+}++#[tokio::test]+async fn an_identified_source_is_not_an_eligible_survivor_for_an_unresolved_target() {+ let h = MergeHarness::new().await;+ let service = h.service();+ let source = h+ .ctx+ .insert_person_with_distinct_id("elig-ident-source")+ .await;+ h.set_person(source, r#"{"plan": "pro"}"#, 3, true).await;++ let response = service+ .merge_persons(Request::new(rpc_request(+ h.ctx.team_id,+ "elig-target",+ &["elig-ident-source"],+ Uuid::now_v7(),+ )))+ .await+ .expect("call succeeds")+ .into_inner();++ // The identified person must not absorb the unresolved target: that+ // attach would settle the pair as a same-person no-op and bypass the+ // saga's refusal. The target is born fresh instead and the pair gets+ // the same policy answer the both-exist shape gives.+ let survivor = response.survivor.as_ref().expect("survivor present");+ assert_ne!(survivor.id, source);+ assert_eq!(+ survivor.uuid,+ person_uuid(h.ctx.team_id, "elig-target").to_string()+ );+ assert_eq!(+ rpc_outcomes(&response),+ vec![(+ "elig-ident-source".to_string(),+ MergeSourceOutcome::SkippedAlreadyIdentified+ )]+ );+ assert_eq!(h.pdi_state("elig-target").await, (survivor.id, false, 0));+ assert_eq!(h.pdi_state("elig-ident-source").await.0, source);+ let (source_deleted, _, _) = h.person_state(source).await;+ assert!(!source_deleted);+ // The refused pair aborts the saga, so the abort delivery flips the+ // newborn through the leader.+ assert_eq!(+ h.leader.calls(),+ vec![LeaderCall::PropertyPush {+ person_id: survivor.id,+ is_identified: Some(true),+ }]+ );++ h.ctx.cleanup().await.expect("cleanup");+}++#[tokio::test]+async fn allow_identified_sources_lets_an_identified_source_survive_an_unresolved_target() {+ let h = MergeHarness::new().await;+ let service = h.service();+ let source = h+ .ctx+ .insert_person_with_distinct_id("elig-allowed-source")+ .await;+ h.set_person(source, r#"{"plan": "pro"}"#, 3, true).await;++ let mut request = rpc_request(+ h.ctx.team_id,+ "elig-allowed-target",+ &["elig-allowed-source"],+ Uuid::now_v7(),+ );+ request.allow_identified_sources = true;+ let response = service+ .merge_persons(Request::new(request))+ .await+ .expect("call succeeds")+ .into_inner();++ let survivor = response.survivor.as_ref().expect("survivor present");+ assert_eq!(survivor.id, source);+ assert_eq!(+ rpc_outcomes(&response),+ vec![(+ "elig-allowed-source".to_string(),+ MergeSourceOutcome::NoopSamePerson+ )]+ );+ assert_eq!(h.pdi_state("elig-allowed-target").await, (source, false, 1));++ h.ctx.cleanup().await.expect("cleanup");+}++#[tokio::test]+async fn a_fully_unresolved_call_births_the_target_person() {+ let h = MergeHarness::new().await;+ let service = h.service();++ let op_id = Uuid::now_v7();+ let mut request = rpc_request(h.ctx.team_id, "birth-target", &["birth-anon"], op_id);+ request.created_at = 1_700_000_000_000;+ let response = service+ .merge_persons(Request::new(request.clone()))+ .await+ .expect("target birth succeeds")+ .into_inner();++ // The person is born on the target distinct id's deterministic uuid,+ // stamped with the event's timestamp, and identified by the settlement+ // flip through the leader.+ let survivor = response.survivor.as_ref().expect("survivor present");+ assert_eq!(+ survivor.uuid,+ person_uuid(h.ctx.team_id, "birth-target").to_string()+ );+ assert_eq!(survivor.created_at, 1_700_000_000_000);+ assert!(survivor.is_identified);+ assert_eq!(+ rpc_outcomes(&response),+ vec![("birth-anon".to_string(), MergeSourceOutcome::Attached)]+ );+ // The uuid-seeding distinct id keeps version 0 (its implied-person+ // events already point at this person); the attached one gets 1.+ assert_eq!(h.pdi_state("birth-target").await, (survivor.id, false, 0));+ assert_eq!(h.pdi_state("birth-anon").await, (survivor.id, false, 1));+ // Born unidentified, then flipped through the leader: the flip is a+ // change the leader records, so it doubles as the newborn's first+ // changelog document — the downstream person feed's copy. A stub born+ // identified would make the flip a no-op and never reach the feed.+ assert_eq!(+ h.leader.calls(),+ vec![LeaderCall::PropertyPush {+ person_id: survivor.id,+ is_identified: Some(true),+ }]+ );+ 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);++ // A retry re-classifies against the settled world and answers the+ // equivalent no-op, with the same survivor.+ let retry = service+ .merge_persons(Request::new(request))+ .await+ .expect("retry succeeds")+ .into_inner();+ assert_eq!(+ retry.survivor.as_ref().expect("survivor present").id,+ survivor.id+ );+ assert_eq!(+ rpc_outcomes(&retry),+ vec![("birth-anon".to_string(), MergeSourceOutcome::NoopSamePerson)]+ );++ h.ctx.cleanup().await.expect("cleanup");+}++#[tokio::test]+async fn an_all_illegal_call_births_the_target_unidentified() {+ let h = MergeHarness::new().await;+ let service = h.service();++ let response = service+ .merge_persons(Request::new(rpc_request(+ h.ctx.team_id,+ "illegal-only-target",+ &["anonymous"],+ Uuid::now_v7(),+ )))+ .await+ .expect("call succeeds")+ .into_inner();++ // The caller's event still needs a person, so the target is born — but+ // an identify whose every pair was skipped proves no identity.+ let survivor = response.survivor.as_ref().expect("survivor present");+ assert!(!survivor.is_identified);+ assert_eq!(+ rpc_outcomes(&response),+ vec![("anonymous".to_string(), MergeSourceOutcome::SkippedIllegal)]+ );+ assert_eq!(+ h.pdi_state("illegal-only-target").await,+ (survivor.id, false, 0)+ );+ assert!(h.leader.calls().is_empty());++ h.ctx.cleanup().await.expect("cleanup");+}++#[tokio::test]+async fn an_unresolved_target_call_still_runs_the_saga_for_second_persons() {+ let h = MergeHarness::new().await;+ let service = h.service();+ let survivor = h.ctx.insert_person_with_distinct_id("flip-saga-a").await;+ let other = h.ctx.insert_person_with_distinct_id("flip-saga-b").await;++ let response = service+ .merge_persons(Request::new(rpc_request(+ h.ctx.team_id,+ "flip-saga-target",+ &["flip-saga-a", "flip-saga-b"],+ Uuid::now_v7(),+ )))+ .await+ .expect("merge succeeds")+ .into_inner();++ // The first resolved source's person survives; the second person folds+ // into it through the saga and dies.+ assert_eq!(+ response.survivor.as_ref().expect("survivor present").id,+ survivor+ );+ assert_eq!(+ rpc_outcomes(&response),+ vec![+ (+ "flip-saga-a".to_string(),+ MergeSourceOutcome::NoopSamePerson+ ),+ ("flip-saga-b".to_string(), MergeSourceOutcome::Merged),+ ]+ );+ assert_eq!(h.pdi_state("flip-saga-target").await, (survivor, false, 1));+ assert_eq!(h.pdi_state("flip-saga-b").await, (survivor, false, 1));+ let (other_deleted, _, _) = h.person_state(other).await;+ assert!(other_deleted);++ 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;@@ -1901,10 +2215,10 @@ async fn a_move_limited_source_skips_while_the_rest_merge_through_the_rpc() {}#[tokio::test]-async fn an_identified_source_aborts_through_the_rpc_with_no_survivor() {+async fn an_identified_source_abort_still_delivers_the_events_writes() {let h = MergeHarness::new().await;let service = h.service();- let _target = h+ let target = h.ctx.insert_person_with_distinct_id("rpc-ident-target").await;@@ -1915,20 +2229,24 @@ async fn an_identified_source_aborts_through_the_rpc_with_no_survivor() {h.set_person(source, r#"{"plan": "pro"}"#, 3, true).await;let op_id = Uuid::now_v7();- let request = rpc_request(+ let mut request = rpc_request(h.ctx.team_id,"rpc-ident-target",&["rpc-ident-source"],op_id,);+ request.event_set = serde_json::to_vec(&json!({"tier": "pro"})).unwrap();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.+ // The skip is an answer, not an error. The saga never folds, so the+ // event's $set and the identified flip are delivered through the+ // ordinary write surface instead, and the answer carries the person+ // they landed on — the same person ingestion continues the event with+ // when it refuses a merge.assert_eq!(rpc_outcomes(&response),vec![(@@ -1936,18 +2254,26 @@ async fn an_identified_source_aborts_through_the_rpc_with_no_survivor() {MergeSourceOutcome::SkippedAlreadyIdentified)]);- assert!(response.survivor.is_none());+ assert_eq!(response.survivor.as_ref().expect("survivor").id, target);+ assert_eq!(+ h.leader.calls(),+ vec![LeaderCall::PropertyPush {+ person_id: target,+ is_identified: Some(true),+ }]+ );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.+ // re-running classification, and re-drives the delivery (the same+ // at-least-once semantics as the inline branch).let retry = service.merge_persons(Request::new(request)).await.expect("retry succeeds").into_inner();- assert!(retry.survivor.is_none());+ assert_eq!(retry.survivor.as_ref().expect("survivor").id, target);assert_eq!(rpc_outcomes(&retry),vec![(@@ -1955,6 +2281,70 @@ async fn an_identified_source_aborts_through_the_rpc_with_no_survivor() {MergeSourceOutcome::SkippedAlreadyIdentified)]);+ assert_eq!(h.leader.calls().len(), 2);++ h.ctx.cleanup().await.expect("cleanup");+}++#[tokio::test]+async fn a_failed_abort_delivery_errors_the_call_and_the_retry_delivers() {+ let h = MergeHarness::new().await;+ let service = h.service();+ let target = h+ .ctx+ .insert_person_with_distinct_id("rpc-abort-fail-target")+ .await;+ let source = h+ .ctx+ .insert_person_with_distinct_id("rpc-abort-fail-source")+ .await;+ h.set_person(source, r#"{"plan": "pro"}"#, 3, true).await;+ h.leader.fail_next(+ Rpc::PropertyPush,+ target,+ Status::unavailable("leader unavailable"),+ );++ let op_id = Uuid::now_v7();+ let mut request = rpc_request(+ h.ctx.team_id,+ "rpc-abort-fail-target",+ &["rpc-abort-fail-source"],+ op_id,+ );+ request.event_set = serde_json::to_vec(&json!({"tier": "pro"})).unwrap();++ // OK means the event's writes are durable, so a failed delivery must+ // surface as an error, never as an aborted answer with lost writes.+ let status = service+ .merge_persons(Request::new(request.clone()))+ .await+ .expect_err("a failed delivery fails the call");+ assert_eq!(status.code(), Code::Unavailable);+ let (step, _) = op_row_state(&h.ctx.pool, op_id).await;+ assert_eq!(step, STEP_ABORTED);++ // The retry attaches to the recorded abort and re-drives the delivery.+ let retry = service+ .merge_persons(Request::new(request))+ .await+ .expect("retry succeeds")+ .into_inner();+ assert_eq!(retry.survivor.as_ref().expect("survivor").id, target);+ assert_eq!(+ rpc_outcomes(&retry),+ vec![(+ "rpc-abort-fail-source".to_string(),+ MergeSourceOutcome::SkippedAlreadyIdentified+ )]+ );+ assert_eq!(+ h.leader.calls(),+ vec![LeaderCall::PropertyPush {+ person_id: target,+ is_identified: Some(true),+ }]+ );h.ctx.cleanup().await.expect("cleanup");}@@ -2103,3 +2493,115 @@ async fn a_failed_push_after_attach_leaves_the_attach_durable() {h.ctx.cleanup().await.expect("cleanup");}++#[tokio::test]+async fn a_target_attach_race_resolves_to_the_winner() {+ let h = MergeHarness::new().await;+ let winner = h.ctx.insert_person_with_distinct_id("race-winner").await;+ let source = h.ctx.insert_person_with_distinct_id("race-source").await;+ let racing = Arc::new(common::RacingStorage::new(h.ctx.storage.clone()));+ *racing.hijack_attach_to.lock().unwrap() = Some(winner);+ let service = h.service_with_storage(racing);++ let response = service+ .merge_persons(Request::new(rpc_request(+ h.ctx.team_id,+ "race-target",+ &["race-source"],+ Uuid::now_v7(),+ )))+ .await+ .expect("merge succeeds")+ .into_inner();++ // The concurrent mapping wins: the target distinct id belongs to the+ // winner, the winner is the survivor, and the resolved source still+ // folds into it through the saga.+ assert_eq!(response.survivor.as_ref().expect("survivor").id, winner);+ assert_eq!(+ rpc_outcomes(&response),+ vec![("race-source".to_string(), MergeSourceOutcome::Merged)]+ );+ assert_eq!(h.pdi_state("race-target").await, (winner, false, 1));+ let (source_deleted, _, _) = h.person_state(source).await;+ assert!(source_deleted);++ h.ctx.cleanup().await.expect("cleanup");+}++#[tokio::test]+async fn a_lost_stub_race_resolves_to_the_winner() {+ let h = MergeHarness::new().await;+ let racing = Arc::new(common::RacingStorage::new(h.ctx.storage.clone()));+ *racing.lose_create_race.lock().unwrap() = true;+ let service = h.service_with_storage(racing);++ let response = service+ .merge_persons(Request::new(rpc_request(+ h.ctx.team_id,+ "race-birth-target",+ &["race-birth-anon"],+ Uuid::now_v7(),+ )))+ .await+ .expect("merge succeeds")+ .into_inner();++ // The lost insert re-resolves to the concurrent winner — the same+ // person, born on the target distinct id's deterministic uuid — and+ // settlement continues against it.+ let survivor = response.survivor.as_ref().expect("survivor");+ assert_eq!(+ survivor.uuid,+ person_uuid(h.ctx.team_id, "race-birth-target").to_string()+ );+ assert_eq!(+ rpc_outcomes(&response),+ vec![("race-birth-anon".to_string(), MergeSourceOutcome::Attached)]+ );+ assert_eq!(+ h.pdi_state("race-birth-anon").await,+ (survivor.id, false, 1)+ );++ h.ctx.cleanup().await.expect("cleanup");+}++#[tokio::test]+async fn a_vanished_survivor_answers_unavailable_with_nothing_written() {+ let h = MergeHarness::new().await;+ let source = h+ .ctx+ .insert_person_with_distinct_id("race-vanish-source")+ .await;+ let racing = Arc::new(common::RacingStorage::new(h.ctx.storage.clone()));+ *racing.vanish_attach.lock().unwrap() = true;+ let service = h.service_with_storage(racing);++ let status = service+ .merge_persons(Request::new(rpc_request(+ h.ctx.team_id,+ "race-vanish-target",+ &["race-vanish-source"],+ Uuid::now_v7(),+ )))+ .await+ .expect_err("a vanished survivor fails the call");++ // Retryable, and nothing durable happened: the target distinct id is+ // still unmapped and the source person untouched.+ assert_eq!(status.code(), Code::Unavailable);+ let mapped: i64 = sqlx::query_scalar(+ "SELECT count(*) FROM posthog_persondistinctid WHERE team_id = $1 AND distinct_id = $2",+ )+ .bind(h.ctx.team_id as i32)+ .bind("race-vanish-target")+ .fetch_one(&h.ctx.pool)+ .await+ .unwrap();+ assert_eq!(mapped, 0);+ let (source_deleted, _, _) = h.person_state(source).await;+ assert!(!source_deleted);++ h.ctx.cleanup().await.expect("cleanup");+}