Skip to content

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

perf(personhog): renew lifecycle leases only when they run low (#111047)

Zach Brown069a411fd568
diff --git a/rust/personhog-identity/src/lifecycle/engine.rs b/rust/personhog-identity/src/lifecycle/engine.rs
index 77a815e70d09..65ae814c2ac3 100644
--- a/rust/personhog-identity/src/lifecycle/engine.rs
+++ b/rust/personhog-identity/src/lifecycle/engine.rs
@@ -41,13 +41,15 @@ const STEP_FAILURES_TOTAL: &str = "personhog_lifecycle_step_failures_total";
const OPS_PARKED_TOTAL: &str = "personhog_lifecycle_ops_parked_total";
const OPS_PARKED: &str = "personhog_lifecycle_ops_parked";
const STEP_DURATION_MS: &str = "personhog_lifecycle_step_duration_ms";
+const LEASES_LOST_TOTAL: &str = "personhog_lifecycle_leases_lost_total";
+const CLAIM_WAIT_MS: &str = "personhog_lifecycle_claim_wait_ms";
/// How many abandoned ops one sweep pass will pick up.
const SWEEP_BATCH_SIZE: i64 = 100;
-/// Pause before re-driving a step that lost a database conflict. Long
-/// enough for the competing statement (typically a writer flush) to finish;
-/// the execute deadline still bounds the total retry time.
+/// Pause before re-driving a step that lost a database conflict or its
+/// connection. Long enough for the competing statement (typically a writer
+/// flush) to finish; the execute deadline still bounds the total retry time.
const DB_CONFLICT_BACKOFF: Duration = Duration::from_millis(50);
pub type Tx<'a> = sqlx::Transaction<'a, sqlx::Postgres>;
@@ -105,6 +107,22 @@ impl SagaError {
matches!(db.code().as_deref(), Some("40P01" | "40001" | "57014"))
}
+ /// The connection broke (class 08) or the server shut down (57P01,
+ /// 57P02). A re-drive runs on a fresh connection, and the reloaded row
+ /// shows any commit the break hid.
+ pub fn is_db_connection_lost(&self) -> bool {
+ let SagaError::Db(err) = self else {
+ return false;
+ };
+ match err {
+ sqlx::Error::Io(_) | sqlx::Error::Tls(_) => true,
+ sqlx::Error::Database(db) => db
+ .code()
+ .is_some_and(|code| code.starts_with("08") || code == "57P01" || code == "57P02"),
+ _ => false,
+ }
+ }
+
/// The Postgres error detail for a database conflict. For a deadlock it
/// names the processes, lock targets, and relations in the cycle — the
/// only place that evidence surfaces when server-side error logging is
@@ -120,6 +138,9 @@ impl SagaError {
impl From<SagaError> for Status {
fn from(err: SagaError) -> Status {
+ if err.is_db_connection_lost() {
+ return Status::unavailable(format!("{err}; retry with the same op_id"));
+ }
match err {
SagaError::Db(e) => Status::internal(format!("database error: {e}")),
// A definitive refusal (the op_id belongs to a different
@@ -216,6 +237,26 @@ pub struct Engine {
tables: IdentityTables,
}
+/// Records a driver displaced from its op. Another driver can then repeat
+/// the step this one was on, so a climb for one step shows which step outlives
+/// the lease left at its start.
+fn lease_lost(row: &OpRow) {
+ tracing::warn!(
+ op_id = %row.op_id,
+ op_type = %row.op_type,
+ step = %row.step,
+ "lifecycle op driver lost its lease; going back to claiming"
+ );
+ common_metrics::inc(
+ LEASES_LOST_TOTAL,
+ &[
+ ("op_type".to_string(), row.op_type.clone()),
+ ("step".to_string(), row.step.clone()),
+ ],
+ 1,
+ );
+}
+
impl Engine {
pub fn new(pools: IdentityPools, config: EngineConfig, tables: IdentityTables) -> Self {
tables.validate().expect("invalid identity table set");
@@ -351,12 +392,15 @@ impl Engine {
op_id: Uuid,
wait_for_lease: bool,
) -> Result<OpRow, SagaError> {
- let deadline = tokio::time::Instant::now() + self.config.execute_timeout;
+ let drive_start = tokio::time::Instant::now();
+ let deadline = drive_start + self.config.execute_timeout;
// The attempt number returned by our claim, used as a fencing token:
// renew/release only touch the lease while `attempt` still matches,
// so a driver whose lease was stolen (the stealer bumped `attempt`)
// cannot extend or clear the stealer's lease.
let mut claim_attempt: Option<i32> = None;
+ // When our lease was last set, taken before the statement that set it so it errs early.
+ let mut lease_set_at = tokio::time::Instant::now();
loop {
let Some(row) = self.load(op_id).await? else {
@@ -402,12 +446,26 @@ impl Engine {
match claim_attempt {
Some(attempt) => {
- if !self.renew_lease(op_id, attempt).await? {
- // Another driver stole the lease; go back to
- // claiming instead of running a step we would lose.
+ // Only a claim bumps `attempt`, so the row just loaded
+ // shows a stolen lease without a write. Go back to
+ // claiming instead of running a step we would lose.
+ if row.attempt != attempt {
+ lease_lost(&row);
claim_attempt = None;
continue;
}
+ // Renewing only once a third of the lease has passed
+ // starts every step with at least two thirds of it; most
+ // ops finish inside the first third and never renew.
+ if lease_set_at.elapsed() >= self.config.lease / 3 {
+ let sent = tokio::time::Instant::now();
+ if !self.renew_lease(op_id, attempt).await? {
+ lease_lost(&row);
+ claim_attempt = None;
+ continue;
+ }
+ lease_set_at = sent;
+ }
}
None => {
// A live lease means the claim below cannot succeed, so
@@ -421,9 +479,17 @@ impl Engine {
self.poll_pause().await;
continue;
}
+ let sent = tokio::time::Instant::now();
match self.try_claim(op_id, wait_for_lease).await? {
Some(attempt) => {
claim_attempt = Some(attempt);
+ lease_set_at = sent;
+ // Includes polling behind another driver's lease.
+ common_metrics::histogram(
+ CLAIM_WAIT_MS,
+ &[("op_type".to_string(), row.op_type.clone())],
+ drive_start.elapsed().as_secs_f64() * 1000.0,
+ );
if attempt >= self.config.attempt_alert_threshold {
tracing::warn!(
op_id = %op_id,
@@ -457,6 +523,7 @@ impl Engine {
// retry noise. Alert on it — a wedged op can hold fences.
let kind = match &err {
SagaError::Db(_) if err.is_db_conflict() => "db_conflict",
+ SagaError::Db(_) if err.is_db_connection_lost() => "db_connection",
SagaError::Db(_) => "db",
SagaError::Leader(_) => "leader",
SagaError::LeaderRefused(_) => "leader_refused",
@@ -492,6 +559,17 @@ impl Engine {
tokio::time::sleep(DB_CONFLICT_BACKOFF).await;
continue;
}
+ if err.is_db_connection_lost() {
+ tracing::warn!(
+ op_id = %op_id,
+ op_type = %row.op_type,
+ step = %row.step,
+ error = %err,
+ "lifecycle step lost its database connection; retrying"
+ );
+ tokio::time::sleep(DB_CONFLICT_BACKOFF).await;
+ continue;
+ }
if let SagaError::LeaderRefused(status) = &err {
// Retrying a refusal cannot succeed, and the sweeper
// looping on it would hold this op's fences forever.
diff --git a/rust/personhog-identity/src/main.rs b/rust/personhog-identity/src/main.rs
index 1424701d4f2d..026a9fa4c985 100644
--- a/rust/personhog-identity/src/main.rs
+++ b/rust/personhog-identity/src/main.rs
@@ -183,8 +183,10 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
}),
)
.route("/_liveness", get(move || async move { liveness.check() }));
+ // Dense from 250ms to 5s, where merge tails sit.
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,
+ 1.0, 5.0, 10.0, 25.0, 50.0, 100.0, 250.0, 500.0, 750.0, 1000.0, 1500.0, 2000.0, 3000.0,
+ 5000.0, 10000.0, 30000.0,
];
// Lifecycle ops span "settled in one drive" (tens of ms) to
// "abandoned, parked, or leader-blocked and resumed by the sweeper"
diff --git a/rust/personhog-identity/src/service/merge.rs b/rust/personhog-identity/src/service/merge.rs
index faefaaefee8a..360266c7b70f 100644
--- a/rust/personhog-identity/src/service/merge.rs
+++ b/rust/personhog-identity/src/service/merge.rs
@@ -7,6 +7,7 @@
use std::collections::HashMap;
use std::sync::Arc;
+use std::time::Instant;
use chrono::{DateTime, Utc};
use personhog_common::persons::person_uuid;
@@ -37,6 +38,15 @@ const OUTCOME_SKIPPED_ILLEGAL: &str = "skipped_illegal";
const OUTCOME_ATTACHED: &str = "attached";
const MERGE_SOURCES_PER_CALL: &str = "personhog_identity_merge_sources_per_call";
+const MERGE_PHASE_DURATION: &str = "personhog_identity_merge_phase_duration_ms";
+
+fn record_phase(phase: &'static str, start: Instant) {
+ common_metrics::histogram(
+ MERGE_PHASE_DURATION,
+ &[("phase".to_string(), phase.to_string())],
+ start.elapsed().as_secs_f64() * 1000.0,
+ );
+}
const PAYLOAD_NUL_SANITIZED_TOTAL: &str = "personhog_identity_merge_payload_nul_sanitized_total";
const PAYLOAD_NUMBERS_CLAMPED_TOTAL: &str =
"personhog_identity_merge_payload_numbers_clamped_total";
@@ -98,6 +108,7 @@ impl MergeEntrance {
// classify divergently and the insert loser then sees the engine's
// full-request mismatch; that surfaces as retryable UNAVAILABLE
// (see MergeOpExecutor::execute) and the retry attaches here.
+ let start = Instant::now();
let mut existing = self.ops.find(op_id).await?;
// A claim abort is disposable; checked before the request
// comparison so any request may reuse the id once it is gone.
@@ -107,6 +118,7 @@ impl MergeEntrance {
existing = None;
}
}
+ record_phase("lookup", start);
if let Some(row) = existing {
if row.op_type != OP_TYPE_MERGE
|| row.team_id != request.team_id
@@ -118,8 +130,12 @@ impl MergeEntrance {
));
}
let frozen = row.request.clone();
+ let start = Instant::now();
let row = self.ops.execute(op_id, row.team_id, &frozen).await?;
+ record_phase("saga", start);
+ let start = Instant::now();
let delivered = self.deliver_aborted_writes(&request, &row).await?;
+ record_phase("deliver", start);
// Drives the recorded op with its own frozen request, never
// reclassified; properties apply only where the op aborted.
return merge_response(&row, delivered);
@@ -143,16 +159,23 @@ impl MergeEntrance {
keys.push((request.team_id, did.clone()));
}
}
+ let start = Instant::now();
let resolved = self
.storage
.resolve_distinct_ids(&keys)
.await
.map_err(|e| Status::internal(format!("resolution failed: {e}")))?;
+ record_phase("resolve", start);
let target_key = (request.team_id, request.target_distinct_id.clone());
let (target_person, target_was_born) = match resolved.get(&target_key) {
Some(target) => (target.clone(), false),
- None => self.establish_target(&request, &resolved).await?,
+ None => {
+ let start = Instant::now();
+ let established = self.establish_target(&request, &resolved).await?;
+ record_phase("establish", start);
+ established
+ }
};
let mut attach: Vec<String> = Vec::new();
@@ -180,11 +203,13 @@ impl MergeEntrance {
// and attach is a retryable conflict, unless it landed on the
// target anyway.
if !attach.is_empty() {
+ let start = Instant::now();
let attached = self
.storage
.attach_distinct_ids(request.team_id, target_person.id, &attach)
.await
.map_err(|e| Status::internal(format!("attach failed: {e}")))?;
+ record_phase("attach", start);
for did in attach {
let outcome = match attached.get(&did) {
Some(AttachOutcome::Attached { .. }) => OUTCOME_ATTACHED,
@@ -231,9 +256,11 @@ impl MergeEntrance {
let flip_identified = inline_results
.values()
.any(|o| o == OUTCOME_ATTACHED || o == OUTCOME_NOOP_SAME_PERSON);
+ let start = Instant::now();
let pushed = self
.push_event_properties(&request, &target_person, flip_identified, target_was_born)
.await?;
+ record_phase("push", start);
let results = request
.sources
.iter()
@@ -277,8 +304,12 @@ impl MergeEntrance {
frozen["inline_results"] = serde_json::to_value(&inline_results)
.map_err(|e| Status::internal(format!("failed to freeze inline results: {e}")))?;
+ let start = Instant::now();
let row = self.ops.execute(op_id, request.team_id, &frozen).await?;
+ record_phase("saga", start);
+ let start = Instant::now();
let delivered = self.deliver_aborted_writes(&request, &row).await?;
+ record_phase("deliver", start);
merge_response(&row, delivered)
}
@@ -397,20 +428,24 @@ impl MergeEntrance {
) -> Result<(Person, bool), 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 decide in request order, as one-at-a-time identifies would:
+ // the first eligible source survives if it has a person, and a
+ // personless one births the target. An identified source is skipped
+ // unless allowed, so the saga still refuses it rather than aliasing
+ // the target onto it.
+ let first_eligible = 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 {
+ .filter(|s| {
+ !is_distinct_id_illegal(&s.source_distinct_id)
+ && !is_distinct_id_oversized(&s.source_distinct_id)
+ })
+ .map(|s| resolved.get(&(request.team_id, s.source_distinct_id.clone())))
+ .find(|person| {
+ person.is_none_or(|p| request.allow_identified_sources || !p.is_identified)
+ })
+ .flatten();
+ if let Some(survivor) = first_eligible {
let attached = self
.storage
.attach_distinct_ids(
diff --git a/rust/personhog-identity/tests/lifecycle_engine_tests.rs b/rust/personhog-identity/tests/lifecycle_engine_tests.rs
index 50fa3c3c5e59..253a9314d50f 100644
--- a/rust/personhog-identity/tests/lifecycle_engine_tests.rs
+++ b/rust/personhog-identity/tests/lifecycle_engine_tests.rs
@@ -451,7 +451,7 @@ async fn lease_is_live(pool: &PgPool, op_id: Uuid) -> bool {
/// Driver whose first step gets its lease stolen mid-run. `fail_after_steal`
/// picks the exit: Err exercises the engine's release path, Ok without
-/// advancing (a lost CAS) exercises the renew path.
+/// advancing (a lost CAS) exercises the attempt check on the reloaded row.
struct StolenLeaseDriver {
steps_run: AtomicUsize,
fail_after_steal: bool,
@@ -517,6 +517,107 @@ async fn a_driver_whose_lease_was_stolen_stops_running_steps_instead_of_renewing
ctx.cleanup().await.expect("cleanup");
}
+/// The two-step dummy op, recording the op's lease expiry as each step
+/// starts and pausing its first step for `first_step_pause`.
+struct LeaseRecordingDriver {
+ inner: DummyDriver,
+ first_step_pause: std::time::Duration,
+ expiries: std::sync::Mutex<Vec<chrono::DateTime<chrono::Utc>>>,
+}
+
+#[async_trait]
+impl OpDriver for LeaseRecordingDriver {
+ fn op_type(&self) -> &'static str {
+ "merge"
+ }
+
+ fn initial_step(&self) -> &'static str {
+ "started"
+ }
+
+ async fn run_step(&self, pools: &IdentityPools, op: &OpRow) -> Result<(), SagaError> {
+ let expiry: chrono::DateTime<chrono::Utc> =
+ sqlx::query_scalar("SELECT lease_expires_at FROM lifecycle_op WHERE op_id = $1")
+ .bind(op.op_id)
+ .fetch_one(pools.fast())
+ .await
+ .map_err(SagaError::Db)?;
+ self.expiries.lock().unwrap().push(expiry);
+ if op.step == "started" {
+ tokio::time::sleep(self.first_step_pause).await;
+ }
+ self.inner.run_step(pools, op).await
+ }
+}
+
+/// Lease expiries seen by the dummy op's two steps under a `lease`-long lease.
+async fn step_lease_expiries(
+ ctx: &TestContext,
+ lease: std::time::Duration,
+ first_step_pause: std::time::Duration,
+) -> Vec<chrono::DateTime<chrono::Utc>> {
+ let driver = LeaseRecordingDriver {
+ inner: DummyDriver::new(),
+ first_step_pause,
+ expiries: std::sync::Mutex::new(Vec::new()),
+ };
+ let engine = personhog_identity::lifecycle::engine::Engine::new(
+ ctx.pools.clone(),
+ personhog_identity::lifecycle::engine::EngineConfig {
+ lease,
+ execute_timeout: std::time::Duration::from_secs(10),
+ poll_interval: std::time::Duration::from_millis(25),
+ attempt_alert_threshold: 5,
+ gc_batch_limit: 10_000,
+ },
+ ctx.tables.clone(),
+ );
+ engine
+ .execute(&driver, Uuid::now_v7(), ctx.team_id, &json!({}))
+ .await
+ .expect("the op completes");
+ assert_eq!(driver.inner.steps_run.load(Ordering::SeqCst), 2);
+ driver.expiries.into_inner().unwrap()
+}
+
+#[tokio::test]
+async fn steps_that_finish_inside_a_third_of_the_lease_run_on_the_claim_without_renewing() {
+ let ctx = TestContext::new().await;
+
+ let expiries = step_lease_expiries(
+ &ctx,
+ std::time::Duration::from_secs(30),
+ std::time::Duration::ZERO,
+ )
+ .await;
+
+ assert_eq!(
+ expiries[0], expiries[1],
+ "the second step ran on the claim's lease"
+ );
+
+ ctx.cleanup().await.expect("cleanup");
+}
+
+#[tokio::test]
+async fn a_step_that_starts_after_a_third_of_the_lease_renews_it_first() {
+ let ctx = TestContext::new().await;
+
+ let expiries = step_lease_expiries(
+ &ctx,
+ std::time::Duration::from_secs(3),
+ std::time::Duration::from_millis(1_200),
+ )
+ .await;
+
+ assert!(
+ expiries[1] > expiries[0],
+ "the second step ran on a renewed lease"
+ );
+
+ ctx.cleanup().await.expect("cleanup");
+}
+
#[tokio::test]
async fn a_failing_driver_whose_lease_was_stolen_does_not_release_the_stealers_lease() {
let ctx = TestContext::new().await;
@@ -814,14 +915,46 @@ fn database_conflicts_classify_as_retriable() {
assert!(!SagaError::Busy.is_db_conflict());
}
-/// Driver whose first attempts lose a deadlock; every later attempt
+fn connection_lost() -> SagaError {
+ SagaError::Db(sqlx::Error::Io(std::io::Error::new(
+ std::io::ErrorKind::UnexpectedEof,
+ "expected to read 5 bytes, got 0 bytes at EOF",
+ )))
+}
+
+#[test]
+fn lost_connections_classify_as_retriable_and_unavailable() {
+ for err in [
+ connection_lost(),
+ db_error("08006"),
+ db_error("57P01"),
+ db_error("57P02"),
+ ] {
+ assert!(
+ err.is_db_connection_lost(),
+ "{err} must be a lost connection"
+ );
+ assert!(!err.is_db_conflict());
+ assert_eq!(tonic::Status::from(err).code(), tonic::Code::Unavailable);
+ }
+ for err in [db_error("23505"), db_error("40P01"), SagaError::Busy] {
+ assert!(
+ !err.is_db_connection_lost(),
+ "{err} is not a lost connection"
+ );
+ }
+}
+
+type FailStep = fn() -> SagaError;
+
+/// Driver whose first attempts fail with `error`; every later attempt
/// behaves like [`DummyDriver`]. Failing more than once exercises the
-/// repeated backoff-and-renew passes of the retry loop, not just the
-/// first.
+/// repeated backoff passes of the retry loop, not just the first.
struct DeadlockingDriver {
inner: DummyDriver,
fail_first: usize,
attempts: AtomicUsize,
+ error: FailStep,
}
#[async_trait]
@@ -836,37 +969,47 @@ impl OpDriver for DeadlockingDriver {
async fn run_step(&self, pools: &IdentityPools, op: &OpRow) -> Result<(), SagaError> {
if self.attempts.fetch_add(1, Ordering::SeqCst) < self.fail_first {
- return Err(db_error("40P01"));
+ return Err((self.error)());
}
self.inner.run_step(pools, op).await
}
}
#[tokio::test]
-async fn a_step_that_loses_a_database_conflict_is_retried_not_surfaced() {
+async fn a_step_that_loses_a_database_conflict_or_its_connection_is_retried_not_surfaced() {
let ctx = TestContext::new().await;
let engine = ctx.engine();
- let driver = DeadlockingDriver {
- inner: DummyDriver::new(),
- fail_first: 3,
- attempts: AtomicUsize::new(0),
- };
- let op_id = Uuid::now_v7();
-
- let row = engine
- .execute(&driver, op_id, ctx.team_id, &json!({"work": 1}))
- .await
- .expect("the conflict is retried inside the engine, not surfaced");
+ let failures: [(&str, FailStep); 2] = [
+ ("deadlock", || db_error("40P01")),
+ ("lost connection", connection_lost),
+ ];
+ for (name, error) in failures {
+ let driver = DeadlockingDriver {
+ inner: DummyDriver::new(),
+ fail_first: 3,
+ attempts: AtomicUsize::new(0),
+ error,
+ };
+ let op_id = Uuid::now_v7();
- assert_eq!(row.step, STEP_COMPLETED);
- assert_eq!(
- driver.inner.steps_run.load(Ordering::SeqCst),
- 2,
- "both real steps ran after the deadlocked attempts"
- );
- let (_, attempt, _, completed) = op_row(&ctx, op_id).await;
- assert!(completed);
- assert_eq!(attempt, 1, "the retry re-drives under the original claim");
+ let row = engine
+ .execute(&driver, op_id, ctx.team_id, &json!({"work": 1}))
+ .await
+ .unwrap_or_else(|err| panic!("{name}: retried inside the engine, not surfaced: {err}"));
+
+ assert_eq!(row.step, STEP_COMPLETED, "{name}");
+ assert_eq!(
+ driver.inner.steps_run.load(Ordering::SeqCst),
+ 2,
+ "{name}: both real steps ran after the failed attempts"
+ );
+ let (_, attempt, _, completed) = op_row(&ctx, op_id).await;
+ assert!(completed, "{name}");
+ assert_eq!(
+ attempt, 1,
+ "{name}: the retry re-drives under the original claim"
+ );
+ }
ctx.cleanup().await.expect("cleanup");
}
diff --git a/rust/personhog-identity/tests/lifecycle_merge_tests.rs b/rust/personhog-identity/tests/lifecycle_merge_tests.rs
index 0b1b82a066f9..9e047836243f 100644
--- a/rust/personhog-identity/tests/lifecycle_merge_tests.rs
+++ b/rust/personhog-identity/tests/lifecycle_merge_tests.rs
@@ -2288,10 +2288,10 @@ async fn invalid_merge_requests_are_rejected_before_any_work() {
}
#[tokio::test]
-async fn an_unresolved_target_attaches_to_the_first_resolved_sources_person() {
+async fn an_unresolved_target_with_a_personless_first_source_is_born_and_absorbs_the_rest() {
let h = MergeHarness::new().await;
let service = h.service();
- let survivor = h.ctx.insert_person_with_distinct_id("flip-source").await;
+ let source = h.ctx.insert_person_with_distinct_id("flip-source").await;
let response = service
.merge_persons(Request::new(rpc_request(
@@ -2301,35 +2301,28 @@ async fn an_unresolved_target_attaches_to_the_first_resolved_sources_person() {
Uuid::now_v7(),
)))
.await
- .expect("target attach succeeds")
+ .expect("merge succeeds")
.into_inner();
+ // As one-at-a-time identifies would: the first pair births the target,
+ // and the second merges its person into it.
+ let survivor = response.survivor.as_ref().expect("survivor present");
assert_eq!(
- response.survivor.as_ref().expect("survivor present").id,
- survivor
+ survivor.uuid,
+ person_uuid(h.ctx.team_id, "flip-target").to_string()
);
assert_eq!(
rpc_outcomes(&response),
vec![
("flip-personless".to_string(), MergeSourceOutcome::Attached),
- (
- "flip-source".to_string(),
- MergeSourceOutcome::NoopSamePerson
- ),
+ ("flip-source".to_string(), MergeSourceOutcome::Merged),
]
);
- // 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),
- }]
- );
+ assert_eq!(h.pdi_state("flip-target").await.0, survivor.id);
+ assert_eq!(h.pdi_state("flip-personless").await.0, survivor.id);
+ assert_eq!(h.pdi_state("flip-source").await.0, survivor.id);
+ let (source_deleted, _, _) = h.person_state(source).await;
+ assert!(source_deleted);
h.ctx.cleanup().await.expect("cleanup");
}