: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
fix(personhog): keep a merge saga running when its caller hangs up (#117460)
Nick Best6a1b9383710f
diff --git a/rust/Cargo.lock b/rust/Cargo.lockindex 829647b85700..4999aaf5673a 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -8939,6 +8939,7 @@ dependencies = ["envconfig","futures","lifecycle",+ "metrics","metrics-exporter-prometheus","personhog-common","personhog-coordination",@@ -8949,6 +8950,7 @@ dependencies = ["sqlx","thiserror 2.0.18","tokio",+ "tokio-util","tonic 0.12.3","tracing","tracing-subscriber",diff --git a/rust/personhog-identity/Cargo.toml b/rust/personhog-identity/Cargo.tomlindex d30bed8ef304..08a41c7c6670 100644--- a/rust/personhog-identity/Cargo.toml+++ b/rust/personhog-identity/Cargo.toml@@ -20,6 +20,7 @@ axum = { workspace = true }chrono = { workspace = true }envconfig = { workspace = true }futures = { workspace = true }+metrics = { workspace = true }metrics-exporter-prometheus = { workspace = true }rand = { workspace = true }serde = { workspace = true }@@ -27,6 +28,7 @@ serde_json = { workspace = true }sqlx = { workspace = true }thiserror = { workspace = true }tokio = { workspace = true }+tokio-util = { workspace = true, features = ["rt"] }tonic = { workspace = true }tracing = { workspace = true }tracing-subscriber = { workspace = true }diff --git a/rust/personhog-identity/src/config.rs b/rust/personhog-identity/src/config.rsindex 831447919c53..968af54b5609 100644--- a/rust/personhog-identity/src/config.rs+++ b/rust/personhog-identity/src/config.rs@@ -201,6 +201,11 @@ pub struct Config {#[envconfig(default = "5")]pub lifecycle_attempt_alert_threshold: i32,+ /// Merge saga drives allowed to outlive a caller that hangs up; past this+ /// many a drive runs inline and stops with its caller. 0 disables.+ #[envconfig(default = "256")]+ pub lifecycle_detached_drive_limit: usize,+/// Run the sweeper + GC loop for abandoned lifecycle ops; the lease/// arbitrates, so any number of instances may run it.#[envconfig(default = "true")]diff --git a/rust/personhog-identity/src/lifecycle/detach.rs b/rust/personhog-identity/src/lifecycle/detach.rsnew file mode 100644index 000000000000..1ee36f5bfb3d--- /dev/null+++ b/rust/personhog-identity/src/lifecycle/detach.rs@@ -0,0 +1,283 @@+use std::future::Future;+use std::sync::Arc;++use personhog_common::grpc::{+ current_caller_tag, current_client_name, current_method_name, CALLER_TAG, CLIENT_NAME,+ METHOD_NAME,+};+use tokio::sync::Semaphore;+use tokio::task::JoinError;+use tokio_util::task::TaskTracker;+use tracing::Instrument;++const DRIVES_TOTAL: &str = "personhog_lifecycle_detached_drives_total";+const DRIVES_IN_FLIGHT: &str = "personhog_lifecycle_detached_drives_in_flight";++#[derive(Clone)]+pub struct DetachedDrives {+ tracker: TaskTracker,+ permits: Arc<Semaphore>,+}++struct InFlight;++impl InFlight {+ fn new() -> Self {+ metrics::gauge!(DRIVES_IN_FLIGHT).increment(1.0);+ Self+ }+}++impl Drop for InFlight {+ fn drop(&mut self) {+ metrics::gauge!(DRIVES_IN_FLIGHT).decrement(1.0);+ }+}++impl DetachedDrives {+ pub fn new(limit: usize) -> Self {+ Self {+ tracker: TaskTracker::new(),+ permits: Arc::new(Semaphore::new(limit)),+ }+ }++ pub async fn run<F, T>(&self, drive: F) -> Result<T, JoinError>+ where+ F: Future<Output = T> + Send + 'static,+ T: Send + 'static,+ {+ let Ok(permit) = self.permits.clone().try_acquire_owned() else {+ common_metrics::inc(+ DRIVES_TOTAL,+ &[("mode".to_string(), "inline".to_string())],+ 1,+ );+ return Ok(drive.await);+ };+ common_metrics::inc(+ DRIVES_TOTAL,+ &[("mode".to_string(), "detached".to_string())],+ 1,+ );+ let in_flight = InFlight::new();+ let task = async move {+ let _permit = permit;+ let _in_flight = in_flight;+ drive.await+ };+ let task = CLIENT_NAME.scope(+ current_client_name(),+ CALLER_TAG.scope(+ current_caller_tag(),+ METHOD_NAME.scope(current_method_name(), task),+ ),+ );+ self.tracker+ .spawn(task.instrument(tracing::Span::current()))+ .await+ }++ pub fn in_flight(&self) -> usize {+ self.tracker.len()+ }++ pub fn free_slots(&self) -> usize {+ self.permits.available_permits()+ }++ pub async fn shutdown(&self) {+ self.tracker.close();+ self.tracker.wait().await;+ }+}++#[cfg(test)]+mod tests {+ use std::sync::atomic::{AtomicBool, Ordering};+ use std::sync::Arc;+ use std::time::Duration;++ use tokio::sync::oneshot;+ use tokio::time::timeout;++ use super::DetachedDrives;+ use personhog_common::grpc::{+ current_client_name, current_method_name, CLIENT_NAME, METHOD_NAME,+ };++ fn flag_after(+ flag: &Arc<AtomicBool>,+ delay: Duration,+ ) -> impl std::future::Future<Output = ()> {+ let flag = flag.clone();+ async move {+ tokio::time::sleep(delay).await;+ flag.store(true, Ordering::SeqCst);+ }+ }++ async fn wait_for(flag: &AtomicBool) -> bool {+ for _ in 0..200 {+ if flag.load(Ordering::SeqCst) {+ return true;+ }+ tokio::time::sleep(Duration::from_millis(5)).await;+ }+ false+ }++ #[tokio::test]+ async fn a_dropped_caller_leaves_the_drive_running() {+ let drives = DetachedDrives::new(4);+ let done = Arc::new(AtomicBool::new(false));++ let dropped = timeout(+ Duration::from_millis(1),+ drives.run(flag_after(&done, Duration::from_millis(50))),+ )+ .await;+ assert!(+ dropped.is_err(),+ "the caller gave up before the drive finished"+ );+ assert_eq!(drives.in_flight(), 1);++ assert!(+ wait_for(&done).await,+ "the drive finished without its caller"+ );+ tokio::time::sleep(Duration::from_millis(5)).await;+ assert_eq!(drives.in_flight(), 0);+ assert_eq!(drives.free_slots(), 4);+ }++ #[tokio::test]+ async fn a_drive_past_the_cap_runs_inline_and_dies_with_its_caller() {+ let drives = DetachedDrives::new(1);+ let (release, held) = oneshot::channel::<()>();+ let first = Arc::new(AtomicBool::new(false));+ let first_flag = first.clone();+ let hung_up = timeout(+ Duration::from_millis(1),+ drives.run(async move {+ let _ = held.await;+ first_flag.store(true, Ordering::SeqCst);+ }),+ )+ .await;+ assert!(hung_up.is_err());+ assert_eq!(drives.free_slots(), 0);++ let second = Arc::new(AtomicBool::new(false));+ let dropped = timeout(+ Duration::from_millis(1),+ drives.run(flag_after(&second, Duration::from_millis(20))),+ )+ .await;+ assert!(dropped.is_err());+ tokio::time::sleep(Duration::from_millis(60)).await;+ assert!(+ !second.load(Ordering::SeqCst),+ "an inline drive stops when its caller drops"+ );++ release.send(()).expect("the first drive is still waiting");+ assert!(wait_for(&first).await);+ assert_eq!(drives.free_slots(), 1);+ }++ #[tokio::test]+ async fn a_detached_drive_keeps_the_requests_metric_attribution() {+ let drives = DetachedDrives::new(4);+ let seen = CLIENT_NAME+ .scope(+ Arc::from("router"),+ METHOD_NAME.scope(+ Arc::from("MergePersons"),+ drives.run(async { (current_client_name(), current_method_name()) }),+ ),+ )+ .await+ .expect("the drive joins");+ assert_eq!(&*seen.0, "router");+ assert_eq!(&*seen.1, "MergePersons");+ }++ #[tokio::test]+ async fn a_limit_of_zero_never_detaches() {+ let drives = DetachedDrives::new(0);+ let value = drives+ .run(async { 7 })+ .await+ .expect("inline drives cannot fail to join");+ assert_eq!(value, 7);+ assert_eq!(drives.in_flight(), 0);+ }++ #[tokio::test]+ async fn a_panicking_drive_surfaces_as_an_error_and_frees_its_slot() {+ let drives = DetachedDrives::new(1);+ let err = drives+ .run(async { panic!("step blew up") })+ .await+ .expect_err("the panic reaches the caller");+ assert!(err.is_panic());+ assert_eq!(drives.free_slots(), 1);++ let value = drives+ .run(async { 3 })+ .await+ .expect("the slot is usable again");+ assert_eq!(value, 3);+ }++ #[tokio::test]+ async fn shutdown_waits_for_detached_drives_to_finish() {+ let drives = DetachedDrives::new(4);+ let done = Arc::new(AtomicBool::new(false));+ let hung_up = timeout(+ Duration::from_millis(1),+ drives.run(flag_after(&done, Duration::from_millis(50))),+ )+ .await;+ assert!(hung_up.is_err());++ drives.shutdown().await;+ assert!(+ done.load(Ordering::SeqCst),+ "shutdown returned before the drive finished"+ );+ assert_eq!(drives.in_flight(), 0);+ }++ #[tokio::test]+ async fn a_drive_started_while_shutdown_is_draining_is_waited_for_too() {+ let drives = DetachedDrives::new(4);+ let first = Arc::new(AtomicBool::new(false));+ let second = Arc::new(AtomicBool::new(false));+ let hung_up = timeout(+ Duration::from_millis(1),+ drives.run(flag_after(&first, Duration::from_millis(80))),+ )+ .await;+ assert!(hung_up.is_err());++ let shutdown = {+ let drives = drives.clone();+ tokio::spawn(async move { drives.shutdown().await })+ };+ tokio::task::yield_now().await;+ let hung_up = timeout(+ Duration::from_millis(1),+ drives.run(flag_after(&second, Duration::from_millis(40))),+ )+ .await;+ assert!(hung_up.is_err());++ shutdown.await.expect("shutdown task completes");+ assert!(first.load(Ordering::SeqCst));+ assert!(second.load(Ordering::SeqCst));+ assert_eq!(drives.in_flight(), 0);+ }+}diff --git a/rust/personhog-identity/src/lifecycle/engine.rs b/rust/personhog-identity/src/lifecycle/engine.rsindex 5befd3720a81..01b030627df7 100644--- a/rust/personhog-identity/src/lifecycle/engine.rs+++ b/rust/personhog-identity/src/lifecycle/engine.rs@@ -286,10 +286,48 @@ impl Engine {op_id: Uuid,team_id: i64,request: &Value,+ ) -> Result<OpRow, SagaError> {+ self.execute_by(driver, op_id, team_id, request, self.execute_deadline())+ .await+ }++ pub fn execute_deadline(&self) -> tokio::time::Instant {+ tokio::time::Instant::now() + self.config.execute_timeout+ }++ pub async fn execute_by(+ &self,+ driver: &dyn OpDriver,+ op_id: Uuid,+ team_id: i64,+ request: &Value,+ deadline: tokio::time::Instant,) -> Result<OpRow, SagaError> {self.create_or_attach(driver, op_id, team_id, request).await?;- self.drive(driver, op_id, true).await+ self.drive(driver, op_id, true, deadline).await+ }++ pub async fn wait_for_lease_lapse(+ &self,+ op_id: Uuid,+ deadline: tokio::time::Instant,+ ) -> Result<bool, SagaError> {+ loop {+ let Some(row) = self.load(op_id).await? else {+ return Ok(false);+ };+ if row.completed_at.is_some() {+ return Ok(true);+ }+ if !row.lease_live {+ return Ok(false);+ }+ if tokio::time::Instant::now() >= deadline {+ return Err(SagaError::Busy);+ }+ self.poll_pause().await;+ }}/// The create-or-attach half of [`execute`], without driving: create@@ -383,7 +421,8 @@ impl Engine {/// sweeper a live lease means "not abandoned", so this bails with `Busy`/// instead of polling out the execute timeout.pub async fn resume(&self, driver: &dyn OpDriver, op_id: Uuid) -> Result<OpRow, SagaError> {- self.drive(driver, op_id, false).await+ self.drive(driver, op_id, false, self.execute_deadline())+ .await}async fn drive(@@ -391,9 +430,9 @@ impl Engine {driver: &dyn OpDriver,op_id: Uuid,wait_for_lease: bool,+ deadline: tokio::time::Instant,) -> Result<OpRow, SagaError> {- let drive_start = tokio::time::Instant::now();- let deadline = drive_start + self.config.execute_timeout;+ let drive_start = deadline - 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`)diff --git a/rust/personhog-identity/src/lifecycle/merge.rs b/rust/personhog-identity/src/lifecycle/merge.rsindex 01d826c304b6..d1f9798e7289 100644--- a/rust/personhog-identity/src/lifecycle/merge.rs+++ b/rust/personhog-identity/src/lifecycle/merge.rs@@ -50,6 +50,7 @@ use personhog_proto::personhog::types::v1::{use crate::config::IdentityTables;use crate::leader::LifecycleLeader;+use crate::lifecycle::detach::DetachedDrives;use crate::lifecycle::engine::{advance_step_in_tx, complete_op_in_tx, Engine, OpDriver, OpRow, SagaError, Tx, STEP_ABORTED,STEP_COMPLETED,@@ -378,12 +379,17 @@ impl MergeDriver {/// put the wire.pub struct MergeOpExecutor {engine: Arc<Engine>,- driver: MergeDriver,+ driver: Arc<MergeDriver>,+ drives: DetachedDrives,}impl MergeOpExecutor {- pub fn new(engine: Arc<Engine>, driver: MergeDriver) -> Self {- Self { engine, driver }+ pub fn new(engine: Arc<Engine>, driver: MergeDriver, drives: DetachedDrives) -> Self {+ Self {+ engine,+ driver: Arc::new(driver),+ drives,+ }}/// The op row for this id, if one exists.@@ -449,7 +455,8 @@ impl MergeOpExecutor {}/// 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.+ /// row's own request, or a freshly frozen one) and return the row. The+ /// drive outlives a caller that hangs up: see [`DetachedDrives`].// See `find` for why result_large_err is allowed.#[allow(clippy::result_large_err)]pub async fn execute(@@ -458,27 +465,44 @@ impl MergeOpExecutor {team_id: i64,frozen: &Value,) -> Result<OpRow, Status> {- self.engine- .execute(&self.driver, op_id, team_id, frozen)- .await- .map_err(|err| {- // The entrance only reaches this create path after finding- // no op row, so an engine-level mismatch means the row- // appeared in the race window since — a transient loss,- // not op_id misuse (which the entrance's attach-first- // comparison answers). Both client stacks treat- // FAILED_PRECONDITION as terminal, so surfacing the race- // as one would fail a request whose retry attaches fine.- if matches!(err, SagaError::RequestMismatch(_)) {- return Status::unavailable(format!(- "another call is initializing op {op_id}; retry with the same op_id"- ));- }- if matches!(err, SagaError::Db(_) | SagaError::CorruptState(_)) {- tracing::error!(op_id = %op_id, error = %err, "MergePersons failed");- }- Status::from(err)- })+ let engine = self.engine.clone();+ let driver = self.driver.clone();+ let frozen = frozen.clone();+ let deadline = engine.execute_deadline();+ let terminal = engine.wait_for_lease_lapse(op_id, deadline).await;+ let drive = async move {+ engine+ .execute_by(driver.as_ref(), op_id, team_id, &frozen, deadline)+ .await+ .inspect_err(|err| {+ if matches!(err, SagaError::Db(_) | SagaError::CorruptState(_)) {+ tracing::error!(op_id = %op_id, error = %err, "MergePersons failed");+ }+ })+ };+ let driven = match terminal {+ Ok(true) => drive.await,+ Ok(false) => self.drives.run(drive).await.map_err(|err| {+ tracing::error!(op_id = %op_id, error = %err, "MergePersons drive task died");+ Status::internal(format!("merge op {op_id} drive task died: {err}"))+ })?,+ Err(err) => Err(err),+ };+ driven.map_err(|err| {+ // The entrance only reaches this create path after finding+ // no op row, so an engine-level mismatch means the row+ // appeared in the race window since — a transient loss,+ // not op_id misuse (which the entrance's attach-first+ // comparison answers). Both client stacks treat+ // FAILED_PRECONDITION as terminal, so surfacing the race+ // as one would fail a request whose retry attaches fine.+ if matches!(err, SagaError::RequestMismatch(_)) {+ return Status::unavailable(format!(+ "another call is initializing op {op_id}; retry with the same op_id"+ ));+ }+ Status::from(err)+ })}}diff --git a/rust/personhog-identity/src/lifecycle/mod.rs b/rust/personhog-identity/src/lifecycle/mod.rsindex fa06096a5434..9d364f150d65 100644--- a/rust/personhog-identity/src/lifecycle/mod.rs+++ b/rust/personhog-identity/src/lifecycle/mod.rs@@ -8,6 +8,7 @@//! step handlers.pub mod delete;+pub mod detach;pub mod engine;pub(crate) mod leader_calls;pub mod merge;diff --git a/rust/personhog-identity/src/main.rs b/rust/personhog-identity/src/main.rsindex 279f86f21bc9..f38eac84fcc6 100644--- a/rust/personhog-identity/src/main.rs+++ b/rust/personhog-identity/src/main.rs@@ -26,6 +26,7 @@ use personhog_coordination::store::PersonhogStore;use personhog_identity::config::Config;use personhog_identity::leader::LifecycleLeader;use personhog_identity::lifecycle::delete::DeleteDriver;+use personhog_identity::lifecycle::detach::DetachedDrives;use personhog_identity::lifecycle::engine::Engine;use personhog_identity::lifecycle::merge::{MergeDriver, MergeOpExecutor};use personhog_identity::lifecycle::PersonHogLifecycleService;@@ -333,6 +334,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {});}+ let detached_drives = DetachedDrives::new(config.lifecycle_detached_drive_limit);// Separate proto service co-served on the same server so lifecycle// callers are insulated from any future split.let merge_entrance = MergeEntrance::new(@@ -346,6 +348,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {config.tables(),config.lifecycle_leader_call_concurrency,),+ detached_drives.clone(),),);let lifecycle_service = PersonHogLifecycleService::new(@@ -424,6 +427,11 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {{grpc_handle.signal_failure(format!("gRPC server error: {e}"));}+ tracing::info!(+ in_flight = detached_drives.in_flight(),+ "waiting for detached merge drives before exit"+ );+ detached_drives.shutdown().await;});monitor.wait().await?;diff --git a/rust/personhog-identity/tests/lifecycle_engine_tests.rs b/rust/personhog-identity/tests/lifecycle_engine_tests.rsindex 253a9314d50f..3bab3e308b9f 100644--- a/rust/personhog-identity/tests/lifecycle_engine_tests.rs+++ b/rust/personhog-identity/tests/lifecycle_engine_tests.rs@@ -22,6 +22,7 @@ use sqlx::postgres::PgPool;use uuid::Uuid;use personhog_common::grpc::semantic_refusal;+use personhog_identity::lifecycle::detach::DetachedDrives;use personhog_identity::lifecycle::engine::{advance_step_in_tx, complete_op_in_tx, OpDriver, OpRow, SagaError, STEP_COMPLETED,};@@ -31,12 +32,18 @@ use personhog_identity::pools::IdentityPools;/// so tests can prove what did (or did not) re-run.struct DummyDriver {steps_run: AtomicUsize,+ pause: std::time::Duration,}impl DummyDriver {fn new() -> Self {+ Self::paced(std::time::Duration::ZERO)+ }++ fn paced(pause: std::time::Duration) -> Self {Self {steps_run: AtomicUsize::new(0),+ pause,}}}@@ -53,6 +60,7 @@ impl OpDriver for DummyDriver {async fn run_step(&self, pools: &IdentityPools, op: &OpRow) -> Result<(), SagaError> {self.steps_run.fetch_add(1, Ordering::SeqCst);+ tokio::time::sleep(self.pause).await;let mut tx = pools.heavy().begin().await.map_err(SagaError::Db)?;let advanced = match op.step.as_str() {"started" => {@@ -1051,3 +1059,250 @@ async fn a_claim_skips_a_row_a_concurrent_writer_holds_instead_of_queueing() {tx.rollback().await.expect("rollback");ctx.cleanup().await.expect("cleanup");}++async fn wait_until_completed(ctx: &TestContext, op_id: Uuid) -> bool {+ for _ in 0..200 {+ if let Ok(row) = sqlx::query_scalar::<_, Option<chrono::DateTime<chrono::Utc>>>(+ "SELECT completed_at FROM lifecycle_op WHERE op_id = $1",+ )+ .bind(op_id)+ .fetch_one(&ctx.pool)+ .await+ {+ if row.is_some() {+ return true;+ }+ }+ tokio::time::sleep(std::time::Duration::from_millis(25)).await;+ }+ false+}++#[tokio::test]+async fn a_retry_attaches_to_a_detached_drive_instead_of_waiting_out_the_lease() {+ let ctx = TestContext::new().await;+ let engine = std::sync::Arc::new(ctx.engine());+ let driver = std::sync::Arc::new(DummyDriver::paced(std::time::Duration::from_millis(150)));+ let drives = DetachedDrives::new(4);+ let op_id = Uuid::now_v7();++ let detached_engine = engine.clone();+ let detached_driver = driver.clone();+ let hung_up = tokio::time::timeout(+ std::time::Duration::from_millis(1),+ drives.run(async move {+ detached_engine+ .execute(detached_driver.as_ref(), op_id, ctx.team_id, &json!({}))+ .await+ }),+ )+ .await;+ assert!(+ hung_up.is_err(),+ "the caller gave up before the drive finished"+ );+ assert_eq!(drives.in_flight(), 1);++ let started = std::time::Instant::now();+ let row = engine+ .execute(driver.as_ref(), op_id, ctx.team_id, &json!({}))+ .await+ .expect("the retry attaches and returns the terminal row");+ assert_eq!(row.step, STEP_COMPLETED);+ assert!(+ started.elapsed() < std::time::Duration::from_secs(5),+ "the retry waited on the live driver, not on the lease"+ );+ assert_eq!(+ driver.steps_run.load(Ordering::SeqCst),+ 2,+ "the retry polled behind the detached drive instead of re-running steps"+ );++ ctx.cleanup().await.expect("cleanup");+}++#[tokio::test]+async fn with_detaching_disabled_a_dropped_caller_abandons_the_op() {+ let ctx = TestContext::new().await;+ let engine = std::sync::Arc::new(ctx.engine());+ let driver = std::sync::Arc::new(DummyDriver::paced(std::time::Duration::from_millis(50)));+ let drives = DetachedDrives::new(0);+ let op_id = Uuid::now_v7();++ let created = std::sync::Arc::new(tokio::sync::Notify::new());+ let inline_engine = engine.clone();+ let inline_driver = driver.clone();+ let inline_created = created.clone();+ {+ let call = drives.run(async move {+ inline_engine+ .create_or_attach(inline_driver.as_ref(), op_id, ctx.team_id, &json!({}))+ .await+ .expect("create the op");+ inline_created.notify_one();+ inline_engine+ .execute(inline_driver.as_ref(), op_id, ctx.team_id, &json!({}))+ .await+ });+ tokio::pin!(call);+ tokio::select! {+ _ = &mut call => panic!("the drive finished before the caller hung up"),+ _ = created.notified() => {}+ }+ }++ tokio::time::sleep(std::time::Duration::from_millis(300)).await;+ let (step, _, _, completed) = op_row(&ctx, op_id).await;+ assert_eq!(+ step, "started",+ "an inline drive stops where its caller dropped it"+ );+ assert!(!completed);+ assert_eq!(drives.in_flight(), 0);++ ctx.cleanup().await.expect("cleanup");+}++#[tokio::test]+async fn a_detached_drive_finishes_after_its_caller_is_gone() {+ let ctx = TestContext::new().await;+ let engine = std::sync::Arc::new(ctx.engine());+ let driver = std::sync::Arc::new(DummyDriver::paced(std::time::Duration::from_millis(50)));+ let drives = DetachedDrives::new(4);+ let op_id = Uuid::now_v7();++ let hung_up = tokio::time::timeout(+ std::time::Duration::from_millis(1),+ drives.run(async move {+ engine+ .execute(driver.as_ref(), op_id, ctx.team_id, &json!({}))+ .await+ }),+ )+ .await;+ assert!(hung_up.is_err());++ assert!(+ wait_until_completed(&ctx, op_id).await,+ "the detached drive completed the op without its caller"+ );+ let (step, _, outcome, completed) = op_row(&ctx, op_id).await;+ assert_eq!(step, STEP_COMPLETED);+ assert!(completed);+ assert_eq!(outcome, Some(json!({"ok": true})));+ drives.shutdown().await;+ assert_eq!(drives.in_flight(), 0);++ ctx.cleanup().await.expect("cleanup");+}++async fn insert_leased_op(ctx: &TestContext, op_id: Uuid, lease: &str) {+ sqlx::query(&format!(+ "INSERT INTO lifecycle_op (op_id, op_type, team_id, step, request, lease_expires_at) VALUES ($1, 'merge', $2, 'started', '{{}}'::jsonb, {lease})"+ ))+ .bind(op_id)+ .bind(ctx.team_id as i32)+ .execute(&ctx.pool)+ .await+ .expect("insert leased op");+}++#[tokio::test]+async fn waiting_for_a_lease_lapse_returns_at_once_for_a_missing_or_finished_op() {+ let ctx = TestContext::new().await;+ let engine = ctx.engine();+ let driver = DummyDriver::new();++ let missing = Uuid::now_v7();+ assert!(!engine+ .wait_for_lease_lapse(missing, engine.execute_deadline())+ .await+ .expect("a missing op is claimable"));++ let finished = Uuid::now_v7();+ engine+ .execute(&driver, finished, ctx.team_id, &json!({}))+ .await+ .expect("drive to completion");+ assert!(engine+ .wait_for_lease_lapse(finished, engine.execute_deadline())+ .await+ .expect("a finished op is reported terminal"));++ ctx.cleanup().await.expect("cleanup");+}++#[tokio::test]+async fn waiting_for_a_lease_lapse_polls_until_it_lapses_and_gives_up_at_the_deadline() {+ let ctx = TestContext::new().await;+ let short_engine = personhog_identity::lifecycle::engine::Engine::new(+ ctx.pools.clone(),+ personhog_identity::lifecycle::engine::EngineConfig {+ lease: std::time::Duration::from_secs(5),+ execute_timeout: std::time::Duration::from_millis(300),+ poll_interval: std::time::Duration::from_millis(25),+ attempt_alert_threshold: 5,+ gc_batch_limit: 10_000,+ },+ ctx.tables.clone(),+ );++ let lapsing = Uuid::now_v7();+ insert_leased_op(&ctx, lapsing, "now() + interval '150 milliseconds'").await;+ let started = std::time::Instant::now();+ assert!(!short_engine+ .wait_for_lease_lapse(lapsing, short_engine.execute_deadline())+ .await+ .expect("the lease lapses"));+ assert!(started.elapsed() >= std::time::Duration::from_millis(100));++ let held = Uuid::now_v7();+ insert_leased_op(&ctx, held, "now() + interval '1 hour'").await;+ let err = short_engine+ .wait_for_lease_lapse(held, short_engine.execute_deadline())+ .await+ .expect_err("a lease held past the deadline is reported as busy");+ assert!(matches!(err, SagaError::Busy));++ ctx.cleanup().await.expect("cleanup");+}++#[tokio::test]+async fn a_shared_deadline_bounds_the_lease_wait_and_the_drive_together() {+ let ctx = TestContext::new().await;+ let engine = personhog_identity::lifecycle::engine::Engine::new(+ ctx.pools.clone(),+ personhog_identity::lifecycle::engine::EngineConfig {+ lease: std::time::Duration::from_secs(5),+ execute_timeout: std::time::Duration::from_millis(200),+ poll_interval: std::time::Duration::from_millis(10),+ attempt_alert_threshold: 5,+ gc_batch_limit: 10_000,+ },+ ctx.tables.clone(),+ );+ let driver = DummyDriver::paced(std::time::Duration::from_millis(100));+ let op_id = Uuid::now_v7();+ insert_leased_op(&ctx, op_id, "now() + interval '150 milliseconds'").await;++ let started = std::time::Instant::now();+ let deadline = engine.execute_deadline();+ assert!(!engine+ .wait_for_lease_lapse(op_id, deadline)+ .await+ .expect("the lease lapses inside the budget"));+ let err = engine+ .execute_by(&driver, op_id, ctx.team_id, &json!({}), deadline)+ .await+ .expect_err("the drive inherits what is left of the budget");+ assert!(matches!(err, SagaError::DeadlineElapsed));+ assert!(+ started.elapsed() < std::time::Duration::from_millis(400),+ "the two phases shared one budget instead of taking one each"+ );+ let (_, _, _, completed) = op_row(&ctx, op_id).await;+ assert!(!completed);++ ctx.cleanup().await.expect("cleanup");+}diff --git a/rust/personhog-identity/tests/lifecycle_merge_tests.rs b/rust/personhog-identity/tests/lifecycle_merge_tests.rsindex 34cedc377703..9db8adf9b776 100644--- a/rust/personhog-identity/tests/lifecycle_merge_tests.rs+++ b/rust/personhog-identity/tests/lifecycle_merge_tests.rs@@ -24,6 +24,7 @@ use sqlx::Row;use tonic::{Code, Status};use uuid::Uuid;+use personhog_identity::lifecycle::detach::DetachedDrives;use personhog_identity::lifecycle::engine::{Engine, OpDriver, OpRow, SagaError, STEP_ABORTED, STEP_COMPLETED,};@@ -39,6 +40,7 @@ struct MergeHarness {engine: Engine,leader: Arc<SimLeader>,driver: MergeDriver,+ drives: DetachedDrives,}impl MergeHarness {@@ -60,6 +62,7 @@ impl MergeHarness {engine,leader,driver,+ drives: DetachedDrives::new(common::FAN_OUT_CONCURRENCY),}}@@ -1757,6 +1760,7 @@ impl MergeHarness {self.ctx.tables.clone(),common::FAN_OUT_CONCURRENCY,),+ self.drives.clone(),),),common::FAN_OUT_CONCURRENCY,@@ -1784,6 +1788,7 @@ impl MergeHarness {self.ctx.tables.clone(),common::FAN_OUT_CONCURRENCY,),+ self.drives.clone(),),),common::FAN_OUT_CONCURRENCY,@@ -2051,6 +2056,190 @@ async fn the_rpc_runs_the_saga_and_a_retry_returns_the_recorded_answer() {h.ctx.cleanup().await.expect("cleanup");}+async fn op_exists(pool: &PgPool, op_id: Uuid) -> bool {+ sqlx::query_scalar::<_, bool>("SELECT EXISTS (SELECT 1 FROM lifecycle_op WHERE op_id = $1)")+ .bind(op_id)+ .fetch_one(pool)+ .await+ .expect("existence query runs")+}++async fn wait_until_completed(pool: &PgPool, op_id: Uuid) -> bool {+ for _ in 0..200 {+ if op_exists(pool, op_id).await && op_row_state(pool, op_id).await.1 {+ return true;+ }+ tokio::time::sleep(std::time::Duration::from_millis(25)).await;+ }+ false+}++#[tokio::test]+async fn a_caller_that_hangs_up_mid_saga_leaves_the_merge_to_finish() {+ let h = MergeHarness::new().await;+ let service = h.service();+ let target = h.ctx.insert_person_with_distinct_id("hangup-target").await;+ let sources = ["hangup-a", "hangup-b", "hangup-c", "hangup-d", "hangup-e"];+ let mut source_ids = Vec::new();+ for did in sources {+ source_ids.push(h.ctx.insert_person_with_distinct_id(did).await);+ }++ let op_id = Uuid::now_v7();+ let request = rpc_request(h.ctx.team_id, "hangup-target", &sources, op_id);+ {+ let call = service.merge_persons(Request::new(request.clone()));+ tokio::pin!(call);+ loop {+ tokio::select! {+ biased;+ _ = &mut call => panic!("the saga finished before the caller hung up"),+ _ = tokio::time::sleep(std::time::Duration::from_micros(200)) => {+ if op_exists(&h.ctx.pool, op_id).await {+ break;+ }+ }+ }+ }+ }++ assert!(+ wait_until_completed(&h.ctx.pool, op_id).await,+ "the merge completed without its caller"+ );+ for (did, id) in sources.iter().zip(&source_ids) {+ assert_eq!(+ h.pdi_state(did).await.0,+ target,+ "{did} moved to the target"+ );+ assert!(h.person_state(*id).await.0, "source {did} was destroyed");+ }+ let calls_after_saga = h.leader.calls().len();++ let retry = service+ .merge_persons(Request::new(request))+ .await+ .expect("the retry attaches to the finished op")+ .into_inner();+ assert_eq!(+ rpc_outcomes(&retry),+ sources+ .iter()+ .map(|did| (did.to_string(), MergeSourceOutcome::Merged))+ .collect::<Vec<_>>()+ );+ assert_eq!(retry.survivor.expect("survivor present").id, target);+ assert_eq!(h.leader.calls().len(), calls_after_saga);++ h.ctx.cleanup().await.expect("cleanup");+}++#[tokio::test]+async fn an_executor_call_dropped_once_detached_still_drives_the_merge() {+ let h = MergeHarness::new().await;+ let executor = MergeOpExecutor::new(+ Arc::new(h.ctx.engine()),+ MergeDriver::new(+ h.leader.clone(),+ h.ctx.tables.clone(),+ common::FAN_OUT_CONCURRENCY,+ ),+ h.drives.clone(),+ );+ let target = h.ctx.insert_person_with_distinct_id("drop-target").await;+ let source = h.ctx.insert_person_with_distinct_id("drop-source").await;+ let op_id = Uuid::now_v7();+ let frozen = serde_json::to_value(merge_request("drop-target", &["drop-source"])).unwrap();++ {+ let call = executor.execute(op_id, h.ctx.team_id, &frozen);+ tokio::pin!(call);+ loop {+ tokio::select! {+ biased;+ _ = &mut call => panic!("the saga finished before the caller hung up"),+ _ = tokio::time::sleep(std::time::Duration::from_micros(200)) => {+ if h.drives.in_flight() == 1 {+ break;+ }+ }+ }+ }+ }++ assert!(wait_until_completed(&h.ctx.pool, op_id).await);+ assert_eq!(h.pdi_state("drop-source").await.0, target);+ assert!(h.person_state(source).await.0);+ let calls_after_saga = h.leader.calls().len();++ let row = executor+ .execute(op_id, h.ctx.team_id, &frozen)+ .await+ .expect("the retry returns the recorded row");+ assert_eq!(row.step, STEP_COMPLETED);+ assert_eq!(h.leader.calls().len(), calls_after_saga);++ h.ctx.cleanup().await.expect("cleanup");+}++#[tokio::test]+async fn a_retry_waiting_behind_a_live_lease_dies_with_its_caller_instead_of_detaching() {+ let h = MergeHarness::new().await;+ let executor = MergeOpExecutor::new(+ Arc::new(h.ctx.engine()),+ MergeDriver::new(+ h.leader.clone(),+ h.ctx.tables.clone(),+ common::FAN_OUT_CONCURRENCY,+ ),+ h.drives.clone(),+ );+ let target = h.ctx.insert_person_with_distinct_id("waiter-target").await;+ h.ctx.insert_person_with_distinct_id("waiter-source").await;+ let op_id = Uuid::now_v7();+ let request = merge_request("waiter-target", &["waiter-source"]);+ let frozen = serde_json::to_value(&request).unwrap();+ h.create(op_id, &request).await;+ sqlx::query(+ "UPDATE lifecycle_op SET lease_expires_at = now() + interval '2 seconds' WHERE op_id = $1",+ )+ .bind(op_id)+ .execute(&h.ctx.pool)+ .await+ .expect("hold the lease as another driver");++ let hung_up = tokio::time::timeout(+ std::time::Duration::from_millis(100),+ executor.execute(op_id, h.ctx.team_id, &frozen),+ )+ .await;+ assert!(+ hung_up.is_err(),+ "the retry was still waiting behind the lease"+ );+ assert_eq!(+ h.drives.in_flight(),+ 0,+ "a waiter never takes a detached slot"+ );+ assert_eq!(h.drives.free_slots(), common::FAN_OUT_CONCURRENCY);++ sqlx::query("UPDATE lifecycle_op SET lease_expires_at = NULL WHERE op_id = $1")+ .bind(op_id)+ .execute(&h.ctx.pool)+ .await+ .expect("release the lease");+ let row = executor+ .execute(op_id, h.ctx.team_id, &frozen)+ .await+ .expect("the next retry claims and drives");+ assert_eq!(row.step, STEP_COMPLETED);+ assert_eq!(h.pdi_state("waiter-source").await.0, target);++ 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;@@ -2231,6 +2420,7 @@ async fn a_create_race_loser_answers_retryable_unavailable() {h.ctx.tables.clone(),common::FAN_OUT_CONCURRENCY,),+ h.drives.clone(),);let op_id = Uuid::now_v7();diff --git a/rust/personhog-identity/tests/service_tests.rs b/rust/personhog-identity/tests/service_tests.rsindex db06dac0eb98..5f4d31db1d87 100644--- a/rust/personhog-identity/tests/service_tests.rs+++ b/rust/personhog-identity/tests/service_tests.rs@@ -8,6 +8,7 @@ use common::TestContext;use tonic::{Code, Request, Status};use personhog_identity::leader::{PersonStateReader, PropertyWriter};+use personhog_identity::lifecycle::detach::DetachedDrives;use personhog_identity::lifecycle::merge::{MergeDriver, MergeOpExecutor};use personhog_identity::service::merge::MergeEntrance;use personhog_identity::service::validation::RequestLimits;@@ -98,6 +99,7 @@ impl ServiceTestContext {ctx.tables.clone(),common::FAN_OUT_CONCURRENCY,),+ DetachedDrives::new(common::FAN_OUT_CONCURRENCY),),);let service = PersonHogIdentityService::new(