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): publish person merge events from the publisher (#117139)

José Sequeira181ab6bd2273
diff --git a/rust/personhog-identity/.sqlx/query-1de76b4da6cd1b262c612d88ea08b03a1f58ee11e1b91776a39f7217a0720ed9.json b/rust/personhog-identity/.sqlx/query-1de76b4da6cd1b262c612d88ea08b03a1f58ee11e1b91776a39f7217a0720ed9.json
new file mode 100644
index 000000000000..64f368b044e4
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-1de76b4da6cd1b262c612d88ea08b03a1f58ee11e1b91776a39f7217a0720ed9.json
@@ -0,0 +1,28 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "/* service='personhog-identity', operation='publish_merged_sources' */ \n SELECT person_id, person_uuid FROM lifecycle_op_person\n WHERE op_id = $1 AND role = 'source' AND status = 'deleted'\n ORDER BY person_id\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "person_id",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 1,
+ "name": "person_uuid",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ false
+ ]
+ },
+ "hash": "1de76b4da6cd1b262c612d88ea08b03a1f58ee11e1b91776a39f7217a0720ed9"
+}
diff --git a/rust/personhog-identity/.sqlx/query-3644e5988dc099d5b37e28ac930db20f0d829037c735bb11ddfc77d7de765183.json b/rust/personhog-identity/.sqlx/query-3644e5988dc099d5b37e28ac930db20f0d829037c735bb11ddfc77d7de765183.json
new file mode 100644
index 000000000000..13dfd1261f9a
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-3644e5988dc099d5b37e28ac930db20f0d829037c735bb11ddfc77d7de765183.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "/* service='personhog-identity', operation='publish_load_outcome_results' */ SELECT outcome -> 'results' AS \"results: Value\" FROM lifecycle_op_tmp WHERE op_id = $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "results: Value",
+ "type_info": "Jsonb"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "3644e5988dc099d5b37e28ac930db20f0d829037c735bb11ddfc77d7de765183"
+}
diff --git a/rust/personhog-identity/.sqlx/query-54e3a67cc43e9d80047e350828607ebab0f5d102a4cff055f32a40106983f3d3.json b/rust/personhog-identity/.sqlx/query-54e3a67cc43e9d80047e350828607ebab0f5d102a4cff055f32a40106983f3d3.json
new file mode 100644
index 000000000000..ff4218d321ab
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-54e3a67cc43e9d80047e350828607ebab0f5d102a4cff055f32a40106983f3d3.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "/* service='personhog-identity', operation='publish_load_outcome_results' */ SELECT outcome -> 'results' AS \"results: Value\" FROM lifecycle_op WHERE op_id = $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "results: Value",
+ "type_info": "Jsonb"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "54e3a67cc43e9d80047e350828607ebab0f5d102a4cff055f32a40106983f3d3"
+}
diff --git a/rust/personhog-identity/.sqlx/query-b389791503e2ac01778fcd7af7d175067fa7c9fc2f30254df1451203dca2e248.json b/rust/personhog-identity/.sqlx/query-77310c44e1b1635bc70bd2d67ad58b0e760a5023d1f530d0d726bd9cf0353a9a.json
similarity index 53%
rename from rust/personhog-identity/.sqlx/query-b389791503e2ac01778fcd7af7d175067fa7c9fc2f30254df1451203dca2e248.json
rename to rust/personhog-identity/.sqlx/query-77310c44e1b1635bc70bd2d67ad58b0e760a5023d1f530d0d726bd9cf0353a9a.json
index 2ff774bc398d..75d7f2061a8f 100644
--- a/rust/personhog-identity/.sqlx/query-b389791503e2ac01778fcd7af7d175067fa7c9fc2f30254df1451203dca2e248.json
+++ b/rust/personhog-identity/.sqlx/query-77310c44e1b1635bc70bd2d67ad58b0e760a5023d1f530d0d726bd9cf0353a9a.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "/* service='personhog-identity', operation='publish_load_op' */ \n SELECT op.op_type, op.completed_at,\n (SELECT count(*) FROM lifecycle_op_person lop\n WHERE lop.op_id = op.op_id AND lop.role = 'target') AS \"target_rows!\",\n (SELECT count(*) FROM lifecycle_op_person lop\n WHERE lop.op_id = op.op_id\n AND lop.role IN ('source', 'victim')\n AND lop.moved IS NOT NULL\n AND jsonb_typeof(lop.moved) <> 'array') AS \"malformed_moved_rows!\"\n FROM lifecycle_op op\n WHERE op.op_id = $1\n ",
+ "query": "/* service='personhog-identity', operation='publish_load_op' */ \n SELECT op.op_type, op.completed_at,\n (SELECT count(*) FROM lifecycle_op_person lop\n WHERE lop.op_id = op.op_id AND lop.role = 'target') AS \"target_rows!\",\n (SELECT lop.person_uuid FROM lifecycle_op_person lop\n WHERE lop.op_id = op.op_id AND lop.role = 'target'\n ORDER BY lop.person_id LIMIT 1) AS target_uuid,\n (SELECT count(*) FROM lifecycle_op_person lop\n WHERE lop.op_id = op.op_id\n AND lop.role IN ('source', 'victim')\n AND lop.moved IS NOT NULL\n AND jsonb_typeof(lop.moved) <> 'array') AS \"malformed_moved_rows!\"\n FROM lifecycle_op op\n WHERE op.op_id = $1\n ",
"describe": {
"columns": [
{
@@ -20,6 +20,11 @@
},
{
"ordinal": 3,
+ "name": "target_uuid",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 4,
"name": "malformed_moved_rows!",
"type_info": "Int8"
}
@@ -33,8 +38,9 @@
false,
true,
null,
+ null,
null
]
},
- "hash": "b389791503e2ac01778fcd7af7d175067fa7c9fc2f30254df1451203dca2e248"
+ "hash": "77310c44e1b1635bc70bd2d67ad58b0e760a5023d1f530d0d726bd9cf0353a9a"
}
diff --git a/rust/personhog-identity/.sqlx/query-b5521b75e04fe28f5f99904a76e487644986ee16c9a8895379eecf132811cc4e.json b/rust/personhog-identity/.sqlx/query-b5521b75e04fe28f5f99904a76e487644986ee16c9a8895379eecf132811cc4e.json
new file mode 100644
index 000000000000..480a16550dbd
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-b5521b75e04fe28f5f99904a76e487644986ee16c9a8895379eecf132811cc4e.json
@@ -0,0 +1,28 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "/* service='personhog-identity', operation='publish_merged_sources' */ \n SELECT person_id, person_uuid FROM lifecycle_op_person_tmp\n WHERE op_id = $1 AND role = 'source' AND status = 'deleted'\n ORDER BY person_id\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "person_id",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 1,
+ "name": "person_uuid",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ false
+ ]
+ },
+ "hash": "b5521b75e04fe28f5f99904a76e487644986ee16c9a8895379eecf132811cc4e"
+}
diff --git a/rust/personhog-identity/.sqlx/query-1caac56dd992b4ff190a6fa1a88af273e94e77fb1aca4463dbe2cf128343a500.json b/rust/personhog-identity/.sqlx/query-ed9140b030afa2c2cf0a8f94c155a264fffbe8cfa0ca63c4354041d44aeb715e.json
similarity index 52%
rename from rust/personhog-identity/.sqlx/query-1caac56dd992b4ff190a6fa1a88af273e94e77fb1aca4463dbe2cf128343a500.json
rename to rust/personhog-identity/.sqlx/query-ed9140b030afa2c2cf0a8f94c155a264fffbe8cfa0ca63c4354041d44aeb715e.json
index b27460fc35c2..61b17647c38f 100644
--- a/rust/personhog-identity/.sqlx/query-1caac56dd992b4ff190a6fa1a88af273e94e77fb1aca4463dbe2cf128343a500.json
+++ b/rust/personhog-identity/.sqlx/query-ed9140b030afa2c2cf0a8f94c155a264fffbe8cfa0ca63c4354041d44aeb715e.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "/* service='personhog-identity', operation='publish_load_op' */ \n SELECT op.op_type, op.completed_at,\n (SELECT count(*) FROM lifecycle_op_person_tmp lop\n WHERE lop.op_id = op.op_id AND lop.role = 'target') AS \"target_rows!\",\n (SELECT count(*) FROM lifecycle_op_person_tmp lop\n WHERE lop.op_id = op.op_id\n AND lop.role IN ('source', 'victim')\n AND lop.moved IS NOT NULL\n AND jsonb_typeof(lop.moved) <> 'array') AS \"malformed_moved_rows!\"\n FROM lifecycle_op_tmp op\n WHERE op.op_id = $1\n ",
+ "query": "/* service='personhog-identity', operation='publish_load_op' */ \n SELECT op.op_type, op.completed_at,\n (SELECT count(*) FROM lifecycle_op_person_tmp lop\n WHERE lop.op_id = op.op_id AND lop.role = 'target') AS \"target_rows!\",\n (SELECT lop.person_uuid FROM lifecycle_op_person_tmp lop\n WHERE lop.op_id = op.op_id AND lop.role = 'target'\n ORDER BY lop.person_id LIMIT 1) AS target_uuid,\n (SELECT count(*) FROM lifecycle_op_person_tmp lop\n WHERE lop.op_id = op.op_id\n AND lop.role IN ('source', 'victim')\n AND lop.moved IS NOT NULL\n AND jsonb_typeof(lop.moved) <> 'array') AS \"malformed_moved_rows!\"\n FROM lifecycle_op_tmp op\n WHERE op.op_id = $1\n ",
"describe": {
"columns": [
{
@@ -20,6 +20,11 @@
},
{
"ordinal": 3,
+ "name": "target_uuid",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 4,
"name": "malformed_moved_rows!",
"type_info": "Int8"
}
@@ -33,8 +38,9 @@
false,
true,
null,
+ null,
null
]
},
- "hash": "1caac56dd992b4ff190a6fa1a88af273e94e77fb1aca4463dbe2cf128343a500"
+ "hash": "ed9140b030afa2c2cf0a8f94c155a264fffbe8cfa0ca63c4354041d44aeb715e"
}
diff --git a/rust/personhog-identity/src/bin/publisher.rs b/rust/personhog-identity/src/bin/publisher.rs
index 76d8ae716096..417284b77a6a 100644
--- a/rust/personhog-identity/src/bin/publisher.rs
+++ b/rust/personhog-identity/src/bin/publisher.rs
@@ -1,8 +1,8 @@
//! `personhog-publisher`: drains the publish outbox that personhog-identity
-//! writes and produces the ClickHouse distinct id feed. A separate
-//! deployment because publish load follows the create rate and merge sizes
-//! while identity load follows RPC traffic, and because a Kafka outage must
-//! hold this process's connections, not identity's.
+//! writes and produces the ClickHouse distinct id feed and the person merge
+//! events. A separate deployment because publish load follows the create
+//! rate and merge sizes while identity load follows RPC traffic, and because
+//! a Kafka outage must hold this process's connections, not identity's.
use std::time::Duration;
@@ -18,7 +18,7 @@ use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::util::SubscriberInitExt;
use tracing_subscriber::EnvFilter;
-use personhog_identity::publish::config::PublisherConfig;
+use personhog_identity::publish::config::{MergeEventsAllowlist, PublisherConfig};
use personhog_identity::publish::sink::KafkaSink;
use personhog_identity::publish::Publisher;
@@ -51,7 +51,11 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
let tables = config.tables();
tables.validate().expect("Invalid identity table set");
- let drain_config = config.drain_config();
+ let kafka = config.kafka().expect("Invalid Kafka producer settings");
+ let merge_events = config
+ .merge_events()
+ .expect("Invalid PERSON_MERGE_EVENTS settings");
+ let drain_config = config.drain_config(merge_events.as_ref());
tracing::info!("Starting personhog-publisher");
tracing::info!("Metrics port: {}", config.metrics_port);
@@ -62,12 +66,32 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
max_rows_per_pass = drain_config.max_rows_per_pass,
interval_ms = drain_config.interval.as_millis() as u64,
produce_timeout_ms = config.produce_timeout().as_millis() as u64,
+ partitioner = ?kafka.kafka_producer_partitioner,
"Publish settings"
);
+ match &merge_events {
+ Some(settings) => {
+ tracing::info!(
+ topic = %settings.topic,
+ team_allowlist = ?settings.team_allowlist,
+ "Person merge events enabled"
+ );
+ // The cohort seeder reads an empty allowlist as every team, so
+ // a value copied from there silences this one without an error.
+ if matches!(&settings.team_allowlist, MergeEventsAllowlist::Teams(teams) if teams.is_empty())
+ {
+ tracing::warn!(
+ "PERSON_MERGE_EVENTS_TEAM_ALLOWLIST is empty, which allows no team; no merge event will be produced"
+ );
+ }
+ }
+ None => tracing::info!("Person merge events disabled"),
+ }
if tables.is_validation() {
tracing::warn!(
outbox = %tables.person_publish_outbox,
distinct_id_topic = %config.person_distinct_id_topic,
+ merge_events_topic = ?merge_events.as_ref().map(|s| s.topic.as_str()),
"Publisher runs on the validation table set; its topics must be capture topics, never the production names"
);
}
@@ -123,7 +147,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
let pool = get_pool_with_config(&config.primary_database_url, config.pool_config())
.expect("Failed to create database pool");
- let producer = match create_kafka_producer(&config.kafka, kafka_handle.clone()).await {
+ let producer = match create_kafka_producer(&kafka, kafka_handle.clone()).await {
Ok(producer) => producer,
Err(e) => {
tracing::error!(error = %e, "failed to create Kafka producer");
@@ -135,6 +159,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
let sink = KafkaSink::new(
producer,
config.person_distinct_id_topic.clone(),
+ merge_events.as_ref().map(|s| s.topic.clone()),
config.produce_timeout(),
);
let publisher = Publisher::new(pool, tables, sink, drain_config);
diff --git a/rust/personhog-identity/src/publish/config.rs b/rust/personhog-identity/src/publish/config.rs
index 5c0001450a4b..0d32438f0947 100644
--- a/rust/personhog-identity/src/publish/config.rs
+++ b/rust/personhog-identity/src/publish/config.rs
@@ -1,3 +1,4 @@
+use std::collections::HashSet;
use std::time::Duration;
use common_database::PoolConfig;
@@ -7,6 +8,14 @@ use envconfig::Envconfig;
use crate::config::{IdentityTables, IdentityTablesConfig};
use crate::publish::DrainConfig;
+/// librdkafka's Java-compatible partitioner. The cohort stream processor
+/// keeps each person's state on the worker that this placement selects for
+/// `team_id:person_uuid`, and every producer it reads from (the cohort
+/// seeder, the cohort event shuffler, Node, which computes the partition
+/// itself) places keys this way. librdkafka's own default is CRC32 based
+/// and routes the same key elsewhere, and nothing downstream reports it.
+pub const MURMUR2_RANDOM: &str = "murmur2_random";
+
#[derive(Envconfig, Clone)]
pub struct PublisherConfig {
/// The persons primary identity writes to; the outbox lives there.
@@ -69,10 +78,68 @@ pub struct PublisherConfig {
/// tables, a capture topic behind the validation set.
pub person_distinct_id_topic: String,
+ #[envconfig(default = "false")]
+ pub person_merge_events_enabled: bool,
+
+ /// Required when merge events are enabled; no default, for the same
+ /// reason as the distinct id topic.
+ pub person_merge_events_topic: Option<String>,
+
+ /// Teams whose merges emit `person_merge_events`: comma separated team
+ /// ids, `*` for every team, empty for none. Same syntax and default as
+ /// the Node setting. The cohort seeder's own allowlist must cover the
+ /// same teams but reads an empty value as every team, so copy the ids
+ /// across, not the string.
+ #[envconfig(default = "2")]
+ pub person_merge_events_team_allowlist: String,
+
+ /// Read through [`PublisherConfig::kafka`], which pins the partitioner.
#[envconfig(nested = true)]
pub kafka: KafkaConfig,
}
+/// Teams whose merges emit `person_merge_events`, with Node's
+/// PERSON_MERGE_EVENTS_TEAM_ALLOWLIST contract: `*` is every team and empty
+/// is no team. Not `common_types::cohort::TeamAllowlist`, which reads an
+/// empty value as every team and accepts ranges.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub enum MergeEventsAllowlist {
+ All,
+ Teams(HashSet<i64>),
+}
+
+impl MergeEventsAllowlist {
+ /// An entry that is not a team id is an error instead of a silently
+ /// dropped team, so a typo cannot close the gate for one team unnoticed.
+ pub fn parse(value: &str) -> Result<Self, String> {
+ let value = value.trim();
+ if value == "*" {
+ return Ok(Self::All);
+ }
+ let mut teams = HashSet::new();
+ for entry in value.split(',').map(str::trim).filter(|e| !e.is_empty()) {
+ let team_id = entry
+ .parse::<i64>()
+ .map_err(|_| format!("invalid team id {entry:?} in team allowlist {value:?}"))?;
+ teams.insert(team_id);
+ }
+ Ok(Self::Teams(teams))
+ }
+
+ pub fn allows(&self, team_id: i64) -> bool {
+ match self {
+ Self::All => true,
+ Self::Teams(teams) => teams.contains(&team_id),
+ }
+ }
+}
+
+#[derive(Clone, Debug)]
+pub struct MergeEventsSettings {
+ pub topic: String,
+ pub team_allowlist: MergeEventsAllowlist,
+}
+
impl PublisherConfig {
pub fn tables(&self) -> IdentityTables {
self.tables.tables()
@@ -92,12 +159,46 @@ impl PublisherConfig {
}
}
- pub fn drain_config(&self) -> DrainConfig {
+ pub fn kafka(&self) -> Result<KafkaConfig, String> {
+ let mut kafka = self.kafka.clone();
+ match kafka.kafka_producer_partitioner.as_deref() {
+ None => kafka.kafka_producer_partitioner = Some(MURMUR2_RANDOM.to_string()),
+ Some(MURMUR2_RANDOM) => {}
+ Some(other) => {
+ return Err(format!(
+ "KAFKA_PRODUCER_PARTITIONER must be {MURMUR2_RANDOM} or unset, got {other:?}: person_merge_events are placed by key"
+ ))
+ }
+ }
+ Ok(kafka)
+ }
+
+ pub fn merge_events(&self) -> Result<Option<MergeEventsSettings>, String> {
+ if !self.person_merge_events_enabled {
+ return Ok(None);
+ }
+ let topic = self
+ .person_merge_events_topic
+ .clone()
+ .filter(|t| !t.trim().is_empty())
+ .ok_or_else(|| {
+ "PERSON_MERGE_EVENTS_ENABLED is set but PERSON_MERGE_EVENTS_TOPIC is not"
+ .to_string()
+ })?;
+ let team_allowlist = MergeEventsAllowlist::parse(&self.person_merge_events_team_allowlist)?;
+ Ok(Some(MergeEventsSettings {
+ topic,
+ team_allowlist,
+ }))
+ }
+
+ pub fn drain_config(&self, merge_events: Option<&MergeEventsSettings>) -> DrainConfig {
DrainConfig {
batch_size: self.lifecycle_publish_batch_size,
max_rows_per_pass: self.lifecycle_publish_max_rows_per_pass,
interval: Duration::from_millis(self.lifecycle_publish_interval_ms),
lag_alert: Duration::from_secs(self.lifecycle_publish_lag_alert_secs),
+ merge_events: merge_events.map(|settings| settings.team_allowlist.clone()),
}
}
@@ -115,3 +216,93 @@ impl PublisherConfig {
self.produce_timeout() + Duration::from_millis(self.statement_timeout_ms)
}
}
+
+#[cfg(test)]
+mod tests {
+ use std::collections::{HashMap, HashSet};
+
+ use envconfig::Envconfig;
+
+ use super::{MergeEventsAllowlist, PublisherConfig, MURMUR2_RANDOM};
+
+ fn config(extra: &[(&str, &str)]) -> PublisherConfig {
+ let mut env: HashMap<String, String> =
+ HashMap::from([("PERSON_DISTINCT_ID_TOPIC".to_string(), "t".to_string())]);
+ for (key, value) in extra {
+ env.insert(key.to_string(), value.to_string());
+ }
+ PublisherConfig::init_from_hashmap(&env).expect("config initializes")
+ }
+
+ // Node reads an empty value as no team and `*` as every team; the cohort
+ // crates read empty as every team, so a parser that drifted either way
+ // would open or close the gate for every team unnoticed.
+ #[test]
+ fn team_allowlist_follows_the_node_syntax() {
+ let cases = [
+ ("", Some(MergeEventsAllowlist::Teams(HashSet::new()))),
+ ("*", Some(MergeEventsAllowlist::All)),
+ (
+ "2,125931",
+ Some(MergeEventsAllowlist::Teams(HashSet::from([2, 125931]))),
+ ),
+ (
+ " 2 , 3 ",
+ Some(MergeEventsAllowlist::Teams(HashSet::from([2, 3]))),
+ ),
+ ("1000:2000", None),
+ ];
+ for (input, expected) in cases {
+ assert_eq!(
+ MergeEventsAllowlist::parse(input).ok(),
+ expected,
+ "input {input:?}"
+ );
+ }
+ assert!(MergeEventsAllowlist::All.allows(7));
+ assert!(!MergeEventsAllowlist::Teams(HashSet::new()).allows(7));
+ }
+
+ #[test]
+ fn the_producer_partitioner_is_pinned_to_murmur2_random() {
+ assert_eq!(
+ config(&[])
+ .kafka()
+ .unwrap()
+ .kafka_producer_partitioner
+ .as_deref(),
+ Some(MURMUR2_RANDOM)
+ );
+ assert_eq!(
+ config(&[("KAFKA_PRODUCER_PARTITIONER", MURMUR2_RANDOM)])
+ .kafka()
+ .unwrap()
+ .kafka_producer_partitioner
+ .as_deref(),
+ Some(MURMUR2_RANDOM)
+ );
+ assert!(
+ config(&[("KAFKA_PRODUCER_PARTITIONER", "consistent_random")])
+ .kafka()
+ .is_err()
+ );
+ }
+
+ #[test]
+ fn merge_events_need_a_topic_once_enabled() {
+ assert!(config(&[]).merge_events().unwrap().is_none());
+ assert!(config(&[("PERSON_MERGE_EVENTS_ENABLED", "true")])
+ .merge_events()
+ .is_err());
+ let settings = config(&[
+ ("PERSON_MERGE_EVENTS_ENABLED", "true"),
+ ("PERSON_MERGE_EVENTS_TOPIC", "person_merge_events_capture"),
+ ("PERSON_MERGE_EVENTS_TEAM_ALLOWLIST", "*"),
+ ])
+ .merge_events()
+ .unwrap()
+ .expect("enabled");
+ assert_eq!(settings.topic, "person_merge_events_capture");
+ assert_eq!(settings.team_allowlist, MergeEventsAllowlist::All);
+ }
+}
diff --git a/rust/personhog-identity/src/publish/messages.rs b/rust/personhog-identity/src/publish/messages.rs
index 8bcc1a283c68..839d3a2e9ccb 100644
--- a/rust/personhog-identity/src/publish/messages.rs
+++ b/rust/personhog-identity/src/publish/messages.rs
@@ -1,7 +1,8 @@
//! Wire payloads the publisher produces. Field names and types are the
//! Node ingestion worker's, byte for byte: the ClickHouse Kafka engine
-//! table, `flags-consumer` and the hogflow subscription matcher all decode
-//! the same topic whichever path produced the row.
+//! table, `flags-consumer`, the hogflow subscription matcher and the cohort
+//! stream processor all decode the same topics whichever path produced the
+//! message.
use serde::Serialize;
use uuid::Uuid;
@@ -19,6 +20,32 @@ pub struct DistinctIdRow {
pub is_deleted: u8,
}
+/// Mirrors `MERGE_EVENT_SCHEMA_VERSION` in the cohort stream processor.
+pub const MERGE_EVENT_SCHEMA_VERSION: u32 = 1;
+
+/// One `person_merge_events` message: the committed merge of
+/// `old_person_uuid` into `new_person_uuid`. The cohort stream processor
+/// reads `team_id` as i32, `merged_at_ms` as i64 and `schema_version` as
+/// u32, so each has to serialize as a JSON number. It is produced under
+/// [`PersonMergeEvent::key`]; the partitioner that places the key is
+/// pinned by [`crate::publish::config::MURMUR2_RANDOM`].
+#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
+pub struct PersonMergeEvent {
+ pub team_id: i32,
+ pub old_person_uuid: Uuid,
+ pub new_person_uuid: Uuid,
+ pub merged_at_ms: i64,
+ pub schema_version: u32,
+}
+
+impl PersonMergeEvent {
+ /// Node's key, `"{team_id}:{old_person_uuid}"`: the old person, because
+ /// its state is what the merge moves.
+ pub fn key(&self) -> String {
+ format!("{}:{}", self.team_id, self.old_person_uuid)
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -39,4 +66,20 @@ mod tests {
r#"{"person_id":"01928aaa-bbbb-cccc-dddd-eeeeeeeeeeee","team_id":2,"distinct_id":"user-1","version":3,"is_deleted":1}"#
);
}
+
+ #[test]
+ fn merge_event_serializes_and_keys_exactly_as_the_node_producer_does() {
+ let event = PersonMergeEvent {
+ team_id: 2,
+ old_person_uuid: Uuid::parse_str("01928aaa-bbbb-cccc-dddd-eeeeeeeeeeee").unwrap(),
+ new_person_uuid: Uuid::parse_str("01928bbb-cccc-dddd-eeee-ffffffffffff").unwrap(),
+ merged_at_ms: 1_700_000_000_000,
+ schema_version: MERGE_EVENT_SCHEMA_VERSION,
+ };
+ assert_eq!(event.key(), "2:01928aaa-bbbb-cccc-dddd-eeeeeeeeeeee");
+ assert_eq!(
+ serde_json::to_string(&event).unwrap(),
+ r#"{"team_id":2,"old_person_uuid":"01928aaa-bbbb-cccc-dddd-eeeeeeeeeeee","new_person_uuid":"01928bbb-cccc-dddd-eeee-ffffffffffff","merged_at_ms":1700000000000,"schema_version":1}"#
+ );
+ }
}
diff --git a/rust/personhog-identity/src/publish/mod.rs b/rust/personhog-identity/src/publish/mod.rs
index e1b7508d449a..6ab78cf38af6 100644
--- a/rust/personhog-identity/src/publish/mod.rs
+++ b/rust/personhog-identity/src/publish/mod.rs
@@ -2,22 +2,26 @@
//! (kinds `create` and `attach`) that publishes as it is, and an op pointer
//! (kinds `merge_op` and `delete_op`) that resolves against the saga's
//! `moved` records. Identity enqueues pointers in
-//! [`crate::lifecycle::engine::complete_op_in_tx`]; this module drains the
-//! outbox to Kafka from the separate `personhog-publisher` binary.
+//! [`crate::lifecycle::engine::complete_op_in_tx`] and mapping rows from the
+//! stub-create and attach paths; this module drains the outbox to Kafka from
+//! the separate `personhog-publisher` binary.
//!
//! One pass is one transaction: claim the oldest pending rows with `FOR
//! UPDATE SKIP LOCKED`, resolve pointers against `moved` within a per-pass
//! row budget, produce, await every ack, then delete finished rows, advance
-//! unfinished pointers, defer rows that cannot be read, and commit. A
-//! produce error rolls the whole pass back, so the only failure mode is a
-//! repeat publish, which every consumer of these topics absorbs by version.
+//! unfinished pointers, defer rows that cannot be read, and commit. A merge
+//! pointer's final chunk also carries that merge's `person_merge_events`,
+//! one per merged source person, so they go out in the pass that deletes
+//! the pointer and never once per chunk. A produce error rolls the whole
+//! pass back, so the only failure mode is a repeat publish, which every
+//! consumer of these topics absorbs.
//! A row the publisher cannot read (an op row that is gone, a `moved` entry
-//! the saga could not have written) stays pending with `last_error` and a
-//! raised `attempts`: the rest of its batch publishes, the row is retried
-//! on every pass and publishes on its own once the state is repaired, and
-//! the lag gauge reports it meanwhile. The publisher never parks a row;
-//! `given_up_at` is an operator's switch to take a row out of the claim.
-//! Kafka failures retry forever with backoff.
+//! the saga could not have written, an outcome that disagrees with the rows)
+//! stays pending with `last_error` and a raised `attempts`: the rest of its
+//! batch publishes, the row is retried on every pass and publishes on its
+//! own once the state is repaired, and the lag gauge reports it meanwhile.
+//! The publisher never parks a row; `given_up_at` is an operator's switch
+//! to take a row out of the claim. Kafka failures retry forever with backoff.
pub mod claim;
pub mod config;
@@ -25,17 +29,24 @@ pub mod messages;
pub mod pointer;
pub mod sink;
+use std::collections::BTreeSet;
use std::time::{Duration, Instant};
+use chrono::{DateTime, Utc};
use common_sqlx_macros::mirrored_query;
use lifecycle::Handle;
use sqlx::PgPool;
+use uuid::Uuid;
use crate::config::IdentityTables;
use crate::lifecycle::engine::Tx;
-use crate::publish::claim::{claim, ClaimedRow};
-use crate::publish::messages::DistinctIdRow;
-use crate::publish::pointer::{load_op, outbox_depth, resolve_chunk, Cursor};
+use crate::lifecycle::merge::{MergeSourceRecord, OUTCOME_MERGED};
+use crate::publish::claim::{claim, ClaimedRow, KIND_MERGE_OP};
+use crate::publish::config::MergeEventsAllowlist;
+use crate::publish::messages::{DistinctIdRow, PersonMergeEvent, MERGE_EVENT_SCHEMA_VERSION};
+use crate::publish::pointer::{
+ load_op, load_outcome_results, merged_sources, outbox_depth, resolve_chunk, Cursor, PointerOp,
+};
use crate::publish::sink::{PublishBatch, PublishError, PublishSink};
const PUBLISH_ROWS_TOTAL: &str = "personhog_lifecycle_publish_rows_total";
@@ -54,12 +65,16 @@ const MAX_BACKOFF: Duration = Duration::from_secs(30);
#[derive(Clone, Debug)]
pub struct DrainConfig {
pub batch_size: i64,
- /// Distinct id rows one pass produces at most. A pointer's chunk is
- /// bounded by what is left of it, so a pass of large ops stays inside
- /// the produce timeout instead of failing the same way forever.
+ /// Messages one pass produces at most, distinct id rows and merge
+ /// events together. A pointer's chunk is bounded by what is left of it,
+ /// so a pass of large ops stays inside the produce timeout instead of
+ /// failing the same way forever. A merge's events ride its final chunk
+ /// whole, so one pointer can overshoot by its source count, which the
+ /// merge request cap bounds.
pub max_rows_per_pass: i64,
pub interval: Duration,
pub lag_alert: Duration,
+ pub merge_events: Option<MergeEventsAllowlist>,
}
#[derive(Debug, thiserror::Error)]
@@ -207,7 +222,7 @@ impl<S: PublishSink> Publisher<S> {
if remaining <= 0 {
break;
}
- let before = batch.distinct_id_rows.len();
+ let before = batch.distinct_id_rows.len() + batch.merge_events.len();
let disposition = if row.is_pointer() {
self.resolve_pointer(&mut tx, row, &mut batch, remaining)
.await
@@ -225,7 +240,7 @@ impl<S: PublishSink> Publisher<S> {
batch.distinct_id_rows.push(mapping_row(row)?);
Disposition::Finished
};
- remaining -= (batch.distinct_id_rows.len() - before) as i64;
+ remaining -= (batch.distinct_id_rows.len() + batch.merge_events.len() - before) as i64;
dispositions.push((row, disposition));
}
let unprocessed = rows.len() - dispositions.len();
@@ -287,13 +302,14 @@ impl<S: PublishSink> Publisher<S> {
advanced: advanced.0.len(),
deferred: deferred.0.len(),
unprocessed,
- messages: batch.distinct_id_rows.len(),
+ messages: batch.distinct_id_rows.len() + batch.merge_events.len(),
})
}
/// Resolve one pointer's next chunk, at most `limit` rows, into
- /// `batch`. Rows are added only once the whole chunk decodes, so a
- /// poisoned pointer contributes nothing to the batch it is deferred in.
+ /// `batch`, plus the merge events on a merge pointer's final chunk.
+ /// Rows and events are added only once the chunk decodes and the events
+ /// resolve, so a deferred pointer contributes nothing to the batch.
async fn resolve_pointer(
&self,
tx: &mut Tx<'_>,
@@ -309,11 +325,11 @@ impl<S: PublishSink> Publisher<S> {
};
// Pointers are written only by a completed op's own commit, so any
// of these is corrupt state rather than a case to handle.
- if op.completed_at.is_none() {
+ let Some(completed_at) = op.completed_at else {
return Ok(Disposition::Deferred(format!(
"op {op_id} is not completed"
)));
- }
+ };
if format!("{}_op", op.op_type) != row.kind {
return Ok(Disposition::Deferred(format!(
"op {op_id} is a {} op but the pointer kind is {}",
@@ -362,16 +378,91 @@ impl<S: PublishSink> Publisher<S> {
is_deleted: u8::from(resolved.is_deleted),
});
}
- batch.distinct_id_rows.extend(rows);
// A chunk shorter than the limit it was asked for is the last one.
// A chunk exactly at the limit may also be the last, which costs
// one more pass that finds nothing; cheaper than probing past the
// limit on every chunk.
- Ok(match chunk.last() {
+ let disposition = match chunk.last() {
Some(last) if chunk.len() as i64 >= limit => Disposition::Advanced(last.cursor()),
_ => Disposition::Finished,
- })
+ };
+
+ let mut merge_events = Vec::new();
+ if matches!(disposition, Disposition::Finished) && row.kind == KIND_MERGE_OP {
+ if let Some(allowlist) = &self.config.merge_events {
+ if allowlist.allows(i64::from(row.team_id)) {
+ match self
+ .merge_events_for(tx, op_id, &op, row.team_id, completed_at)
+ .await?
+ {
+ Ok(events) => merge_events = events,
+ Err(reason) => return Ok(Disposition::Deferred(reason)),
+ }
+ }
+ }
+ }
+
+ batch.distinct_id_rows.extend(rows);
+ batch.merge_events.extend(merge_events);
+ Ok(disposition)
+ }
+
+ /// One `person_merge_events` message per source person the merge
+ /// deleted, with `merged_at_ms` the op's completion time. The source
+ /// rows and the recorded outcome have to name the same persons;
+ /// anything else is corrupt state, reported as the deferral reason.
+ async fn merge_events_for(
+ &self,
+ tx: &mut Tx<'_>,
+ op_id: Uuid,
+ op: &PointerOp,
+ team_id: i32,
+ completed_at: DateTime<Utc>,
+ ) -> Result<Result<Vec<PersonMergeEvent>, String>, sqlx::Error> {
+ let Some(new_person_uuid) = op.target_uuid else {
+ return Ok(Err(format!("merge op {op_id} has no target row")));
+ };
+ let Some(results) = load_outcome_results(tx, &self.tables, op_id).await? else {
+ return Ok(Err(format!(
+ "merge op {op_id} has no recorded outcome results"
+ )));
+ };
+ let results: Vec<MergeSourceRecord> = match serde_json::from_value(results) {
+ Ok(results) => results,
+ Err(e) => {
+ return Ok(Err(format!(
+ "merge op {op_id} has malformed outcome results: {e}"
+ )))
+ }
+ };
+ let mut recorded: BTreeSet<i64> = BTreeSet::new();
+ for result in results.iter().filter(|r| r.outcome == OUTCOME_MERGED) {
+ let Some(person_id) = result.person_id else {
+ return Ok(Err(format!(
+ "merge op {op_id} recorded a merged source without a person id"
+ )));
+ };
+ recorded.insert(person_id);
+ }
+ let sources = merged_sources(tx, &self.tables, op_id).await?;
+ let deleted: BTreeSet<i64> = sources.iter().map(|s| s.person_id).collect();
+ if recorded != deleted {
+ return Ok(Err(format!(
+ "merge op {op_id} recorded merged sources {recorded:?} but its deleted source rows are {deleted:?}"
+ )));
+ }
+ let merged_at_ms = completed_at.timestamp_millis();
+ Ok(Ok(sources
+ .into_iter()
+ .map(|source| PersonMergeEvent {
+ team_id,
+ old_person_uuid: source.person_uuid,
+ new_person_uuid,
+ merged_at_ms,
+ schema_version: MERGE_EVENT_SCHEMA_VERSION,
+ })
+ .collect()))
}
async fn write_back(
diff --git a/rust/personhog-identity/src/publish/pointer.rs b/rust/personhog-identity/src/publish/pointer.rs
index a3332d83e109..e75da47d9007 100644
--- a/rust/personhog-identity/src/publish/pointer.rs
+++ b/rust/personhog-identity/src/publish/pointer.rs
@@ -10,6 +10,7 @@
use chrono::{DateTime, Utc};
use common_sqlx_macros::{mirrored_query_as, mirrored_query_scalar};
+use serde_json::Value;
use uuid::Uuid;
use crate::config::IdentityTables;
@@ -40,6 +41,8 @@ pub struct PointerOp {
/// fan the resolution join out and repeat every source entry under
/// the same cursor key.
pub target_rows: i64,
+ /// The target row's uuid: the `new_person_uuid` of a merge event.
+ pub target_uuid: Option<Uuid>,
/// Source or victim rows whose `moved` is not a JSON array. The
/// resolution query skips them, so a count above zero is the only way
/// to see the corruption instead of silently publishing nothing.
@@ -61,6 +64,9 @@ pub async fn load_op(
SELECT op.op_type, op.completed_at,
(SELECT count(*) FROM {lifecycle_op_person} lop
WHERE lop.op_id = op.op_id AND lop.role = 'target') AS "target_rows!",
+ (SELECT lop.person_uuid FROM {lifecycle_op_person} lop
+ WHERE lop.op_id = op.op_id AND lop.role = 'target'
+ ORDER BY lop.person_id LIMIT 1) AS target_uuid,
(SELECT count(*) FROM {lifecycle_op_person} lop
WHERE lop.op_id = op.op_id
AND lop.role IN ('source', 'victim')
@@ -74,6 +80,25 @@ pub async fn load_op(
)
}
+/// The recorded outcome's `results` array, which names the merged sources
+/// a merge event is owed for. Read apart from [`load_op`] and only on the
+/// chunk that produces the events: the outcome carries the survivor
+/// document, and even a subfield read detoasts the whole datum.
+pub async fn load_outcome_results(
+ tx: &mut Tx<'_>,
+ tables: &IdentityTables,
+ op_id: Uuid,
+) -> Result<Option<Value>, sqlx::Error> {
+ let results: Option<Option<Value>> = mirrored_query_scalar!(
+ tables.is_validation(),
+ op = "publish_load_outcome_results",
+ r#"SELECT outcome -> 'results' AS "results: Value" FROM {lifecycle_op} WHERE op_id = $1"#,
+ op_id
+ => fetch_optional(&mut **tx)
+ )?;
+ Ok(results.flatten())
+}
+
/// One `moved` entry, positioned for the cursor. The payload columns are
/// nullable on purpose: the query extracts them without casting anything
/// that could raise, so a malformed entry reaches Rust as `None` and gives
@@ -157,6 +182,35 @@ pub async fn resolve_chunk(
)
}
+/// A source person a merge op deleted: the `old_person_uuid` of one merge
+/// event. The primary key `(op_id, person_id)` holds one row per source
+/// person however many of its distinct ids the request named, which is how
+/// one event per merged person falls out.
+#[derive(Debug, Clone)]
+pub struct MergedSource {
+ pub person_id: i64,
+ pub person_uuid: Uuid,
+}
+
+pub async fn merged_sources(
+ tx: &mut Tx<'_>,
+ tables: &IdentityTables,
+ op_id: Uuid,
+) -> Result<Vec<MergedSource>, sqlx::Error> {
+ mirrored_query_as!(
+ MergedSource,
+ tables.is_validation(),
+ op = "publish_merged_sources",
+ r#"
+ SELECT person_id, person_uuid FROM {lifecycle_op_person}
+ WHERE op_id = $1 AND role = 'source' AND status = 'deleted'
+ ORDER BY person_id
+ "#,
+ op_id
+ => fetch_all(&mut **tx)
+ )
+}
+
/// Pending and given-up rows, and the age of the oldest pending one, for
/// the gauges. The age is one index probe and is measured on the database
/// clock, so a skewed publisher clock cannot fake or hide lag; it is the
diff --git a/rust/personhog-identity/src/publish/sink.rs b/rust/personhog-identity/src/publish/sink.rs
index 3c4c25502459..2c406ec58132 100644
--- a/rust/personhog-identity/src/publish/sink.rs
+++ b/rust/personhog-identity/src/publish/sink.rs
@@ -6,21 +6,22 @@
use std::time::Duration;
use async_trait::async_trait;
-use common_kafka::kafka_producer::{send_iter_to_kafka, KafkaContext};
+use common_kafka::kafka_producer::{send_iter_to_kafka, send_keyed_iter_to_kafka, KafkaContext};
use rdkafka::producer::FutureProducer;
-use crate::publish::messages::DistinctIdRow;
+use crate::publish::messages::{DistinctIdRow, PersonMergeEvent};
const PUBLISH_MESSAGES_TOTAL: &str = "personhog_lifecycle_publish_messages_total";
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct PublishBatch {
pub distinct_id_rows: Vec<DistinctIdRow>,
+ pub merge_events: Vec<PersonMergeEvent>,
}
impl PublishBatch {
pub fn is_empty(&self) -> bool {
- self.distinct_id_rows.is_empty()
+ self.distinct_id_rows.is_empty() && self.merge_events.is_empty()
}
}
@@ -40,9 +41,14 @@ pub trait PublishSink: Send + Sync {
async fn send(&self, batch: &PublishBatch) -> Result<(), PublishError>;
}
+/// The Kafka sink. Merge events are keyed and the producer places them with
+/// the partitioner [`crate::publish::config::MURMUR2_RANDOM`] pins.
pub struct KafkaSink {
producer: FutureProducer<KafkaContext>,
distinct_id_topic: String,
+ /// `None` while merge events are disabled; a batch that carries one
+ /// anyway is a configuration error the sink refuses rather than drops.
+ merge_events_topic: Option<String>,
produce_timeout: Duration,
}
@@ -50,14 +56,78 @@ impl KafkaSink {
pub fn new(
producer: FutureProducer<KafkaContext>,
distinct_id_topic: String,
+ merge_events_topic: Option<String>,
produce_timeout: Duration,
) -> Self {
Self {
producer,
distinct_id_topic,
+ merge_events_topic,
produce_timeout,
}
}
+
+ /// Both topics are produced at once: the drain commits only after both
+ /// are acked, so neither the order nor a success on one side alone
+ /// means anything.
+ async fn produce(&self, batch: &PublishBatch) -> Result<(), PublishError> {
+ let (rows, events) = tokio::join!(self.produce_rows(batch), self.produce_events(batch));
+ rows.and(events)
+ }
+
+ async fn produce_rows(&self, batch: &PublishBatch) -> Result<(), PublishError> {
+ if batch.distinct_id_rows.is_empty() {
+ return Ok(());
+ }
+ // Null keys, like the Node producer: the consumers order by
+ // `version`, not by partition.
+ let sent = send_iter_to_kafka(
+ &self.producer,
+ &self.distinct_id_topic,
+ &batch.distinct_id_rows,
+ )
+ .await;
+ settle(&self.distinct_id_topic, "distinct id", &sent)
+ }
+
+ async fn produce_events(&self, batch: &PublishBatch) -> Result<(), PublishError> {
+ if batch.merge_events.is_empty() {
+ return Ok(());
+ }
+ let Some(topic) = &self.merge_events_topic else {
+ return Err(PublishError::Kafka(
+ "merge events in a batch but no merge events topic is configured".to_string(),
+ ));
+ };
+ let sent = send_keyed_iter_to_kafka(
+ &self.producer,
+ topic,
+ |event: &&PersonMergeEvent| Some(event.key()),
+ &batch.merge_events,
+ )
+ .await;
+ settle(topic, "merge event", &sent)
+ }
+}
+
+fn settle<E: std::fmt::Display>(
+ topic: &str,
+ what: &str,
+ sent: &[Result<(), E>],
+) -> Result<(), PublishError> {
+ let failed = sent.iter().filter(|r| r.is_err()).count();
+ if let Some(Err(first)) = sent.iter().find(|r| r.is_err()) {
+ return Err(PublishError::Kafka(format!(
+ "{failed} of {} {what} messages failed; first error: {first}",
+ sent.len()
+ )));
+ }
+ common_metrics::inc(
+ PUBLISH_MESSAGES_TOTAL,
+ &[("topic".to_string(), topic.to_string())],
+ sent.len() as u64,
+ );
+ Ok(())
}
#[async_trait]
@@ -66,30 +136,8 @@ impl PublishSink for KafkaSink {
if batch.is_empty() {
return Ok(());
}
- // Null keys, like the Node producer: the consumers order by
- // `version`, not by partition.
- let sent = tokio::time::timeout(
- self.produce_timeout,
- send_iter_to_kafka(
- &self.producer,
- &self.distinct_id_topic,
- &batch.distinct_id_rows,
- ),
- )
- .await
- .map_err(|_| PublishError::Timeout(self.produce_timeout))?;
- let failed = sent.iter().filter(|r| r.is_err()).count();
- if let Some(Err(first)) = sent.iter().find(|r| r.is_err()) {
- return Err(PublishError::Kafka(format!(
- "{failed} of {} messages failed; first error: {first}",
- sent.len()
- )));
- }
- common_metrics::inc(
- PUBLISH_MESSAGES_TOTAL,
- &[("topic".to_string(), self.distinct_id_topic.clone())],
- sent.len() as u64,
- );
- Ok(())
+ tokio::time::timeout(self.produce_timeout, self.produce(batch))
+ .await
+ .map_err(|_| PublishError::Timeout(self.produce_timeout))?
}
}
diff --git a/rust/personhog-identity/tests/common/mod.rs b/rust/personhog-identity/tests/common/mod.rs
index 65d6a062568e..e8aec3faca99 100644
--- a/rust/personhog-identity/tests/common/mod.rs
+++ b/rust/personhog-identity/tests/common/mod.rs
@@ -13,7 +13,8 @@ use uuid::Uuid;
use personhog_identity::config::{IdentityTables, OutboxWrites};
use personhog_identity::pools::IdentityPools;
-use personhog_identity::publish::messages::DistinctIdRow;
+use personhog_identity::publish::config::MergeEventsAllowlist;
+use personhog_identity::publish::messages::{DistinctIdRow, PersonMergeEvent};
use personhog_identity::publish::sink::{PublishBatch, PublishError, PublishSink};
use personhog_identity::publish::{DrainConfig, Publisher};
use personhog_identity::storage::postgres::PostgresIdentityStorage;
@@ -255,6 +256,24 @@ impl TestContext {
/// row budget is the caller's, so a test can make it small enough that
/// its own pointer drains in chunks.
pub fn publisher<S: PublishSink>(&self, sink: S, max_rows_per_pass: i64) -> Publisher<S> {
+ self.build_publisher(sink, max_rows_per_pass, None)
+ }
+
+ pub fn publisher_with_merge_events<S: PublishSink>(
+ &self,
+ sink: S,
+ max_rows_per_pass: i64,
+ allowlist: MergeEventsAllowlist,
+ ) -> Publisher<S> {
+ self.build_publisher(sink, max_rows_per_pass, Some(allowlist))
+ }
+
+ fn build_publisher<S: PublishSink>(
+ &self,
+ sink: S,
+ max_rows_per_pass: i64,
+ merge_events: Option<MergeEventsAllowlist>,
+ ) -> Publisher<S> {
Publisher::new(
self.pool.clone(),
self.tables.clone(),
@@ -264,6 +283,7 @@ impl TestContext {
max_rows_per_pass,
interval: Duration::from_millis(10),
lag_alert: Duration::from_secs(300),
+ merge_events,
},
)
}
@@ -349,6 +369,14 @@ impl RecordingSink {
.filter(|r| r.team_id == team_id)
.collect()
}
+
+ pub fn merge_events_for_team(&self, team_id: i64) -> Vec<PersonMergeEvent> {
+ self.batches()
+ .into_iter()
+ .flat_map(|b| b.merge_events)
+ .filter(|e| i64::from(e.team_id) == team_id)
+ .collect()
+ }
}
#[async_trait::async_trait]
diff --git a/rust/personhog-identity/tests/lifecycle_merge_tests.rs b/rust/personhog-identity/tests/lifecycle_merge_tests.rs
index 100917f451dc..0ec01fa8ada7 100644
--- a/rust/personhog-identity/tests/lifecycle_merge_tests.rs
+++ b/rust/personhog-identity/tests/lifecycle_merge_tests.rs
@@ -34,7 +34,8 @@ use personhog_identity::lifecycle::merge::{
OUTCOME_NOOP_SAME_PERSON, OUTCOME_SKIPPED_ALREADY_IDENTIFIED, OUTCOME_SKIPPED_CONFLICT,
OUTCOME_SKIPPED_MOVE_LIMIT,
};
-use personhog_identity::publish::messages::DistinctIdRow;
+use personhog_identity::publish::config::MergeEventsAllowlist;
+use personhog_identity::publish::messages::{DistinctIdRow, PersonMergeEvent};
use personhog_proto::personhog::types::v1::LifecycleOpType;
struct MergeHarness {
@@ -3968,3 +3969,92 @@ fn nel_only_ids_match_the_javascript_trim_semantics() {
assert!(is_distinct_id_illegal(" \t\n "));
assert!(is_distinct_id_illegal("\u{FEFF}"));
}
+
+// One event per merged person, however many of its distinct ids the request
+// named, none for a source the saga skipped, and none at all for a team
+// outside the allowlist; the pointer is deleted either way.
+#[tokio::test]
+async fn merge_events_are_one_per_merged_person_and_gated_by_the_team_allowlist() {
+ let h = MergeHarness::new_publishing().await;
+ let _drain_lock = h.ctx.hold_drain_lock().await;
+
+ h.ctx.insert_person_with_distinct_id("ev-target").await;
+ h.ctx.insert_person_with_distinct_id("ev-source").await;
+ h.execute(Uuid::now_v7(), &merge_request("ev-target", &["ev-source"]))
+ .await
+ .expect("merge completes");
+ let silent = RecordingSink::default();
+ h.ctx
+ .publisher_with_merge_events(
+ silent.clone(),
+ 100,
+ MergeEventsAllowlist::Teams(HashSet::new()),
+ )
+ .drain_once()
+ .await
+ .expect("publish pass");
+ assert_eq!(silent.rows_for_team(h.ctx.team_id).len(), 1);
+ assert!(silent.merge_events_for_team(h.ctx.team_id).is_empty());
+ assert!(h.ctx.outbox_rows().await.is_empty());
+
+ let target = h.ctx.insert_person_with_distinct_id("ev-target-2").await;
+ let source = h.ctx.insert_person_with_distinct_id("ev-source-2").await;
+ h.add_distinct_id(source, "ev-source-2-alias").await;
+ let held = h.ctx.insert_person_with_distinct_id("ev-held").await;
+ h.foreign_mark(held).await;
+ let op_id = Uuid::now_v7();
+ let outcome = h
+ .execute(
+ op_id,
+ &merge_request(
+ "ev-target-2",
+ &["ev-source-2", "ev-source-2-alias", "ev-held"],
+ ),
+ )
+ .await
+ .expect("second merge completes");
+ assert_eq!(
+ result_map(&outcome),
+ HashMap::from([
+ ("ev-source-2".to_string(), OUTCOME_MERGED.to_string()),
+ ("ev-source-2-alias".to_string(), OUTCOME_MERGED.to_string()),
+ ("ev-held".to_string(), OUTCOME_SKIPPED_CONFLICT.to_string()),
+ ])
+ );
+ let sink = RecordingSink::default();
+ h.ctx
+ .publisher_with_merge_events(sink.clone(), 100, MergeEventsAllowlist::All)
+ .drain_once()
+ .await
+ .expect("publish pass");
+ assert_eq!(sink.rows_for_team(h.ctx.team_id).len(), 2);
+ let source_uuid: Uuid = sqlx::query_scalar("SELECT uuid FROM posthog_person WHERE id = $1")
+ .bind(source)
+ .fetch_one(&h.ctx.pool)
+ .await
+ .unwrap();
+ let target_uuid: Uuid = sqlx::query_scalar("SELECT uuid FROM posthog_person WHERE id = $1")
+ .bind(target)
+ .fetch_one(&h.ctx.pool)
+ .await
+ .unwrap();
+ let completed_at: chrono::DateTime<Utc> =
+ sqlx::query_scalar("SELECT completed_at FROM lifecycle_op WHERE op_id = $1")
+ .bind(op_id)
+ .fetch_one(&h.ctx.pool)
+ .await
+ .unwrap();
+ assert_eq!(
+ sink.merge_events_for_team(h.ctx.team_id),
+ vec![PersonMergeEvent {
+ team_id: h.ctx.team_id as i32,
+ old_person_uuid: source_uuid,
+ new_person_uuid: target_uuid,
+ merged_at_ms: completed_at.timestamp_millis(),
+ schema_version: 1,
+ }]
+ );
+ assert!(h.ctx.outbox_rows().await.is_empty());
+
+ h.ctx.cleanup().await.expect("cleanup");
+}
diff --git a/rust/personhog-identity/tests/publish_tests.rs b/rust/personhog-identity/tests/publish_tests.rs
index e94d8a7dc6b1..724d0efe7cf9 100644
--- a/rust/personhog-identity/tests/publish_tests.rs
+++ b/rust/personhog-identity/tests/publish_tests.rs
@@ -9,12 +9,14 @@ mod common;
use std::collections::HashMap;
use std::sync::atomic::{AtomicI64, Ordering};
+use chrono::{DateTime, Utc};
use common::{FailingSink, RecordingSink, TestContext};
use serde_json::{json, Value};
use uuid::Uuid;
use personhog_identity::publish::claim::claim_sql;
-use personhog_identity::publish::messages::DistinctIdRow;
+use personhog_identity::publish::config::MergeEventsAllowlist;
+use personhog_identity::publish::messages::{DistinctIdRow, PersonMergeEvent};
use personhog_identity::publish::{DrainError, PassReport};
impl TestContext {
@@ -541,3 +543,181 @@ async fn an_analyzed_backlog_is_claimed_through_the_pending_index_without_a_sort
);
assert!(!plan.contains("Sort"), "claim plan:\n{plan}");
}
+
+/// A completed merge op whose one source, `source_uuid`, merged into
+/// `target_uuid` with `moved` repoints, recorded in the outcome the way
+/// the merge saga writes it, plus its pointer. Returns the op id.
+async fn insert_merged_op(
+ ctx: &TestContext,
+ target_uuid: Uuid,
+ source_uuid: Uuid,
+ moved: Value,
+) -> Uuid {
+ let source_person_id = next_person_id();
+ let op_id = Uuid::now_v7();
+ let outcome = json!({
+ "aborted": false,
+ "survivor": null,
+ "results": [{"distinct_id": "merged-did", "outcome": "merged", "person_id": source_person_id}],
+ });
+ sqlx::query(
+ r#"
+ INSERT INTO lifecycle_op (op_id, op_type, team_id, step, request, outcome, completed_at)
+ VALUES ($1, 'merge', $2, 'completed', '{}'::jsonb, $3, now())
+ "#,
+ )
+ .bind(op_id)
+ .bind(ctx.team_id as i32)
+ .bind(outcome)
+ .execute(&ctx.pool)
+ .await
+ .expect("insert merged op");
+ ctx.insert_op_person(
+ op_id,
+ next_person_id(),
+ target_uuid,
+ "target",
+ Some(json!({"dispositions": []})),
+ )
+ .await;
+ ctx.insert_op_person(op_id, source_person_id, source_uuid, "source", Some(moved))
+ .await;
+ ctx.insert_pointer(op_id, "merge_op").await;
+ op_id
+}
+
+// The event has to go out with exactly one chunk, and the final chunk is
+// the one the drain can tell apart without extra state, because it deletes
+// the pointer in the same pass; per chunk would repeat the event on every
+// pass. Twelve rows give a short final chunk; ten end exactly at the limit,
+// so the final chunk is empty and the event rides a pass that resolves no
+// row.
+#[tokio::test]
+async fn merge_events_go_out_once_with_the_final_chunk() {
+ let ctx = TestContext::new().await;
+ let _drain_lock = ctx.hold_drain_lock().await;
+ for total in [12_i64, 10] {
+ let (target, source) = (Uuid::now_v7(), Uuid::now_v7());
+ let entries: Vec<(String, i64)> = (1..=total).map(|i| (format!("m-{i}"), i)).collect();
+ let op_id = insert_merged_op(&ctx, target, source, moved(&as_refs(&entries))).await;
+ let completed_at: DateTime<Utc> =
+ sqlx::query_scalar("SELECT completed_at FROM lifecycle_op WHERE op_id = $1")
+ .bind(op_id)
+ .fetch_one(&ctx.pool)
+ .await
+ .expect("op row");
+
+ let sink = RecordingSink::default();
+ let publisher = ctx.publisher_with_merge_events(sink.clone(), 5, MergeEventsAllowlist::All);
+ publisher.drain_once().await.expect("first chunk");
+ publisher.drain_once().await.expect("second chunk");
+ assert_eq!(sink.rows_for_team(ctx.team_id).len(), 10, "{total} rows");
+ assert!(
+ sink.merge_events_for_team(ctx.team_id).is_empty(),
+ "{total} rows: no event before the final chunk"
+ );
+
+ publisher.drain_once().await.expect("final chunk");
+ assert_eq!(sink.rows_for_team(ctx.team_id).len() as i64, total);
+ assert_eq!(
+ sink.merge_events_for_team(ctx.team_id),
+ vec![PersonMergeEvent {
+ team_id: ctx.team_id as i32,
+ old_person_uuid: source,
+ new_person_uuid: target,
+ merged_at_ms: completed_at.timestamp_millis(),
+ schema_version: 1,
+ }],
+ "{total} rows"
+ );
+ assert!(ctx.outbox_rows().await.is_empty(), "{total} rows");
+ }
+
+ ctx.cleanup().await.expect("cleanup");
+}
+
+// The outcome and the per-person rows are two records of the same merge;
+// an event built from one while the other disagrees would name a person
+// that was not merged, so the pointer stays pending instead, rows and all,
+// and publishes on its own once the records agree again.
+#[tokio::test]
+async fn a_merge_op_whose_outcome_and_rows_disagree_is_deferred_until_repaired() {
+ let ctx = TestContext::new().await;
+ let _drain_lock = ctx.hold_drain_lock().await;
+ let (target, source) = (Uuid::now_v7(), Uuid::now_v7());
+ let op_id = insert_merged_op(&ctx, target, source, moved(&[("d-1", 1)])).await;
+ let pool = &ctx.pool;
+ let set_source_status = |status: &'static str| async move {
+ sqlx::query(
+ "UPDATE lifecycle_op_person SET status = $1 WHERE op_id = $2 AND role = 'source'",
+ )
+ .bind(status)
+ .bind(op_id)
+ .execute(pool)
+ .await
+ .expect("set the source status");
+ };
+ set_source_status("sealed").await;
+
+ let sink = RecordingSink::default();
+ let publisher = ctx.publisher_with_merge_events(sink.clone(), 100, MergeEventsAllowlist::All);
+ publisher.drain_once().await.expect("the pass commits");
+ assert!(
+ sink.rows_for_team(ctx.team_id).is_empty(),
+ "a deferred pointer publishes none of its rows"
+ );
+ assert!(sink.merge_events_for_team(ctx.team_id).is_empty());
+ let rows = ctx.outbox_rows().await;
+ assert_eq!(rows.len(), 1);
+ assert!(!rows[0].given_up);
+ assert_eq!(rows[0].attempts, 1);
+ assert!(
+ rows[0]
+ .last_error
+ .as_deref()
+ .unwrap_or("")
+ .contains("recorded merged sources"),
+ "{:?}",
+ rows[0].last_error
+ );
+
+ set_source_status("deleted").await;
+ publisher.drain_once().await.expect("the pass commits");
+ assert_eq!(
+ sink.rows_for_team(ctx.team_id),
+ vec![ctx.row(target, "d-1", 1, 0)]
+ );
+ let events = sink.merge_events_for_team(ctx.team_id);
+ assert_eq!(events.len(), 1, "{events:?}");
+ assert_eq!(
+ (events[0].old_person_uuid, events[0].new_person_uuid),
+ (source, target)
+ );
+ assert!(ctx.outbox_rows().await.is_empty());
+
+ ctx.cleanup().await.expect("cleanup");
+}
+
+// A merge's events ride its final chunk, so a pass full of merge pointers
+// could enqueue events past the row budget unless they count against it.
+#[tokio::test]
+async fn merge_events_count_against_the_pass_budget() {
+ let ctx = TestContext::new().await;
+ let _drain_lock = ctx.hold_drain_lock().await;
+ let (target, source_a, source_b) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());
+ insert_merged_op(&ctx, target, source_a, moved(&[("a-1", 1)])).await;
+ insert_merged_op(&ctx, target, source_b, moved(&[("b-1", 1)])).await;
+
+ let sink = RecordingSink::default();
+ let publisher = ctx.publisher_with_merge_events(sink.clone(), 1, MergeEventsAllowlist::All);
+ let first = publisher.drain_once().await.expect("first pass");
+ assert_eq!((first.advanced, first.unprocessed), (1, 1));
+ let second = publisher.drain_once().await.expect("second pass");
+ assert_eq!(
+ (second.finished, second.messages, second.unprocessed),
+ (1, 1, 1)
+ );
+ assert_eq!(sink.merge_events_for_team(ctx.team_id).len(), 1);
+
+ ctx.cleanup().await.expect("cleanup");
+}