Skip to content

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

feat(personhog): fence delete victims through the leader (#81219)

José Sequeira98c4156cbeea
diff --git a/rust/personhog-identity/.sqlx/query-14c5a2212339d66a09b60ed2dd254c3cfe723715cb6f248f4d478ab2faac3349.json b/rust/personhog-identity/.sqlx/query-14c5a2212339d66a09b60ed2dd254c3cfe723715cb6f248f4d478ab2faac3349.json
new file mode 100644
index 000000000000..b1b802bc4ce5
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-14c5a2212339d66a09b60ed2dd254c3cfe723715cb6f248f4d478ab2faac3349.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT person_id FROM lifecycle_op_person\n WHERE op_id = $1 AND status IN ('marked', 'sealed')\n ORDER BY person_id\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "person_id",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "14c5a2212339d66a09b60ed2dd254c3cfe723715cb6f248f4d478ab2faac3349"
+}
diff --git a/rust/personhog-identity/.sqlx/query-3c797d3d827dcfc7a3ccf3fc6f33478c88f6b1fb3daa938d8888590c9e31dd3c.json b/rust/personhog-identity/.sqlx/query-3c797d3d827dcfc7a3ccf3fc6f33478c88f6b1fb3daa938d8888590c9e31dd3c.json
new file mode 100644
index 000000000000..a50a7d6736b1
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-3c797d3d827dcfc7a3ccf3fc6f33478c88f6b1fb3daa938d8888590c9e31dd3c.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n DELETE FROM lifecycle_op_person\n WHERE op_id = $1 AND person_id = ANY($2) AND status IN ('marked', 'sealed')\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Int8Array"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "3c797d3d827dcfc7a3ccf3fc6f33478c88f6b1fb3daa938d8888590c9e31dd3c"
+}
diff --git a/rust/personhog-identity/.sqlx/query-f847b2269365b72844a7e25b9201cb3dda0c7623d728b0f855f2b0797e6f3ecb.json b/rust/personhog-identity/.sqlx/query-f847b2269365b72844a7e25b9201cb3dda0c7623d728b0f855f2b0797e6f3ecb.json
new file mode 100644
index 000000000000..56d0d782ee4f
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-f847b2269365b72844a7e25b9201cb3dda0c7623d728b0f855f2b0797e6f3ecb.json
@@ -0,0 +1,18 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE lifecycle_op_person lop\n SET status = $2, sealed = jsonb_build_object('version', u.version, 'created_at', u.created_at)\n FROM unnest($3::bigint[], $4::bigint[], $5::bigint[]) AS u(person_id, version, created_at)\n WHERE lop.op_id = $1 AND lop.person_id = u.person_id\n AND lop.status IN ('marked', 'sealed')\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Int8Array",
+ "Int8Array",
+ "Int8Array"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "f847b2269365b72844a7e25b9201cb3dda0c7623d728b0f855f2b0797e6f3ecb"
+}
diff --git a/rust/personhog-identity/.sqlx/query-f986c4fea2c4b8a56c903568483947304cb503d897e25b635135c83f8201d707.json b/rust/personhog-identity/.sqlx/query-f986c4fea2c4b8a56c903568483947304cb503d897e25b635135c83f8201d707.json
new file mode 100644
index 000000000000..7f87c8dc3402
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-f986c4fea2c4b8a56c903568483947304cb503d897e25b635135c83f8201d707.json
@@ -0,0 +1,40 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT person_id, person_uuid,\n (sealed->>'version')::bigint AS \"sealed_version!\",\n (sealed->>'created_at')::bigint AS \"sealed_created_at!\"\n FROM lifecycle_op_person\n WHERE op_id = $1 AND status = 'sealed' AND sealed ? 'created_at'\n ORDER BY person_id\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "person_id",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 1,
+ "name": "person_uuid",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 2,
+ "name": "sealed_version!",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 3,
+ "name": "sealed_created_at!",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ null,
+ null
+ ]
+ },
+ "hash": "f986c4fea2c4b8a56c903568483947304cb503d897e25b635135c83f8201d707"
+}
diff --git a/rust/personhog-identity/src/lifecycle/delete.rs b/rust/personhog-identity/src/lifecycle/delete.rs
index 4976c78ce7f0..747b825d537a 100644
--- a/rust/personhog-identity/src/lifecycle/delete.rs
+++ b/rust/personhog-identity/src/lifecycle/delete.rs
@@ -3,32 +3,47 @@
//! was mutated). Each step is one transaction that commits its work together
//! with the step advance — see the engine's correctness model.
//!
-//! Pre-leader-fencing mode: the leader's `FencePerson` / `ReleaseFence` RPCs
-//! have not landed yet, so this driver runs the saga without a fence.
-//! Sealing reads the person's version from Postgres and adds
-//! [`SEAL_VERSION_MARGIN`] (the same margin the legacy delete path uses) so
-//! the death version outranks any write that lands between the seal and the
-//! tombstone. The unmapped transaction writes the person tombstone directly
-//! — once the leader produces death documents and the writer projects them
-//! (RFC stages 6–7), that direct write becomes the fence-gated fallback and
-//! the leader/writer path takes over ClickHouse emission. Until then the
-//! distinct-id rows tombstoned by an op are recorded in each victim row's
-//! `moved` column, so nothing needed for later emission is lost.
+//! Sealing fences each victim on its owning leader — `FencePerson` rejects
+//! writes while the op lives and returns the exact sealed version, so no
+//! margin is needed — and completion calls `ReleaseFence(committed)` per
+//! victim, which makes the leader produce the death document into the
+//! changelog and evict its cache entry. The unmapped transaction still
+//! writes the person tombstone directly: it is the durable revival floor
+//! the sync plane reads (sanctioned by the RFC); the death document
+//! confirms it downstream (writer, ClickHouse) at the same version,
+//! sealed + 1. The distinct-id rows tombstoned by an op are recorded in
+//! each victim row's `moved` column, so nothing needed for later emission
+//! is lost.
+//!
+//! Ops sealed by a pre-fence build (sealed jsonb without `created_at`, the
+//! margin folded into the version) complete without release calls — the
+//! leader was never fenced for them, and their tombstone version already
+//! carries the old margin.
+
+use std::sync::Arc;
use async_trait::async_trait;
+use futures::stream::{self, StreamExt};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use sqlx::postgres::PgPool;
+use tonic::Code;
use uuid::Uuid;
-use personhog_proto::personhog::types::v1::LifecycleOpType;
+use personhog_proto::personhog::types::v1::{
+ FencePersonRequest, LifecycleOpType, ReleaseFenceRequest, ReleaseOutcome,
+};
use crate::config::IdentityTables;
+use crate::leader::LifecycleLeader;
use crate::lifecycle::engine::{
advance_step_in_tx, complete_op_in_tx, OpDriver, OpRow, SagaError, Tx, STEP_ABORTED,
STEP_COMPLETED,
};
+/// Bound on concurrent leader calls per step, matching the merge driver.
+const LEADER_CALL_CONCURRENCY: usize = 8;
+
// Derived from the shared enum so the op-type string cannot drift from
// the leader's fence records or the lifecycle_op CHECK constraint.
pub const OP_TYPE_DELETE: &str = LifecycleOpType::Delete.as_op_type_str();
@@ -65,14 +80,6 @@ impl DeleteStep {
}
}
-/// Added to the person's Postgres version at seal time. Without a fence a
-/// concurrent write can still bump the version between the seal and the
-/// tombstone; the margin parks the death version far above anything such a
-/// write can reach, exactly like the legacy delete path's +100. Once sealing
-/// goes through `FencePerson` no write can follow the seal and the margin
-/// can drop to zero.
-pub const SEAL_VERSION_MARGIN: i64 = 100;
-
/// The frozen `lifecycle_op.request` payload for a delete op.
#[derive(Debug, Serialize, Deserialize)]
pub struct DeleteRequest {
@@ -137,13 +144,14 @@ fn record_outcomes(outcome: &Value) {
}
pub struct DeleteDriver {
+ leader: Arc<dyn LifecycleLeader>,
tables: IdentityTables,
}
impl DeleteDriver {
- pub fn new(tables: IdentityTables) -> Self {
+ pub fn new(leader: Arc<dyn LifecycleLeader>, tables: IdentityTables) -> Self {
tables.validate().expect("invalid identity table set");
- Self { tables }
+ Self { leader, tables }
}
}
@@ -166,9 +174,9 @@ impl OpDriver for DeleteDriver {
})?;
match step {
DeleteStep::Started => mark(pool, &self.tables.person, op).await,
- DeleteStep::Marked => seal(pool, &self.tables.person, op).await,
+ DeleteStep::Marked => seal(pool, self.leader.as_ref(), op).await,
DeleteStep::Sealed => unmap(pool, &self.tables, op).await,
- DeleteStep::Unmapped => complete(pool, op).await,
+ DeleteStep::Unmapped => complete(pool, self.leader.as_ref(), op).await,
}
}
}
@@ -348,30 +356,108 @@ async fn mark(pool: &PgPool, person_table: &str, op: &OpRow) -> Result<(), SagaE
Ok(())
}
-/// `marked → sealed`: freeze each victim's final version. Pre-fence this
-/// reads the version from Postgres and adds [`SEAL_VERSION_MARGIN`]; with
-/// leader fencing (RFC stage 6) this becomes a `FencePerson` call per victim
-/// and the sealed version is exact.
-async fn seal(pool: &PgPool, person_table: &str, op: &OpRow) -> Result<(), SagaError> {
- let team_id = op.team_id as i32;
- let mut tx = pool.begin().await?;
+/// `marked → sealed`: fence every victim's owning leader and
+/// persist the exact sealed versions. The fences are the step's only
+/// external effect and a same-op re-fence is a re-seal returning fresh
+/// state, so the fan-out is safe to repeat; the sealed values and the step
+/// CAS commit together afterwards. The sealed jsonb records `created_at`
+/// (epoch seconds, as the leader seals it) alongside `version`; its
+/// presence is what marks a victim as fenced when the release runs.
+///
+/// A victim the leader reports NOT_FOUND vanished between the claim
+/// recheck and its fence (destroyed by another actor) — its mark row is
+/// removed so it settles as `not_found`, mirroring the merge driver's
+/// vanished-source handling. A definitive refusal propagates and parks the
+/// op; unlike the merge driver's pre-flip abort, delete has no abort path
+/// past `started`, and a parked delete is an operator signal, not a stuck
+/// customer flow.
+async fn seal(pool: &PgPool, leader: &dyn LifecycleLeader, op: &OpRow) -> Result<(), SagaError> {
+ let victims = sqlx::query!(
+ r#"
+ SELECT person_id FROM lifecycle_op_person
+ WHERE op_id = $1 AND status IN ('marked', 'sealed')
+ ORDER BY person_id
+ "#,
+ op.op_id
+ )
+ .fetch_all(pool)
+ .await?;
- let seal_sql = format!(
+ let fence_calls: Vec<_> = victims
+ .iter()
+ .map(|victim| {
+ let request = FencePersonRequest {
+ team_id: op.team_id,
+ person_id: victim.person_id,
+ op_id: op.op_id.to_string(),
+ op_type: LifecycleOpType::Delete.into(),
+ };
+ let person_id = victim.person_id;
+ async move { (person_id, leader.fence_person(request).await) }
+ })
+ .collect();
+ let fence_results: Vec<_> = stream::iter(fence_calls)
+ .buffer_unordered(LEADER_CALL_CONCURRENCY)
+ .collect()
+ .await;
+
+ let mut sealed_ids: Vec<i64> = Vec::with_capacity(fence_results.len());
+ let mut sealed_versions: Vec<i64> = Vec::with_capacity(fence_results.len());
+ let mut sealed_created_ats: Vec<i64> = Vec::with_capacity(fence_results.len());
+ let mut vanished: Vec<i64> = Vec::new();
+ for (person_id, result) in fence_results {
+ match result {
+ Ok(response) => {
+ let sealed = response.sealed.ok_or_else(|| {
+ SagaError::CorruptState(format!(
+ "fence response for person {person_id} carries no sealed state"
+ ))
+ })?;
+ sealed_ids.push(person_id);
+ sealed_versions.push(sealed.version);
+ sealed_created_ats.push(sealed.created_at);
+ }
+ Err(status) if status.code() == Code::NotFound => {
+ tracing::error!(
+ op_id = %op.op_id,
+ person_id,
+ "marked delete victim vanished before its fence; settling it as not_found"
+ );
+ vanished.push(person_id);
+ }
+ Err(status) => return Err(SagaError::leader(status)),
+ }
+ }
+
+ let mut tx = pool.begin().await?;
+ sqlx::query!(
r#"
UPDATE lifecycle_op_person lop
- SET status = $3, sealed = jsonb_build_object('version', COALESCE(p.version, 0) + $4)
- FROM {person_table} p
- WHERE lop.op_id = $1 AND lop.status IN ('marked', 'sealed')
- AND p.team_id = $2 AND p.id = lop.person_id
- "#
- );
- sqlx::query(&seal_sql)
- .bind(op.op_id)
- .bind(team_id)
- .bind(STATUS_SEALED)
- .bind(SEAL_VERSION_MARGIN)
+ SET status = $2, sealed = jsonb_build_object('version', u.version, 'created_at', u.created_at)
+ FROM unnest($3::bigint[], $4::bigint[], $5::bigint[]) AS u(person_id, version, created_at)
+ WHERE lop.op_id = $1 AND lop.person_id = u.person_id
+ AND lop.status IN ('marked', 'sealed')
+ "#,
+ op.op_id,
+ STATUS_SEALED,
+ &sealed_ids,
+ &sealed_versions,
+ &sealed_created_ats,
+ )
+ .execute(&mut *tx)
+ .await?;
+ if !vanished.is_empty() {
+ sqlx::query!(
+ r#"
+ DELETE FROM lifecycle_op_person
+ WHERE op_id = $1 AND person_id = ANY($2) AND status IN ('marked', 'sealed')
+ "#,
+ op.op_id,
+ &vanished,
+ )
.execute(&mut *tx)
.await?;
+ }
if !advance_step_in_tx(
&mut tx,
@@ -412,6 +498,32 @@ async fn unmap(pool: &PgPool, tables: &IdentityTables, op: &OpRow) -> Result<(),
.await?;
victims.sort_unstable();
+ // Take every row lock this transaction will need up front, in id order,
+ // before the multi-row updates below. Those statements acquire locks in
+ // whatever order the query plan visits rows, and the writer's flush
+ // upsert spans overlapping persons in one statement — uncontrolled
+ // order on either side is a deadlock cycle waiting for load. Sorted
+ // acquisition on both sides (the writer sorts its flush batches the
+ // same way) makes a cycle impossible.
+ let lock_persons_sql = format!(
+ "SELECT id FROM {person_table} WHERE team_id = $1 AND id = ANY($2) ORDER BY id FOR UPDATE",
+ person_table = tables.person,
+ );
+ sqlx::query(&lock_persons_sql)
+ .bind(team_id)
+ .bind(&victims)
+ .execute(&mut *tx)
+ .await?;
+ let lock_pdi_sql = format!(
+ "SELECT id FROM {pdi_table} WHERE team_id = $1 AND person_id = ANY($2) ORDER BY id FOR UPDATE",
+ pdi_table = tables.person_distinct_id,
+ );
+ sqlx::query(&lock_pdi_sql)
+ .bind(team_id)
+ .bind(&victims)
+ .execute(&mut *tx)
+ .await?;
+
let tombstone_pdi_sql = format!(
r#"
UPDATE {pdi_table}
@@ -519,13 +631,61 @@ async fn unmap(pool: &PgPool, tables: &IdentityTables, op: &OpRow) -> Result<(),
Ok(())
}
-/// `unmapped → completed`: settle the per-person rows to `deleted` (which
-/// releases their marks), record the outcome, and stamp completion. With
-/// leader fencing (RFC stage 6) the per-victim `ReleaseFence(committed)`
-/// calls — the leader producing each death document — happen before this
-/// transaction.
-async fn complete(pool: &PgPool, op: &OpRow) -> Result<(), SagaError> {
+/// `unmapped → completed`: release each fenced victim with the committed
+/// outcome — the leader produces the death document into the changelog and
+/// evicts its cache entry — then settle the per-person rows to `deleted`
+/// (which releases their marks), record the outcome, and stamp completion.
+///
+/// The releases run before the settle transaction because the leader
+/// verifies a committed release against a live mark (`marked`/`sealed`)
+/// and fails closed without one; a mark already settled as `deleted`
+/// absorbs a retried release without a second death document. Only victims
+/// whose sealed jsonb carries `created_at` are released: that key exists
+/// exactly when `FencePerson` sealed them, so an op sealed pre-fence (or
+/// across a kill-switch flip) completes without phantom release calls.
+async fn complete(
+ pool: &PgPool,
+ leader: &dyn LifecycleLeader,
+ op: &OpRow,
+) -> Result<(), SagaError> {
let request = parse_request(op)?;
+
+ let fenced = sqlx::query!(
+ r#"
+ SELECT person_id, person_uuid,
+ (sealed->>'version')::bigint AS "sealed_version!",
+ (sealed->>'created_at')::bigint AS "sealed_created_at!"
+ FROM lifecycle_op_person
+ WHERE op_id = $1 AND status = 'sealed' AND sealed ? 'created_at'
+ ORDER BY person_id
+ "#,
+ op.op_id
+ )
+ .fetch_all(pool)
+ .await?;
+ let release_calls: Vec<_> = fenced
+ .iter()
+ .map(|victim| {
+ let request = ReleaseFenceRequest {
+ team_id: op.team_id,
+ person_id: victim.person_id,
+ person_uuid: victim.person_uuid.to_string(),
+ op_id: op.op_id.to_string(),
+ outcome: ReleaseOutcome::Committed.into(),
+ sealed_version: Some(victim.sealed_version),
+ created_at: victim.sealed_created_at,
+ };
+ async move { leader.release_fence(request).await }
+ })
+ .collect();
+ let release_results: Vec<_> = stream::iter(release_calls)
+ .buffer_unordered(LEADER_CALL_CONCURRENCY)
+ .collect()
+ .await;
+ for result in release_results {
+ result.map_err(SagaError::leader)?;
+ }
+
let mut tx = pool.begin().await?;
sqlx::query!(
diff --git a/rust/personhog-identity/src/lifecycle/engine.rs b/rust/personhog-identity/src/lifecycle/engine.rs
index 741a46385fce..77ca8b12131c 100644
--- a/rust/personhog-identity/src/lifecycle/engine.rs
+++ b/rust/personhog-identity/src/lifecycle/engine.rs
@@ -39,6 +39,11 @@ const OPS_PARKED: &str = "personhog_lifecycle_ops_parked";
/// 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.
+const DB_CONFLICT_BACKOFF: Duration = Duration::from_millis(50);
+
pub type Tx<'a> = sqlx::Transaction<'a, sqlx::Postgres>;
#[derive(Debug, thiserror::Error)]
@@ -77,6 +82,30 @@ impl SagaError {
SagaError::Leader(Box::new(status))
}
}
+
+ /// A database conflict Postgres asks callers to retry: deadlock victim
+ /// (40P01), serialization failure (40001), or a cancelled statement
+ /// (57014, the statement timeout under lock contention). Steps commit
+ /// their work and their step advance together, so re-driving one is
+ /// always safe — the engine retries these instead of surfacing them.
+ pub fn is_db_conflict(&self) -> bool {
+ let SagaError::Db(sqlx::Error::Database(db)) = self else {
+ return false;
+ };
+ matches!(db.code().as_deref(), Some("40P01" | "40001" | "57014"))
+ }
+
+ /// 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
+ /// disabled (dev RDS logs no ERROR lines).
+ pub fn db_detail(&self) -> Option<&str> {
+ let SagaError::Db(sqlx::Error::Database(db)) = self else {
+ return None;
+ };
+ db.try_downcast_ref::<sqlx::postgres::PgDatabaseError>()
+ .and_then(|e| e.detail())
+ }
}
impl From<SagaError> for Status {
@@ -336,6 +365,7 @@ impl Engine {
// counter climbing for one op_type/kind, not as generic
// 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(_) => "db",
SagaError::Leader(_) => "leader",
SagaError::LeaderRefused(_) => "leader_refused",
@@ -352,6 +382,24 @@ impl Engine {
],
1,
);
+ if err.is_db_conflict() {
+ // Concurrent multi-row writers (a writer flush, another
+ // saga) can deadlock or time out against a step's
+ // transaction; the loser rolls back whole and the step
+ // is safe to repeat. Keep the lease and re-drive after a
+ // pause instead of surfacing an error the caller would
+ // retry anyway; the execute deadline bounds the loop.
+ tracing::warn!(
+ op_id = %op_id,
+ op_type = %row.op_type,
+ step = %row.step,
+ error = %err,
+ detail = %err.db_detail().unwrap_or(""),
+ "lifecycle step lost a database conflict; 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/lifecycle/mod.rs b/rust/personhog-identity/src/lifecycle/mod.rs
index 660a837fbae1..0c86c36fa192 100644
--- a/rust/personhog-identity/src/lifecycle/mod.rs
+++ b/rust/personhog-identity/src/lifecycle/mod.rs
@@ -23,6 +23,7 @@ use personhog_proto::personhog::lifecycle::v1::{
DeletePersonOutcome, DeletePersonResult, DeletePersonsRequest, DeletePersonsResponse,
};
+use crate::leader::LifecycleLeader;
use crate::lifecycle::delete::{
DeleteDriver, DeleteOutcome, OUTCOME_DELETED, OUTCOME_NOT_FOUND, OUTCOME_SKIPPED_CONFLICT,
};
@@ -35,10 +36,14 @@ pub struct PersonHogLifecycleService {
}
impl PersonHogLifecycleService {
- pub fn new(engine: Arc<Engine>, tables: crate::config::IdentityTables) -> Self {
+ pub fn new(
+ engine: Arc<Engine>,
+ leader: Arc<dyn LifecycleLeader>,
+ tables: crate::config::IdentityTables,
+ ) -> Self {
Self {
engine,
- delete_driver: DeleteDriver::new(tables),
+ delete_driver: DeleteDriver::new(leader, tables),
}
}
}
diff --git a/rust/personhog-identity/src/main.rs b/rust/personhog-identity/src/main.rs
index 47f82100190b..8eb8a7b66951 100644
--- a/rust/personhog-identity/src/main.rs
+++ b/rust/personhog-identity/src/main.rs
@@ -20,6 +20,7 @@ use tracing_subscriber::EnvFilter;
use personhog_common::client::RouterClient;
use personhog_identity::config::Config;
+use personhog_identity::leader::LifecycleLeader;
use personhog_identity::lifecycle::delete::DeleteDriver;
use personhog_identity::lifecycle::engine::Engine;
use personhog_identity::lifecycle::merge::MergeDriver;
@@ -185,14 +186,17 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
RouterClient::new(&config.router_url, config.leader_request_timeout())
.expect("Invalid router URL"),
);
+ // Both sagas' leader surface, reached through the router like the
+ // property writes.
+ let lifecycle_leader: Arc<dyn LifecycleLeader> = property_writer.clone();
let engine = Arc::new(Engine::new(
storage.primary_pool.clone(),
config.lifecycle_engine_config(),
));
if let Some(sweeper_handle) = sweeper_handle {
let sweeper_merge_driver = MergeDriver::new(property_writer.clone(), config.tables());
+ let sweeper_delete_driver = DeleteDriver::new(lifecycle_leader.clone(), config.tables());
let sweeper_engine = engine.clone();
- let sweeper_driver = DeleteDriver::new(config.tables());
let sweep_interval = config.lifecycle_sweep_interval();
let retention = config.lifecycle_op_retention();
tracing::info!(
@@ -213,7 +217,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
_ = ticker.tick() => {}
}
match sweeper_engine
- .sweep(&[&sweeper_driver, &sweeper_merge_driver])
+ .sweep(&[&sweeper_delete_driver, &sweeper_merge_driver])
.await
{
Ok(resumed) if resumed > 0 => {
@@ -232,7 +236,8 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
let service = PersonHogIdentityService::new(storage, property_writer, config.request_limits());
// Separate proto service co-served on the same server so lifecycle
// callers are insulated from any future split.
- let lifecycle_service = PersonHogLifecycleService::new(engine, config.tables());
+ let lifecycle_service =
+ PersonHogLifecycleService::new(engine, lifecycle_leader, config.tables());
let grpc_addr = config.grpc_address;
let keepalive_interval = config.grpc_keepalive_interval();
diff --git a/rust/personhog-identity/tests/lifecycle_delete_tests.rs b/rust/personhog-identity/tests/lifecycle_delete_tests.rs
index b07c217552e9..b020533bc238 100644
--- a/rust/personhog-identity/tests/lifecycle_delete_tests.rs
+++ b/rust/personhog-identity/tests/lifecycle_delete_tests.rs
@@ -6,11 +6,13 @@ mod common;
use std::sync::Arc;
use chrono::Utc;
+use common::sim_leader::{LeaderCall, Rpc, SimLeader, FENCED_METADATA_KEY};
use common::TestContext;
-use tonic::Request;
+use tonic::{Request, Status};
use uuid::Uuid;
-use personhog_identity::lifecycle::delete::SEAL_VERSION_MARGIN;
+use personhog_identity::lifecycle::delete::{DeleteDriver, DeleteOutcome};
+use personhog_identity::lifecycle::engine::{Engine, OpRow, SagaError};
use personhog_identity::lifecycle::PersonHogLifecycleService;
use personhog_identity::storage::{IdentityStorage, PersonStub, StubOutcome};
use personhog_proto::personhog::lifecycle::v1::person_hog_lifecycle_server::PersonHogLifecycle;
@@ -19,7 +21,14 @@ use personhog_proto::personhog::lifecycle::v1::{DeletePersonOutcome, DeletePerso
/// Storage-assertion helpers used only by this test binary.
impl TestContext {
fn lifecycle_service(&self) -> PersonHogLifecycleService {
- PersonHogLifecycleService::new(Arc::new(self.engine()), self.tables.clone())
+ PersonHogLifecycleService::new(
+ Arc::new(self.engine()),
+ Arc::new(SimLeader::new(
+ self.pool.clone(),
+ self.tables.person.clone(),
+ )),
+ self.tables.clone(),
+ )
}
/// (is_deleted, version, properties) of a person row.
@@ -187,10 +196,11 @@ async fn delete_destroys_the_person_and_its_satellite_rows() {
vec![(person_id, DeletePersonOutcome::Deleted)]
);
- // The person: tombstoned at sealed + 1 (version 0 at seal time), scrubbed.
+ // The person: tombstoned at sealed + 1 (the fence sealed version 0),
+ // scrubbed.
let (is_deleted, version, properties) = ctx.person_state(person_id).await;
assert!(is_deleted);
- assert_eq!(version, SEAL_VERSION_MARGIN + 1);
+ assert_eq!(version, 1);
assert_eq!(properties, "{}");
// The mappings: tombstoned one version above their previous one.
@@ -530,6 +540,304 @@ async fn a_recreated_distinct_id_revives_above_the_death_version() {
ctx.cleanup().await.expect("cleanup");
}
+/// Fenced-mode walkthrough harness: the delete driver wired to a
+/// [`SimLeader`], driven through the engine directly so tests can stop at
+/// step boundaries and probe the leader's state in between.
+struct FencedHarness {
+ ctx: TestContext,
+ engine: Engine,
+ leader: Arc<SimLeader>,
+ driver: DeleteDriver,
+}
+
+impl FencedHarness {
+ async fn new() -> Self {
+ let ctx = TestContext::new().await;
+ let engine = ctx.engine();
+ let leader = Arc::new(SimLeader::new(ctx.pool.clone(), ctx.tables.person.clone()));
+ let driver = DeleteDriver::new(leader.clone(), ctx.tables.clone());
+ Self {
+ ctx,
+ engine,
+ leader,
+ driver,
+ }
+ }
+
+ fn request(person_ids: &[i64]) -> serde_json::Value {
+ serde_json::json!({ "person_ids": person_ids })
+ }
+
+ async fn execute(&self, op_id: Uuid, person_ids: &[i64]) -> Result<OpRow, SagaError> {
+ self.engine
+ .execute(
+ &self.driver,
+ op_id,
+ self.ctx.team_id,
+ &Self::request(person_ids),
+ )
+ .await
+ }
+
+ async fn step(&self, op_id: Uuid) -> Result<OpRow, SagaError> {
+ self.engine
+ .step_once(&self.driver, op_id, self.ctx.team_id)
+ .await
+ }
+
+ fn outcome(row: &OpRow) -> DeleteOutcome {
+ serde_json::from_value(row.outcome.clone().expect("terminal outcome"))
+ .expect("outcome parses")
+ }
+}
+
+#[tokio::test]
+async fn fenced_delete_seals_the_exact_version_and_produces_the_death_document() {
+ let h = FencedHarness::new().await;
+ let distinct_id = format!("fenced-victim-{}", Uuid::now_v7());
+ let person_id = h.ctx.create_person_via_stub(&distinct_id).await;
+
+ let op_id = Uuid::now_v7();
+ let row = h
+ .execute(op_id, &[person_id])
+ .await
+ .expect("fenced delete completes");
+ let outcome = FencedHarness::outcome(&row);
+ assert_eq!(outcome.results[0].outcome, "deleted");
+
+ // The fence sealed the stub's exact version (0), so the tombstone and
+ // the death document land at 1 — no margin.
+ let (is_deleted, version, _) = h.ctx.person_state(person_id).await;
+ assert!(is_deleted);
+ assert_eq!(version, 1, "fenced seal must not add the pre-fence margin");
+ let docs = h.leader.death_documents();
+ assert_eq!(docs.len(), 1);
+ assert_eq!(docs[0].person_id, person_id);
+ assert_eq!(docs[0].version, 1);
+
+ // The fence is gone, and it was installed before the release ran.
+ assert!(h.leader.fence_for(person_id).is_none());
+ let calls = h.leader.calls();
+ let fence_at = calls
+ .iter()
+ .position(|c| matches!(c, LeaderCall::Fence { .. }))
+ .expect("a fence call");
+ let release_at = calls
+ .iter()
+ .position(|c| matches!(c, LeaderCall::ReleaseCommitted { .. }))
+ .expect("a committed release call");
+ assert!(fence_at < release_at);
+
+ h.ctx.cleanup().await.expect("cleanup");
+}
+
+#[tokio::test]
+async fn a_fenced_victim_rejects_writes_until_the_op_completes() {
+ let h = FencedHarness::new().await;
+ let distinct_id = format!("fenced-frozen-{}", Uuid::now_v7());
+ let person_id = h.ctx.create_person_via_stub(&distinct_id).await;
+
+ let op_id = Uuid::now_v7();
+ h.engine
+ .create_or_attach(
+ &h.driver,
+ op_id,
+ h.ctx.team_id,
+ &FencedHarness::request(&[person_id]),
+ )
+ .await
+ .expect("create op");
+ let row = h.step(op_id).await.expect("started -> marked");
+ assert_eq!(row.step, "marked");
+ let row = h.step(op_id).await.expect("marked -> sealed");
+ assert_eq!(row.step, "sealed");
+
+ // Sealed means fenced: an ordinary write is rejected with the leader's
+ // typed fence metadata until the op finishes.
+ let rejection = h
+ .leader
+ .admit_write(h.ctx.team_id, person_id)
+ .await
+ .expect_err("a sealed victim must reject writes");
+ assert!(rejection.metadata().contains_key(FENCED_METADATA_KEY));
+
+ let row = h.step(op_id).await.expect("sealed -> unmapped");
+ assert_eq!(row.step, "unmapped");
+ let row = h.step(op_id).await.expect("unmapped -> completed");
+ assert!(row.completed_at.is_some());
+
+ // The fence is released; the person now answers destroyed, not fenced.
+ assert!(h.leader.fence_for(person_id).is_none());
+ let destroyed = h
+ .leader
+ .admit_write(h.ctx.team_id, person_id)
+ .await
+ .expect_err("a destroyed person rejects writes");
+ assert_eq!(destroyed.code(), tonic::Code::NotFound);
+
+ h.ctx.cleanup().await.expect("cleanup");
+}
+
+#[tokio::test]
+async fn a_transient_fence_failure_leaves_the_op_retryable() {
+ let h = FencedHarness::new().await;
+ let distinct_id = format!("fenced-retry-{}", Uuid::now_v7());
+ let person_id = h.ctx.create_person_via_stub(&distinct_id).await;
+
+ h.leader
+ .fail_next(Rpc::Fence, person_id, Status::unavailable("leader down"));
+ let op_id = Uuid::now_v7();
+ let err = h
+ .execute(op_id, &[person_id])
+ .await
+ .expect_err("the fence failure surfaces");
+ assert!(matches!(err, SagaError::Leader(_)));
+
+ let row = h
+ .execute(op_id, &[person_id])
+ .await
+ .expect("retry completes");
+ assert_eq!(FencedHarness::outcome(&row).results[0].outcome, "deleted");
+ assert_eq!(h.leader.death_documents().len(), 1);
+
+ h.ctx.cleanup().await.expect("cleanup");
+}
+
+#[tokio::test]
+async fn a_transient_release_failure_leaves_the_op_retryable() {
+ let h = FencedHarness::new().await;
+ let distinct_id = format!("fenced-release-retry-{}", Uuid::now_v7());
+ let person_id = h.ctx.create_person_via_stub(&distinct_id).await;
+
+ h.leader
+ .fail_next(Rpc::Release, person_id, Status::unavailable("leader down"));
+ let op_id = Uuid::now_v7();
+ let err = h
+ .execute(op_id, &[person_id])
+ .await
+ .expect_err("the release failure surfaces");
+ assert!(matches!(err, SagaError::Leader(_)));
+
+ // The op parked on unmapped with its sync-plane work done; the retry
+ // re-releases and the duplicate-absorbing leader still produces exactly
+ // one death document.
+ let row = h
+ .execute(op_id, &[person_id])
+ .await
+ .expect("retry completes");
+ assert_eq!(FencedHarness::outcome(&row).results[0].outcome, "deleted");
+ assert_eq!(h.leader.death_documents().len(), 1);
+ assert!(h.leader.fence_for(person_id).is_none());
+
+ h.ctx.cleanup().await.expect("cleanup");
+}
+
+#[tokio::test]
+async fn an_op_sealed_by_a_pre_fence_build_completes_without_release_calls() {
+ let h = FencedHarness::new().await;
+ let distinct_id = format!("pre-fence-upgrade-{}", Uuid::now_v7());
+ let person_id = h.ctx.create_person_via_stub(&distinct_id).await;
+
+ // Recreate the state a pre-fence build leaves behind at a deploy
+ // boundary: victims sealed with the margin folded into the version and
+ // no created_at in the sealed jsonb. The new build must finish the op
+ // without inventing release calls for victims it never fenced.
+ let op_id = Uuid::now_v7();
+ h.engine
+ .create_or_attach(
+ &h.driver,
+ op_id,
+ h.ctx.team_id,
+ &FencedHarness::request(&[person_id]),
+ )
+ .await
+ .expect("create op");
+ let row = h.step(op_id).await.expect("started -> marked");
+ assert_eq!(row.step, "marked");
+ sqlx::query(
+ r#"
+ UPDATE lifecycle_op_person
+ SET status = 'sealed', sealed = jsonb_build_object('version', 100)
+ WHERE op_id = $1 AND person_id = $2
+ "#,
+ )
+ .bind(op_id)
+ .bind(person_id)
+ .execute(&h.ctx.pool)
+ .await
+ .expect("seal like a pre-fence build");
+ sqlx::query("UPDATE lifecycle_op SET step = 'sealed' WHERE op_id = $1")
+ .bind(op_id)
+ .execute(&h.ctx.pool)
+ .await
+ .expect("advance like a pre-fence build");
+
+ let row = h.step(op_id).await.expect("sealed -> unmapped");
+ assert_eq!(row.step, "unmapped");
+ let row = h.step(op_id).await.expect("unmapped -> completed");
+ assert!(row.completed_at.is_some());
+ assert_eq!(FencedHarness::outcome(&row).results[0].outcome, "deleted");
+ assert!(
+ h.leader.calls().is_empty(),
+ "a margin-sealed op must not reach the leader"
+ );
+ let (is_deleted, version, _) = h.ctx.person_state(person_id).await;
+ assert!(is_deleted);
+ assert_eq!(version, 101, "the old margin stays folded into the version");
+
+ h.ctx.cleanup().await.expect("cleanup");
+}
+
+#[tokio::test]
+async fn a_victim_destroyed_before_its_fence_settles_as_not_found() {
+ let h = FencedHarness::new().await;
+ let keep = h
+ .ctx
+ .create_person_via_stub(&format!("fenced-keep-{}", Uuid::now_v7()))
+ .await;
+ let gone = h
+ .ctx
+ .create_person_via_stub(&format!("fenced-gone-{}", Uuid::now_v7()))
+ .await;
+
+ let op_id = Uuid::now_v7();
+ h.engine
+ .create_or_attach(
+ &h.driver,
+ op_id,
+ h.ctx.team_id,
+ &FencedHarness::request(&[keep, gone]),
+ )
+ .await
+ .expect("create op");
+ let row = h.step(op_id).await.expect("started -> marked");
+ assert_eq!(row.step, "marked");
+ // Destroy one victim behind its mark — the anomaly the seal absorbs by
+ // settling it as not_found instead of failing the whole op.
+ sqlx::query("UPDATE posthog_person SET is_deleted = true WHERE team_id = $1 AND id = $2")
+ .bind(h.ctx.team_id as i32)
+ .bind(gone)
+ .execute(&h.ctx.pool)
+ .await
+ .expect("tombstone the victim");
+
+ let row = h.execute(op_id, &[keep, gone]).await.expect("op completes");
+ let outcome = FencedHarness::outcome(&row);
+ assert_eq!(
+ outcome
+ .results
+ .iter()
+ .map(|r| (r.person_id, r.outcome.as_str()))
+ .collect::<Vec<_>>(),
+ vec![(keep, "deleted"), (gone, "not_found")]
+ );
+ let docs = h.leader.death_documents();
+ assert_eq!(docs.len(), 1, "only the live victim gets a death document");
+ assert_eq!(docs[0].person_id, keep);
+
+ h.ctx.cleanup().await.expect("cleanup");
+}
+
#[tokio::test]
async fn full_flow_works_on_a_configured_person_table() {
// Runs create, resolve, and the whole delete saga against
@@ -614,7 +922,9 @@ async fn full_flow_works_on_a_configured_person_table() {
.await
.expect("tombstone row exists");
assert!(is_deleted);
- assert!(version > SEAL_VERSION_MARGIN);
+ // The fence sealed the stub's exact version (0), so the tombstone
+ // lands at 1 — no margin.
+ assert_eq!(version, 1);
let resolved = ctx
.storage
diff --git a/rust/personhog-identity/tests/lifecycle_engine_tests.rs b/rust/personhog-identity/tests/lifecycle_engine_tests.rs
index b06a012065f5..e0fa909924e1 100644
--- a/rust/personhog-identity/tests/lifecycle_engine_tests.rs
+++ b/rust/personhog-identity/tests/lifecycle_engine_tests.rs
@@ -658,3 +658,116 @@ async fn resume_does_not_unpark() {
ctx.cleanup().await.expect("cleanup");
}
+
+/// A concocted Postgres error carrying just a SQLSTATE, so tests can hand
+/// the engine the exact errors Postgres emits for lock conflicts without
+/// manufacturing a real deadlock.
+#[derive(Debug)]
+struct FakePgError(&'static str);
+
+impl std::fmt::Display for FakePgError {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(f, "fake database error ({})", self.0)
+ }
+}
+
+impl std::error::Error for FakePgError {}
+
+impl sqlx::error::DatabaseError for FakePgError {
+ fn message(&self) -> &str {
+ "fake database error"
+ }
+
+ fn code(&self) -> Option<std::borrow::Cow<'_, str>> {
+ Some(std::borrow::Cow::Borrowed(self.0))
+ }
+
+ fn as_error(&self) -> &(dyn std::error::Error + Send + Sync + 'static) {
+ self
+ }
+
+ fn as_error_mut(&mut self) -> &mut (dyn std::error::Error + Send + Sync + 'static) {
+ self
+ }
+
+ fn into_error(self: Box<Self>) -> Box<dyn std::error::Error + Send + Sync + 'static> {
+ self
+ }
+
+ fn kind(&self) -> sqlx::error::ErrorKind {
+ sqlx::error::ErrorKind::Other
+ }
+}
+
+fn db_error(code: &'static str) -> SagaError {
+ SagaError::Db(sqlx::Error::Database(Box::new(FakePgError(code))))
+}
+
+#[test]
+fn database_conflicts_classify_as_retriable() {
+ for code in ["40P01", "40001", "57014"] {
+ assert!(db_error(code).is_db_conflict(), "{code} must be a conflict");
+ }
+ assert!(
+ !db_error("23505").is_db_conflict(),
+ "a unique violation is not a conflict"
+ );
+ assert!(!SagaError::Busy.is_db_conflict());
+}
+
+/// Driver whose first attempts lose a deadlock; 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.
+struct DeadlockingDriver {
+ inner: DummyDriver,
+ fail_first: usize,
+ attempts: AtomicUsize,
+}
+
+#[async_trait]
+impl OpDriver for DeadlockingDriver {
+ fn op_type(&self) -> &'static str {
+ "merge"
+ }
+
+ fn initial_step(&self) -> &'static str {
+ "started"
+ }
+
+ async fn run_step(&self, pool: &PgPool, op: &OpRow) -> Result<(), SagaError> {
+ if self.attempts.fetch_add(1, Ordering::SeqCst) < self.fail_first {
+ return Err(db_error("40P01"));
+ }
+ self.inner.run_step(pool, op).await
+ }
+}
+
+#[tokio::test]
+async fn a_step_that_loses_a_database_conflict_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");
+
+ 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");
+
+ ctx.cleanup().await.expect("cleanup");
+}
diff --git a/rust/personhog-identity/tests/lifecycle_service_tests.rs b/rust/personhog-identity/tests/lifecycle_service_tests.rs
index cb4ba9ed8643..88c23dbac5e9 100644
--- a/rust/personhog-identity/tests/lifecycle_service_tests.rs
+++ b/rust/personhog-identity/tests/lifecycle_service_tests.rs
@@ -1,6 +1,9 @@
+mod common;
+
use std::sync::Arc;
use std::time::Duration;
+use common::sim_leader::SimLeader;
use sqlx::postgres::PgPoolOptions;
use tonic::{Code, Request};
@@ -26,7 +29,7 @@ async fn delete_status(request: DeletePersonsRequest) -> Code {
.connect_lazy("postgres://unused:unused@localhost:1/unused")
.expect("lazy pool never connects");
let engine = Arc::new(Engine::new(
- pool,
+ pool.clone(),
EngineConfig {
lease: Duration::from_secs(1),
execute_timeout: Duration::from_secs(1),
@@ -34,7 +37,12 @@ async fn delete_status(request: DeletePersonsRequest) -> Code {
attempt_alert_threshold: 5,
},
));
- let service = PersonHogLifecycleService::new(engine, IdentityTables::real());
+ let tables = IdentityTables::real();
+ let service = PersonHogLifecycleService::new(
+ engine,
+ Arc::new(SimLeader::new(pool, tables.person.clone())),
+ tables,
+ );
service
.delete_persons(Request::new(request))
.await
diff --git a/rust/personhog-leader/tests/fence_integration.rs b/rust/personhog-leader/tests/fence_integration.rs
index 3414fd2e2d34..b13dcffcb7cd 100644
--- a/rust/personhog-leader/tests/fence_integration.rs
+++ b/rust/personhog-leader/tests/fence_integration.rs
@@ -2355,3 +2355,125 @@ async fn a_folds_target_cache_dirt_is_sanitized() {
serde_json::json!({"dirty": "a\u{FFFD}b"})
);
}
+
+/// The saga's unmap writes the person tombstone straight to PG before the
+/// release runs, and cache pressure can evict the fenced victim in that
+/// window (nothing pins fenced entries). The release's cache miss must not
+/// mistake that direct tombstone for an already-emitted death document.
+/// Today this holds because the PG fallback load filters `is_deleted =
+/// false`, so the release sees no person and takes the cold-leader path,
+/// re-deriving the document from the sealed version — this test pins that
+/// composed behavior against either side changing (the load filter, or the
+/// duplicate-release absorb).
+#[tokio::test]
+async fn a_release_after_a_cache_eviction_still_produces_the_death_document() {
+ let pool = common::create_persons_pool().await;
+ let mut harness = start_fence_harness(
+ test_cached_person(),
+ Some(PgFallback {
+ pool: pool.clone(),
+ table: "posthog_person".to_string(),
+ }),
+ )
+ .await;
+ let team_id = harness.team_id;
+ let partition = harness.partition;
+ let person_id = harness.person_id;
+ let person_uuid = test_cached_person().uuid;
+ let op = Uuid::now_v7();
+
+ sqlx::query(
+ "INSERT INTO lifecycle_op (op_id, op_type, team_id, step, request) \
+ VALUES ($1, 'delete', $2, 'unmapped', '{}'::jsonb)",
+ )
+ .bind(op)
+ .bind(team_id as i32)
+ .execute(&pool)
+ .await
+ .expect("insert op");
+ sqlx::query(
+ "INSERT INTO lifecycle_op_person (op_id, team_id, person_id, person_uuid, role, status) \
+ VALUES ($1, $2, $3, $4::uuid, 'victim', 'sealed')",
+ )
+ .bind(op)
+ .bind(team_id as i32)
+ .bind(person_id)
+ .bind(&person_uuid)
+ .execute(&pool)
+ .await
+ .expect("insert mark");
+
+ let sealed = harness
+ .client
+ .fence_person(with_partition(
+ fence_request(team_id, person_id, &op),
+ partition,
+ ))
+ .await
+ .expect("fence succeeds")
+ .into_inner()
+ .sealed
+ .unwrap();
+ let sealed_version = sealed.version;
+
+ // The unmap transaction's direct tombstone: scrubbed, parked at
+ // sealed + 1.
+ sqlx::query(
+ "INSERT INTO posthog_person \
+ (id, team_id, uuid, properties, created_at, version, is_identified, is_deleted) \
+ VALUES ($1, $2, $3::uuid, '{}'::jsonb, now(), $4, false, true)",
+ )
+ .bind(person_id)
+ .bind(team_id as i32)
+ .bind(&person_uuid)
+ .bind(sealed_version + 1)
+ .execute(&pool)
+ .await
+ .expect("insert unmap tombstone");
+
+ // The eviction: Foyer may drop any entry under capacity pressure, and
+ // nothing pins a fenced victim.
+ harness.cache.remove(
+ partition,
+ &personhog_leader::cache::PersonCacheKey { team_id, person_id },
+ );
+
+ harness
+ .client
+ .release_fence(with_partition(
+ ReleaseFenceRequest {
+ team_id,
+ person_id,
+ person_uuid: person_uuid.clone(),
+ op_id: op.to_string(),
+ outcome: ReleaseOutcome::Committed.into(),
+ sealed_version: Some(sealed_version),
+ created_at: sealed.created_at,
+ },
+ partition,
+ ))
+ .await
+ .expect("committed release succeeds");
+
+ let records = changelog_records(&harness);
+ let death = records.last().expect("the death document must be produced");
+ assert!(death.is_deleted);
+ assert_eq!(death.uuid, person_uuid);
+ assert_eq!(
+ death.version,
+ sealed_version + 1,
+ "the death document confirms the direct tombstone at the same version"
+ );
+
+ sqlx::query("DELETE FROM lifecycle_op WHERE op_id = $1")
+ .bind(op)
+ .execute(&pool)
+ .await
+ .expect("cleanup op");
+ sqlx::query("DELETE FROM posthog_person WHERE team_id = $1 AND id = $2")
+ .bind(team_id as i32)
+ .bind(person_id)
+ .execute(&pool)
+ .await
+ .expect("cleanup person");
+}
diff --git a/rust/personhog-writer/src/pg.rs b/rust/personhog-writer/src/pg.rs
index f6aff7d37089..1c9f74d26f60 100644
--- a/rust/personhog-writer/src/pg.rs
+++ b/rust/personhog-writer/src/pg.rs
@@ -99,9 +99,16 @@ impl PgStore {
/// must halt on. Nothing is ever dropped or substituted here — a silent
/// repair would diverge PG from the cache and changelog.
fn prepare_chunk(persons: &[Person]) -> Result<PreparedArrays<'_>, WriteError> {
- let cap = persons.len();
- let mut arrays = PreparedArrays::with_capacity(cap);
- for person in persons {
+ // Bind order is lock order: the upsert acquires row locks in unnest
+ // order, so binding in conflict-key order gives every flush one global
+ // lock direction. Concurrent multi-row writers on overlapping persons
+ // (the delete saga's unmap, another flush) sort the same way, and
+ // sorted-vs-sorted acquisition cannot deadlock. Only the bind order
+ // changes — batch composition and ack accounting are untouched.
+ let mut sorted: Vec<&Person> = persons.iter().collect();
+ sorted.sort_unstable_by_key(|p| (p.team_id, p.id));
+ let mut arrays = PreparedArrays::with_capacity(sorted.len());
+ for person in sorted {
push_person(&mut arrays, person)?;
}
Ok(arrays)
@@ -414,6 +421,22 @@ mod tests {
}
}
+ #[test]
+ fn prepare_chunk_binds_in_conflict_key_order() {
+ // Bind order is the upsert's lock order; a batch bound in buffer
+ // order deadlocks against concurrent sorted writers on overlapping
+ // rows.
+ let persons = [
+ person_with(5, 2),
+ person_with(3, 1),
+ person_with(4, 2),
+ person_with(1, 1),
+ ];
+ let arrays = prepare_chunk(&persons).expect("chunk prepares");
+ assert_eq!(arrays.team_ids, vec![1, 1, 2, 2]);
+ assert_eq!(arrays.ids, vec![1, 3, 4, 5]);
+ }
+
#[test]
fn prepare_chunk_errors_on_out_of_range_team_id() {
// One unbindable row fails the whole chunk: silently dropping it