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.

fix(personhog): check the leader flag before a merge target attaches (#116628)

Zach Browncbe5afd791db
diff --git a/rust/personhog-identity/src/leader.rs b/rust/personhog-identity/src/leader.rs
index 98babb58d6d9..c83a80742aed 100644
--- a/rust/personhog-identity/src/leader.rs
+++ b/rust/personhog-identity/src/leader.rs
@@ -1,14 +1,33 @@
use async_trait::async_trait;
-use tonic::Status;
+use tonic::{Code, Status};
use personhog_common::client::RouterClient;
use personhog_proto::personhog::types::v1::{
- FencePersonRequest, FencePersonResponse, FencePersonsRequest, FencePersonsResponse,
- FoldPersonDocumentRequest, FoldPersonDocumentResponse, ReleaseFenceRequest,
- ReleaseFenceResponse, ReleaseFencesRequest, ReleaseFencesResponse,
+ ConsistencyLevel, FencePersonRequest, FencePersonResponse, FencePersonsRequest,
+ FencePersonsResponse, FoldPersonDocumentRequest, FoldPersonDocumentResponse,
+ ReleaseFenceRequest, ReleaseFenceResponse, ReleaseFencesRequest, ReleaseFencesResponse,
UpdatePersonPropertiesRequest, UpdatePersonPropertiesResponse,
};
+/// The leader's view of a person's identified flag; identity's own row lags it through the writer.
+#[async_trait]
+pub trait PersonStateReader: Send + Sync {
+ /// `None` when the leader holds no live person under the id.
+ async fn is_identified(&self, team_id: i64, person_id: i64) -> Result<Option<bool>, Status>;
+}
+
+#[async_trait]
+impl PersonStateReader for RouterClient {
+ async fn is_identified(&self, team_id: i64, person_id: i64) -> Result<Option<bool>, Status> {
+ match RouterClient::get_person(self, team_id, person_id, ConsistencyLevel::Strong).await {
+ Ok(person) => Ok(person.map(|person| person.is_identified)),
+ // The leader answers NOT_FOUND for a destroyed or absent person.
+ Err(status) if status.code() == Code::NotFound => Ok(None),
+ Err(status) => Err(status),
+ }
+ }
+}
+
/// Writes initial person properties on the creation branch. Production goes
/// through the router (which routes to the owning leader); tests mock this.
#[async_trait]
diff --git a/rust/personhog-identity/src/main.rs b/rust/personhog-identity/src/main.rs
index 026a9fa4c985..86d1bcfaa1a6 100644
--- a/rust/personhog-identity/src/main.rs
+++ b/rust/personhog-identity/src/main.rs
@@ -337,6 +337,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
let merge_entrance = MergeEntrance::new(
storage.clone(),
property_writer.clone(),
+ property_writer.clone(),
MergeOpExecutor::new(
engine.clone(),
MergeDriver::new(
diff --git a/rust/personhog-identity/src/service/merge.rs b/rust/personhog-identity/src/service/merge.rs
index 360266c7b70f..bc26ef077ec4 100644
--- a/rust/personhog-identity/src/service/merge.rs
+++ b/rust/personhog-identity/src/service/merge.rs
@@ -20,7 +20,7 @@ use personhog_proto::personhog::identity::v1::{
};
use personhog_proto::personhog::types::v1::{Person as ProtoPerson, UpdatePersonPropertiesRequest};
-use crate::leader::PropertyWriter;
+use crate::leader::{PersonStateReader, PropertyWriter};
use crate::lifecycle::engine::OpRow;
use crate::lifecycle::merge::{
record_conflict, record_outcome_count, MergeOpExecutor, MergeOutcome, MergeRequest,
@@ -39,6 +39,8 @@ 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";
+const ESTABLISH_IDENTIFIED_READS_TOTAL: &str =
+ "personhog_identity_merge_establish_identified_reads_total";
fn record_phase(phase: &'static str, start: Instant) {
common_metrics::histogram(
@@ -54,6 +56,7 @@ const PAYLOAD_NUMBERS_CLAMPED_TOTAL: &str =
pub struct MergeEntrance {
storage: Arc<dyn IdentityStorage>,
property_writer: Arc<dyn PropertyWriter>,
+ person_state: Arc<dyn PersonStateReader>,
ops: MergeOpExecutor,
}
@@ -61,11 +64,13 @@ impl MergeEntrance {
pub fn new(
storage: Arc<dyn IdentityStorage>,
property_writer: Arc<dyn PropertyWriter>,
+ person_state: Arc<dyn PersonStateReader>,
ops: MergeOpExecutor,
) -> Self {
Self {
storage,
property_writer,
+ person_state,
ops,
}
}
@@ -433,18 +438,29 @@ impl MergeEntrance {
// 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)
- && !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();
+ let mut first_eligible: Option<&Person> = None;
+ for source in request.sources.iter().filter(|s| {
+ !is_distinct_id_illegal(&s.source_distinct_id)
+ && !is_distinct_id_oversized(&s.source_distinct_id)
+ }) {
+ let Some(person) = resolved.get(&(request.team_id, source.source_distinct_id.clone()))
+ else {
+ break;
+ };
+ if request.allow_identified_sources {
+ first_eligible = Some(person);
+ break;
+ }
+ if person.is_identified {
+ continue;
+ }
+ // The identity row's flag lags the leader's; only the leader can clear the source.
+ if self.leader_identified(request.team_id, person.id).await? != Some(false) {
+ continue;
+ }
+ first_eligible = Some(person);
+ break;
+ }
if let Some(survivor) = first_eligible {
let attached = self
.storage
@@ -507,6 +523,27 @@ impl MergeEntrance {
}
}
+ /// `None` is a person the leader no longer holds, which cannot survive either.
+ async fn leader_identified(
+ &self,
+ team_id: i64,
+ person_id: i64,
+ ) -> Result<Option<bool>, Status> {
+ let identified = self.person_state.is_identified(team_id, person_id).await;
+ let result = match identified {
+ Ok(Some(true)) => "identified",
+ Ok(Some(false)) => "unidentified",
+ Ok(None) => "absent",
+ Err(_) => "error",
+ };
+ common_metrics::inc(
+ ESTABLISH_IDENTIFIED_READS_TOTAL,
+ &[("result".to_string(), result.to_string())],
+ 1,
+ );
+ identified
+ }
+
/// Re-resolve the target distinct id after losing an establishment
/// race. The winner's person is as good a survivor as ours would have
/// been; a mapping that vanished again mid-race sends the caller back
diff --git a/rust/personhog-identity/tests/common/mod.rs b/rust/personhog-identity/tests/common/mod.rs
index 94d609dd0d08..9a924e4bce99 100644
--- a/rust/personhog-identity/tests/common/mod.rs
+++ b/rust/personhog-identity/tests/common/mod.rs
@@ -228,6 +228,17 @@ impl TestContext {
/// instead of a hang or a panic mid-transaction.
pub struct UnusedLeader;
+#[async_trait::async_trait]
+impl personhog_identity::leader::PersonStateReader for UnusedLeader {
+ async fn is_identified(
+ &self,
+ _team_id: i64,
+ _person_id: i64,
+ ) -> Result<Option<bool>, tonic::Status> {
+ Err(tonic::Status::unimplemented("not exercised by this test"))
+ }
+}
+
#[async_trait::async_trait]
impl personhog_identity::leader::PropertyWriter for UnusedLeader {
async fn update_person_properties(
diff --git a/rust/personhog-identity/tests/common/sim_leader.rs b/rust/personhog-identity/tests/common/sim_leader.rs
index e90c8e5ad5e5..2d1f164657f0 100644
--- a/rust/personhog-identity/tests/common/sim_leader.rs
+++ b/rust/personhog-identity/tests/common/sim_leader.rs
@@ -33,7 +33,7 @@ use uuid::Uuid;
use personhog_common::grpc::semantic_refusal;
use personhog_identity::config::IdentityTables;
-use personhog_identity::leader::{LifecycleLeader, PropertyWriter};
+use personhog_identity::leader::{LifecycleLeader, PersonStateReader, PropertyWriter};
use personhog_proto::personhog::types::v1::{
FencePersonRequest, FencePersonResponse, FencePersonsRequest, FencePersonsResponse,
FencedPersonSeal, FoldPersonDocumentRequest, FoldPersonDocumentResponse, LifecycleOpType,
@@ -48,6 +48,7 @@ pub enum Rpc {
Fold,
Release,
PropertyPush,
+ IdentifiedRead,
}
/// A person's live fence in the simulated leader.
@@ -140,6 +141,8 @@ pub struct SimLeader {
/// be ahead of Postgres, which is exactly what the seal-time re-check
/// exists for.
sealed_identified: Mutex<HashMap<i64, bool>>,
+ /// Person ids whose identified flag the entrance read, in order.
+ identified_reads: Mutex<Vec<i64>>,
/// Injected `last_seen_at` per person: leader-side state with no
/// Postgres column.
last_seen: Mutex<HashMap<i64, i64>>,
@@ -158,6 +161,7 @@ impl SimLeader {
deaths: Mutex::new(HashMap::new()),
scripted: Mutex::new(HashMap::new()),
sealed_identified: Mutex::new(HashMap::new()),
+ identified_reads: Mutex::new(Vec::new()),
last_seen: Mutex::new(HashMap::new()),
batch_rpcs_supported: AtomicBool::new(true),
}
@@ -193,6 +197,10 @@ impl SimLeader {
.is_none_or(|queue| queue.is_empty())
}
+ pub fn identified_reads(&self) -> Vec<i64> {
+ self.identified_reads.lock().unwrap().clone()
+ }
+
pub fn set_sealed_identified(&self, person_id: i64, identified: bool) {
self.sealed_identified
.lock()
@@ -204,6 +212,23 @@ impl SimLeader {
self.last_seen.lock().unwrap().insert(person_id, epoch);
}
+ /// Destroy a live person on the leader only; its Postgres row stays.
+ pub async fn declare_dead(&self, team_id: i64, person_id: i64) {
+ let person = self
+ .live_person(team_id, person_id)
+ .await
+ .expect("person must be live to be destroyed");
+ self.deaths.lock().unwrap().insert(
+ person_id,
+ DeathDocument {
+ person_id,
+ person_uuid: person.uuid,
+ version: person.version,
+ created_at: person.created_at,
+ },
+ );
+ }
+
pub fn fence_for(&self, person_id: i64) -> Option<Fence> {
self.fences.lock().unwrap().get(&person_id).copied()
}
@@ -636,6 +661,30 @@ impl LifecycleLeader for SimLeader {
}
}
+/// The leader's flag: the sealed override where one is set, else the live row.
+#[async_trait]
+impl PersonStateReader for SimLeader {
+ async fn is_identified(&self, team_id: i64, person_id: i64) -> Result<Option<bool>, Status> {
+ self.identified_reads.lock().unwrap().push(person_id);
+ if let Some(status) = self.take_scripted(Rpc::IdentifiedRead, person_id) {
+ return Err(status);
+ }
+ if self.deaths.lock().unwrap().contains_key(&person_id) {
+ return Ok(None);
+ }
+ let Some(person) = self.live_person(team_id, person_id).await else {
+ return Ok(None);
+ };
+ let overridden = self
+ .sealed_identified
+ .lock()
+ .unwrap()
+ .get(&person_id)
+ .copied();
+ Ok(Some(overridden.unwrap_or(person.is_identified)))
+ }
+}
+
/// The RPC's inline path pushes the merge event's properties through the
/// ordinary write surface; the sim applies the same admission rules as
/// any other write, so a push to a fenced or destroyed person fails the
diff --git a/rust/personhog-identity/tests/lifecycle_merge_tests.rs b/rust/personhog-identity/tests/lifecycle_merge_tests.rs
index a8cf6af0e34b..0997cac5fcf1 100644
--- a/rust/personhog-identity/tests/lifecycle_merge_tests.rs
+++ b/rust/personhog-identity/tests/lifecycle_merge_tests.rs
@@ -1749,6 +1749,7 @@ impl MergeHarness {
MergeEntrance::new(
storage,
self.leader.clone(),
+ self.leader.clone(),
MergeOpExecutor::new(
engine,
MergeDriver::new(
@@ -1775,6 +1776,7 @@ impl MergeHarness {
MergeEntrance::new(
self.ctx.storage.clone(),
self.leader.clone(),
+ self.leader.clone(),
MergeOpExecutor::new(
engine,
MergeDriver::new(
@@ -2434,6 +2436,134 @@ async fn a_call_that_lost_the_birth_race_does_not_stamp_its_creator() {
h.ctx.cleanup().await.expect("cleanup");
}
+#[tokio::test]
+async fn a_source_the_leader_marks_identified_is_not_an_eligible_survivor_while_the_row_lags() {
+ // The identity row still says unidentified; only the leader has flipped it.
+ let h = MergeHarness::new().await;
+ let service = h.service();
+ let source = h
+ .ctx
+ .insert_person_with_distinct_id("lag-ident-source")
+ .await;
+ h.leader.set_sealed_identified(source, true);
+
+ let request = rpc_request(
+ h.ctx.team_id,
+ "lag-target",
+ &["lag-ident-source"],
+ Uuid::now_v7(),
+ );
+ let response = service
+ .merge_persons(Request::new(request))
+ .await
+ .expect("call succeeds")
+ .into_inner();
+
+ let survivor = response.survivor.as_ref().expect("survivor present");
+ assert_ne!(survivor.id, source);
+ assert_eq!(
+ survivor.uuid,
+ person_uuid(h.ctx.team_id, "lag-target").to_string()
+ );
+ assert_eq!(
+ rpc_outcomes(&response),
+ vec![(
+ "lag-ident-source".to_string(),
+ MergeSourceOutcome::SkippedAlreadyIdentified
+ )]
+ );
+ assert_eq!(h.leader.identified_reads(), vec![source]);
+
+ h.ctx.cleanup().await.expect("cleanup");
+}
+
+#[tokio::test]
+async fn a_source_destroyed_on_the_leader_is_skipped_and_the_target_is_born() {
+ // The identity row still resolves the source; the leader has destroyed it.
+ let h = MergeHarness::new().await;
+ let service = h.service();
+ let source = h.ctx.insert_person_with_distinct_id("dead-source").await;
+ h.leader.declare_dead(h.ctx.team_id, source).await;
+
+ let request = rpc_request(
+ h.ctx.team_id,
+ "dead-target",
+ &["dead-source"],
+ Uuid::now_v7(),
+ );
+ let response = service
+ .merge_persons(Request::new(request))
+ .await
+ .expect("call succeeds")
+ .into_inner();
+
+ let survivor = response.survivor.as_ref().expect("survivor present");
+ assert_eq!(
+ survivor.uuid,
+ person_uuid(h.ctx.team_id, "dead-target").to_string()
+ );
+ assert_eq!(
+ rpc_outcomes(&response),
+ vec![("dead-source".to_string(), MergeSourceOutcome::Error)]
+ );
+ assert_eq!(h.leader.identified_reads(), vec![source]);
+
+ h.ctx.cleanup().await.expect("cleanup");
+}
+
+#[tokio::test]
+async fn a_failed_leader_read_fails_the_call_and_attaches_nothing() {
+ // The identity row says unidentified; the row alone must not clear the source.
+ let h = MergeHarness::new().await;
+ let service = h.service();
+ let source = h
+ .ctx
+ .insert_person_with_distinct_id("readfail-source")
+ .await;
+ h.leader.fail_next(
+ Rpc::IdentifiedRead,
+ source,
+ Status::unavailable("leader down"),
+ );
+
+ let op_id = Uuid::now_v7();
+ let request = rpc_request(
+ h.ctx.team_id,
+ "readfail-target",
+ &["readfail-source"],
+ op_id,
+ );
+ let status = service
+ .merge_persons(Request::new(request))
+ .await
+ .expect_err("a failed leader read fails the call");
+ assert_eq!(status.code(), Code::Unavailable);
+ assert!(h.leader.scripted_drained(Rpc::IdentifiedRead, source));
+
+ let target_rows: i64 = sqlx::query_scalar(&format!(
+ "SELECT count(*) FROM {} WHERE team_id = $1 AND distinct_id = $2",
+ h.ctx.tables.person_distinct_id
+ ))
+ .bind(h.ctx.team_id as i32)
+ .bind("readfail-target")
+ .fetch_one(&h.ctx.pool)
+ .await
+ .unwrap();
+ assert_eq!(target_rows, 0);
+ let op_count: i64 = sqlx::query_scalar(&format!(
+ "SELECT count(*) FROM {} WHERE op_id = $1",
+ h.ctx.tables.lifecycle_op
+ ))
+ .bind(op_id)
+ .fetch_one(&h.ctx.pool)
+ .await
+ .unwrap();
+ assert_eq!(op_count, 0);
+ assert!(h.leader.calls().is_empty());
+
+ h.ctx.cleanup().await.expect("cleanup");
+}
+
#[tokio::test]
async fn an_identified_source_is_not_an_eligible_survivor_for_an_unresolved_target() {
let h = MergeHarness::new().await;
diff --git a/rust/personhog-identity/tests/service_tests.rs b/rust/personhog-identity/tests/service_tests.rs
index e079ce260004..db06dac0eb98 100644
--- a/rust/personhog-identity/tests/service_tests.rs
+++ b/rust/personhog-identity/tests/service_tests.rs
@@ -7,7 +7,7 @@ use async_trait::async_trait;
use common::TestContext;
use tonic::{Code, Request, Status};
-use personhog_identity::leader::PropertyWriter;
+use personhog_identity::leader::{PersonStateReader, PropertyWriter};
use personhog_identity::lifecycle::merge::{MergeDriver, MergeOpExecutor};
use personhog_identity::service::merge::MergeEntrance;
use personhog_identity::service::validation::RequestLimits;
@@ -39,6 +39,14 @@ impl MockPropertyWriter {
}
}
+/// These tests seed the identity row directly, so the leader agrees with it.
+#[async_trait]
+impl PersonStateReader for MockPropertyWriter {
+ async fn is_identified(&self, _team_id: i64, _person_id: i64) -> Result<Option<bool>, Status> {
+ Ok(Some(false))
+ }
+}
+
#[async_trait]
impl PropertyWriter for MockPropertyWriter {
async fn update_person_properties(
@@ -82,6 +90,7 @@ impl ServiceTestContext {
let merge = MergeEntrance::new(
ctx.storage.clone(),
writer.clone(),
+ writer.clone(),
MergeOpExecutor::new(
engine,
MergeDriver::new(