:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(personhog): publish merge ingestion warnings from the identity service (#118122)
Nick Best2b531d2ffc8c
diff --git a/.agents/skills/adding-ingestion-warnings/SKILL.md b/.agents/skills/adding-ingestion-warnings/SKILL.mdindex ed0af4e0884d..39051cb5629e 100644--- a/.agents/skills/adding-ingestion-warnings/SKILL.md+++ b/.agents/skills/adding-ingestion-warnings/SKILL.md@@ -93,6 +93,8 @@ Warning::new(WarningType::MyNewType)`into_row` takes a `WarningSource` (declare one const per emit site, as capture does in `src/lib.rs`) and injects `teamId` and the registry's `category`/`severity` over the caller's details (they cannot be spoofed or forgotten), and stamps the ClickHouse-format timestamp. A direct-row type needs **no** `captureProduced` flag and no `from_tag` arm — register it, regenerate the artifact, and emit. See the module doc in `rust/common/ingestion_warnings/src/serializer.rs` for the envelope-vs-row correspondence table and the trust rationale (the envelope lane is attacker-writable, so the consumer stamps classification; the row topic is ACL-guarded, so the producer does).+The crate's `RowWarningEmitter` (`src/row.rs`) is the producer for this transport: `KafkaRowWarningEmitter` wraps a dedicated fire-and-forget `ThreadedProducer`, throttles per `(team_id, scope, type)` where `scope` is the caller's debounce entity (a distinct id, say), keys rows by team, and reports through the same `ingestion_warnings_total` outcomes as the envelope emitter. `test_support::CollectingRowEmitter` records rows for assertions. The emitter's throttle keeps the crate's default tracked-key cap unless the caller raises it, and a per-entity scope needs a cap sized for that cardinality (see `MAX_TRACKED_SCOPES` in the identity service). personhog-identity is the reference caller (`rust/personhog-identity/src/warnings.rs`: a `WarningSource` per emit site, a pure verdict-to-warning mapping, and `install` building the producer from env with the emitter-enabled gauge); the leader still carries its own older `WarningsProducer`.+Emitting from Rust:- **Emit it** via `WarningEmitter::emit(token, source, warning, details, count)` — the builder injects `count` and `pipelineStep` into details and stamps `type`/`source`/`details` into the event properties the consumer reads. Use the same camelCase details keys as nodejs (`distinctId`, `eventUuid`, ...). The envelope's top-level `distinct_id` is always the token (never the offending id), so an oversized offending distinct_id can't make the consumer drop the warning.diff --git a/rust/Cargo.lock b/rust/Cargo.lockindex 71f0f0f6a597..37689993e62b 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -8943,6 +8943,7 @@ dependencies = ["chrono","common-alloc","common-database",+ "common-ingestion-warnings","common-kafka","common-metrics","common-sqlx-macros",@@ -8951,11 +8952,13 @@ dependencies = ["lifecycle","metrics","metrics-exporter-prometheus",+ "metrics-util","personhog-common","personhog-coordination","personhog-proto","rand 0.8.5","rdkafka",+ "rstest","serde","serde_json","sqlx",diff --git a/rust/common/ingestion_warnings/src/lib.rs b/rust/common/ingestion_warnings/src/lib.rsindex b10a90350098..82247a4e4687 100644--- a/rust/common/ingestion_warnings/src/lib.rs+++ b/rust/common/ingestion_warnings/src/lib.rs@@ -4,7 +4,7 @@//! Node.js source of truth) and one builder ([`serializer::Warning`])://! services that only know API tokens (capture) commit via//! [`serializer::Warning::into_event_envelope`], and services that know `team_id`-//! (personhog leader/writer) commit the terminal row via+//! (personhog leader/identity) commit the terminal row via//! [`serializer::Warning::into_row`]. See `serializer.rs` for the//! field-by-field correspondence and the trust rationale.//!@@ -38,6 +38,7 @@pub mod registry;pub mod request;+pub mod row;pub mod serializer;pub mod test_support;pub mod throttle;@@ -56,6 +57,7 @@ use tracing::warn;pub use registry::WarningType;pub use request::{emit_request_warning, WarningRequestContext, UNKNOWN_ATTRIBUTION};+pub use row::{KafkaRowWarningEmitter, RowWarningEmitter};pub use throttle::{ThrottleDecision, WarningThrottle};/// Counter of emission attempts: labels `type` (warning type), `source`diff --git a/rust/common/ingestion_warnings/src/row.rs b/rust/common/ingestion_warnings/src/row.rsnew file mode 100644index 000000000000..5a5ba6d4a0fb--- /dev/null+++ b/rust/common/ingestion_warnings/src/row.rs@@ -0,0 +1,284 @@+//! Direct-row transport for services that know the `team_id`; same+//! fire-and-forget contract as [`crate::WarningEmitter`]. The throttle key+//! is `team_id` plus a caller-chosen scope, so one offending entity+//! re-presenting the same condition warns once per period while a+//! different entity warns at once. Scopes are far more numerous than+//! capture's tokens, so a caller sizes the throttle's tracked-key cap for+//! its own cardinality instead of taking the default.++use std::hash::{DefaultHasher, Hash, Hasher};+use std::time::Duration;++use common_kafka::kafka_producer::ThreadedKafkaContext;+use metrics::{counter, gauge};+use rdkafka::error::KafkaError;+use rdkafka::producer::{BaseRecord, Producer, ThreadedProducer};+use rdkafka::types::RDKafkaErrorCode;+use tracing::warn;++use crate::registry::WarningType;+use crate::serializer::Warning;+use crate::throttle::WarningThrottle;+use crate::{+ WarningDelivery, WarningSource, INGESTION_WARNINGS_THROTTLE_KEYS, INGESTION_WARNINGS_TOTAL,+};++pub trait RowWarningEmitter: Send + Sync {+ fn emit(&self, team_id: i64, scope: &str, source: WarningSource, warning: Warning);++ fn flush(&self, timeout: Duration);+}++pub struct KafkaRowWarningEmitter {+ producer: ThreadedProducer<ThreadedKafkaContext<WarningDelivery>>,+ topic: String,+ throttle: WarningThrottle,+}++impl KafkaRowWarningEmitter {+ pub fn new(+ producer: ThreadedProducer<ThreadedKafkaContext<WarningDelivery>>,+ topic: impl Into<String>,+ ) -> Self {+ Self::with_throttle(producer, topic, WarningThrottle::default())+ }++ pub fn with_throttle(+ producer: ThreadedProducer<ThreadedKafkaContext<WarningDelivery>>,+ topic: impl Into<String>,+ throttle: WarningThrottle,+ ) -> Self {+ Self {+ producer,+ topic: topic.into(),+ throttle,+ }+ }++ pub fn sweep_throttle(&self) {+ self.throttle.sweep();+ gauge!(INGESTION_WARNINGS_THROTTLE_KEYS).set(self.throttle.tracked_keys() as f64);+ }+}++/// The scope is caller data of unbounded length (a distinct id, say), and+/// the throttle retains every key for the period, so the key carries a+/// fixed-width digest of it instead.+pub fn throttle_key(team_id: i64, scope: &str) -> String {+ let mut hasher = DefaultHasher::new();+ scope.hash(&mut hasher);+ format!("{team_id}:{:016x}", hasher.finish())+}++fn count(warning: WarningType, source: WarningSource, outcome: &'static str) {+ counter!(+ INGESTION_WARNINGS_TOTAL,+ "type" => warning.as_str(),+ "source" => source.service,+ "path" => source.path,+ "outcome" => outcome,+ )+ .increment(1);+}++impl RowWarningEmitter for KafkaRowWarningEmitter {+ fn emit(&self, team_id: i64, scope: &str, source: WarningSource, warning: Warning) {+ let warning_type = warning.warning_type();+ if let Some(outcome) = self+ .throttle+ .check(&throttle_key(team_id, scope), warning_type)+ .drop_outcome()+ {+ count(warning_type, source, outcome);+ return;+ }++ let payload = match serde_json::to_vec(&warning.into_row(team_id, source)) {+ Ok(payload) => payload,+ Err(err) => {+ count(warning_type, source, "serialize_error");+ warn!(warning_type = warning_type.as_str(), source = source.service, error = %err,+ "failed to serialize ingestion warning row");+ return;+ }+ };++ let key = team_id.to_string();+ let record = BaseRecord::with_opaque_to(+ &self.topic,+ Box::new(WarningDelivery {+ warning: warning_type,+ source,+ }),+ )+ .key(&key)+ .payload(&payload);++ match self.producer.send(record) {+ Ok(()) => count(warning_type, source, "emitted"),+ Err((KafkaError::MessageProduction(RDKafkaErrorCode::QueueFull), _record)) => {+ count(warning_type, source, "queue_full");+ }+ Err((err, _record)) => {+ count(warning_type, source, "enqueue_error");+ warn!(warning_type = warning_type.as_str(), source = source.service, error = %err,+ "failed to enqueue ingestion warning row");+ }+ }+ }++ fn flush(&self, timeout: Duration) {+ drop(self.producer.flush(timeout));+ }+}++#[cfg(test)]+mod tests {+ use std::num::NonZeroU32;+ use std::time::Instant;++ use common_kafka::config::KafkaConfig;+ use common_kafka::kafka_producer::create_threaded_kafka_producer_no_ping;+ use common_liveness::SyncLivenessReporter;+ use metrics_util::debugging::{DebugValue, DebuggingRecorder, Snapshotter};++ use super::*;+ use crate::observe_delivery;+ use crate::throttle::DEFAULT_THROTTLE_PERIOD;++ #[derive(Clone, Copy)]+ struct AlwaysHealthy;++ impl SyncLivenessReporter for AlwaysHealthy {+ fn report_healthy(&self) {}+ fn report_unhealthy(&self) {}+ }++ const SOURCE: WarningSource = WarningSource {+ service: "personhog-test",+ path: "row_test",+ pipeline_step: "personhog_test_step",+ };++ fn unreachable_producer(+ queue_messages: u32,+ ) -> ThreadedProducer<ThreadedKafkaContext<WarningDelivery>> {+ let config = KafkaConfig {+ kafka_hosts: "192.0.2.1:9092".to_string(),+ kafka_message_timeout_ms: 500,+ kafka_producer_linger_ms: 5,+ kafka_producer_queue_messages: queue_messages,+ kafka_producer_retries: Some(0),+ ..Default::default()+ };+ create_threaded_kafka_producer_no_ping(&config, AlwaysHealthy, observe_delivery)+ .expect("client config is valid, so creation cannot fail without a broker round-trip")+ }++ fn outcomes(snapshotter: &Snapshotter) -> Vec<(String, u64)> {+ let mut totals: std::collections::BTreeMap<String, u64> = Default::default();+ for (ckey, _, _, value) in snapshotter.snapshot().into_vec() {+ if ckey.key().name() != INGESTION_WARNINGS_TOTAL {+ continue;+ }+ let outcome = ckey+ .key()+ .labels()+ .find(|l| l.key() == "outcome")+ .map(|l| l.value().to_string())+ .expect("outcome label");+ let n = match value {+ DebugValue::Counter(n) => n,+ other => panic!("expected a counter, got {other:?}"),+ };+ *totals.entry(outcome).or_default() += n;+ }+ totals.into_iter().collect()+ }++ fn warning() -> Warning {+ Warning::new(WarningType::CannotMergeAlreadyIdentified).with_detail("distinctId", "u1")+ }++ #[test]+ fn emit_is_fire_and_forget_and_throttles_per_team_scope_and_type() {+ let emitter = KafkaRowWarningEmitter::new(unreachable_producer(100), "warnings");+ let recorder = DebuggingRecorder::new();+ let snapshotter = recorder.snapshotter();++ let start = Instant::now();+ metrics::with_local_recorder(&recorder, || {+ emitter.emit(7, "did-a", SOURCE, warning());+ emitter.emit(7, "did-a", SOURCE, warning());+ emitter.emit(7, "did-b", SOURCE, warning());+ emitter.emit(8, "did-a", SOURCE, warning());+ emitter.emit(+ 7,+ "did-a",+ SOURCE,+ Warning::new(WarningType::MergeSettledFailure),+ );+ });+ assert!(+ start.elapsed() < Duration::from_millis(500),+ "emit must never wait on the broker"+ );++ assert_eq!(+ outcomes(&snapshotter),+ vec![("emitted".to_string(), 4), ("throttled".to_string(), 1)],+ "only the repeat of the same team, scope and type is throttled"+ );+ }++ #[test]+ fn a_type_budget_caps_the_pod_across_teams() {+ let throttle =+ WarningThrottle::default().with_type_budget(DEFAULT_THROTTLE_PERIOD, NonZeroU32::MIN);+ let emitter =+ KafkaRowWarningEmitter::with_throttle(unreachable_producer(100), "warnings", throttle);+ let recorder = DebuggingRecorder::new();+ let snapshotter = recorder.snapshotter();++ metrics::with_local_recorder(&recorder, || {+ for team in [1, 2, 3] {+ emitter.emit(team, "did", SOURCE, warning());+ }+ });++ assert_eq!(+ outcomes(&snapshotter),+ vec![+ ("emitted".to_string(), 1),+ ("type_budget_exhausted".to_string(), 2)+ ]+ );+ }++ #[test]+ fn a_full_local_queue_drops_the_row_and_counts_it() {+ let emitter = KafkaRowWarningEmitter::new(unreachable_producer(1), "warnings");+ let recorder = DebuggingRecorder::new();+ let snapshotter = recorder.snapshotter();++ metrics::with_local_recorder(&recorder, || {+ emitter.emit(1, "a", SOURCE, warning());+ emitter.emit(2, "a", SOURCE, warning());+ });++ assert_eq!(+ outcomes(&snapshotter),+ vec![("emitted".to_string(), 1), ("queue_full".to_string(), 1)]+ );+ }++ #[test]+ fn the_throttle_key_is_fixed_width_whatever_the_scope_length() {+ let huge = "x".repeat(1 << 20);+ let key = throttle_key(7, &huge);+ assert_eq!(key.len(), throttle_key(7, "did").len());+ assert_ne!(key, throttle_key(7, &format!("{huge}y")));+ assert_ne!(key, throttle_key(8, &huge));+ assert_eq!(key, throttle_key(7, &huge));+ }+}diff --git a/rust/common/ingestion_warnings/src/serializer.rs b/rust/common/ingestion_warnings/src/serializer.rsindex 8d6ea9fc50bf..da406cbc7d9c 100644--- a/rust/common/ingestion_warnings/src/serializer.rs+++ b/rust/common/ingestion_warnings/src/serializer.rs@@ -77,6 +77,10 @@ impl Warning {}}+ pub fn warning_type(&self) -> WarningType {+ self.warning+ }+pub fn with_detail(mut self, key: impl Into<String>, value: impl Into<Value>) -> Self {self.details.insert(key.into(), value.into());selfdiff --git a/rust/common/ingestion_warnings/src/test_support.rs b/rust/common/ingestion_warnings/src/test_support.rsindex dceeceed03f3..8c7b552b3585 100644--- a/rust/common/ingestion_warnings/src/test_support.rs+++ b/rust/common/ingestion_warnings/src/test_support.rs@@ -1,5 +1,6 @@-//! Test double for [`crate::WarningEmitter`], available to downstream crates'-//! dev-tests (which is why this module is not `#[cfg(test)]`-gated).+//! Test doubles for [`crate::WarningEmitter`] and+//! [`crate::RowWarningEmitter`], available to downstream crates' dev-tests+//! (which is why this module is not `#[cfg(test)]`-gated).use std::sync::Mutex;use std::time::Duration;@@ -7,7 +8,8 @@ use std::time::Duration;use serde_json::{Map, Value};use crate::registry::WarningType;-use crate::{WarningEmitter, WarningSource};+use crate::serializer::Warning;+use crate::{RowWarningEmitter, WarningEmitter, WarningSource};/// One captured [`WarningEmitter::emit`] call.#[derive(Debug, Clone, PartialEq)]@@ -58,3 +60,66 @@ impl WarningEmitter for CollectingEmitter {fn flush(&self, _timeout: Duration) {}}++#[derive(Debug, Clone, PartialEq)]+pub struct EmittedRow {+ pub team_id: i64,+ pub scope: String,+ pub source: WarningSource,+ pub warning: WarningType,+ pub row: Value,+}++impl EmittedRow {+ pub fn details(&self) -> Value {+ serde_json::from_str(+ self.row["details"]+ .as_str()+ .expect("details is a JSON string"),+ )+ .expect("details parses")+ }+}++#[derive(Default)]+pub struct CollectingRowEmitter {+ rows: Mutex<Vec<EmittedRow>>,+}++impl CollectingRowEmitter {+ pub fn new() -> Self {+ Self::default()+ }++ pub fn rows(&self) -> Vec<EmittedRow> {+ self.rows+ .lock()+ .expect("row emitter mutex poisoned")+ .clone()+ }++ pub fn clear(&self) {+ self.rows+ .lock()+ .expect("row emitter mutex poisoned")+ .clear();+ }+}++impl RowWarningEmitter for CollectingRowEmitter {+ fn emit(&self, team_id: i64, scope: &str, source: WarningSource, warning: Warning) {+ let warning_type = warning.warning_type();+ self.rows+ .lock()+ .expect("row emitter mutex poisoned")+ .push(EmittedRow {+ team_id,+ scope: scope.to_string(),+ source,+ warning: warning_type,+ row: warning.into_row(team_id, source),+ });+ }++ fn flush(&self, _timeout: Duration) {}+}diff --git a/rust/common/ingestion_warnings/src/throttle.rs b/rust/common/ingestion_warnings/src/throttle.rsindex 988668afd00e..0f6c5b039fb8 100644--- a/rust/common/ingestion_warnings/src/throttle.rs+++ b/rust/common/ingestion_warnings/src/throttle.rs@@ -10,8 +10,10 @@//! caps how many warnings of one type a pod sends, whatever the number of//! tokens.+use std::collections::HashMap;use std::num::NonZeroU32;-use std::time::Duration;+use std::sync::{Mutex, PoisonError};+use std::time::{Duration, Instant};use governor::{clock, state::keyed::DefaultKeyedStateStore, Quota, RateLimiter};@@ -27,11 +29,64 @@ pub const DEFAULT_THROTTLE_PERIOD: Duration = Duration::from_secs(3600);pub const DEFAULT_MAX_TRACKED_KEYS: usize = 100_000;type Key = (String, crate::registry::WarningType);-type TypeBudget = RateLimiter<- crate::registry::WarningType,- DefaultKeyedStateStore<crate::registry::WarningType>,- clock::DefaultClock,->;++/// Per-type token bucket: `burst` permits, one refilled per `period`. Not a+/// governor limiter because [`WarningThrottle::check`] must know whether a+/// permit is available before it tracks a new key, and governor can only+/// take one.+struct TypeBudget {+ period: Duration,+ burst: f64,+ buckets: Mutex<HashMap<crate::registry::WarningType, Bucket>>,+}++struct Bucket {+ permits: f64,+ refilled_at: Instant,+}++impl TypeBudget {+ fn new(period: Duration, burst: NonZeroU32) -> Self {+ assert!(!period.is_zero(), "type budget period must be non-zero");+ Self {+ period,+ burst: f64::from(burst.get()),+ buckets: Mutex::new(HashMap::new()),+ }+ }++ fn give_back(&self, warning: crate::registry::WarningType, now: Instant) {+ self.with_permits(warning, now, |permits| *permits += 1.0);+ }++ fn take_permit(&self, warning: crate::registry::WarningType, now: Instant) -> bool {+ self.with_permits(warning, now, |permits| {+ if *permits < 1.0 {+ return false;+ }+ *permits -= 1.0;+ true+ })+ }++ fn with_permits<T>(+ &self,+ warning: crate::registry::WarningType,+ now: Instant,+ f: impl FnOnce(&mut f64) -> T,+ ) -> T {+ let mut buckets = self.buckets.lock().unwrap_or_else(PoisonError::into_inner);+ let bucket = buckets.entry(warning).or_insert(Bucket {+ permits: self.burst,+ refilled_at: now,+ });+ let refilled =+ now.duration_since(bucket.refilled_at).as_secs_f64() / self.period.as_secs_f64();+ bucket.permits = (bucket.permits + refilled).min(self.burst);+ bucket.refilled_at = now;+ f(&mut bucket.permits)+ }+}/// Outcome of a throttle check; names align with the emission metric's/// `outcome` label values.@@ -93,39 +148,53 @@ impl WarningThrottle {/// at `burst`, refilling one permit per `period`. This bounds what one/// failure that hits many tokens at once can send. Off by default.pub fn with_type_budget(mut self, period: Duration, burst: NonZeroU32) -> Self {- let quota = Quota::with_period(period)- .expect("type budget period must be non-zero")- .allow_burst(burst);- self.type_budget = Some(RateLimiter::dashmap(quota));+ self.type_budget = Some(TypeBudget::new(period, burst));self}- /// Consume a permit for this `(token, type)` if the key map has room and- /// the key has budget, then a permit of the type budget if one is set.- /// Anything but [`ThrottleDecision::Emit`] means the caller should drop the- /// warning.+ /// Consume a type budget permit if one is set, then the `(token, type)`+ /// key's own permit if the key map has room. Anything but+ /// [`ThrottleDecision::Emit`] means the caller should drop the warning.pub fn check(&self, token: &str, warning: crate::registry::WarningType) -> ThrottleDecision {+ self.check_at(token, warning, Instant::now())+ }++ /// [`Self::check`] as of `now`, so a test can advance the type budget+ /// without sleeping. The per-key limiter keeps its own clock.+ pub fn check_at(+ &self,+ token: &str,+ warning: crate::registry::WarningType,+ now: Instant,+ ) -> ThrottleDecision {// Governor's keyed limiter inserts on lookup, so the cap must gate// every check — including keys already tracked — to stay O(1).if self.limiter.len() >= self.max_tracked_keys {return ThrottleDecision::CardinalityCapped;}+ // The budget permit is held before the per-key check, so a token the+ // budget refuses neither takes a slot in the map nor spends its own+ // hourly permit, and two racing checks cannot both pass on one+ // permit. A repeat gives the permit back, so a token that repeats a+ // warning cannot use up the budget of every other token.+ if self+ .type_budget+ .as_ref()+ .is_some_and(|budget| !budget.take_permit(warning, now))+ {+ return ThrottleDecision::TypeBudgetExhausted;+ }if self.limiter.check_key(&(token.to_string(), warning)).is_err(){- return ThrottleDecision::Throttled;- }- // The type budget comes second, so a token that repeats a warning- // spends at most one budget permit per period and cannot use up the- // budget of every other token.- match &self.type_budget {- Some(budget) if budget.check_key(&warning).is_err() => {- ThrottleDecision::TypeBudgetExhausted+ if let Some(budget) = &self.type_budget {+ budget.give_back(warning, now);}- _ => ThrottleDecision::Emit,+ return ThrottleDecision::Throttled;}+ ThrottleDecision::Emit}/// Drop per-key state that has fully refilled, bounding memory. Call@@ -268,12 +337,67 @@ mod tests {ThrottleDecision::Throttled,ThrottleDecision::Emit,ThrottleDecision::TypeBudgetExhausted,- // The refused check still spent tok_c's per-token permit.- ThrottleDecision::Throttled,+ ThrottleDecision::TypeBudgetExhausted,// Each type has its own budget.ThrottleDecision::Emit,]);+ assert_eq!(+ throttle.tracked_keys(),+ 3,+ "the refused tok_c checks must not take key-map slots"+ );+ }++ // Racing checks on the last permit: before the permit was taken first,+ // every racer passed the peek, spent its hourly key slot, and the losers+ // then stayed silent for the hour.+ #[test]+ fn a_budget_loser_keeps_its_hourly_permit() {+ let throttle =+ WarningThrottle::default().with_type_budget(DEFAULT_THROTTLE_PERIOD, NonZeroU32::MIN);+ let racers = 16;+ let barrier = std::sync::Barrier::new(racers);+ let decisions: Vec<(String, ThrottleDecision)> = std::thread::scope(|scope| {+ let handles: Vec<_> = (0..racers)+ .map(|n| {+ let token = format!("tok_{n}");+ let barrier = &barrier;+ let throttle = &throttle;+ scope.spawn(move || {+ barrier.wait();+ let decision = throttle.check(&token, WarningType::InvalidOptions);+ (token, decision)+ })+ })+ .collect();+ handles.into_iter().map(|h| h.join().unwrap()).collect()+ });+ let emitted = decisions+ .iter()+ .filter(|(_, d)| *d == ThrottleDecision::Emit)+ .count();+ assert_eq!(emitted, 1, "{decisions:?}");+ assert!(decisions.iter().all(|(_, d)| matches!(+ d,+ ThrottleDecision::Emit | ThrottleDecision::TypeBudgetExhausted+ )));+ assert_eq!(+ throttle.tracked_keys(),+ 1,+ "only the emitted key holds a slot"+ );++ let (loser, _) = decisions+ .iter()+ .find(|(_, d)| *d == ThrottleDecision::TypeBudgetExhausted)+ .unwrap();+ let refilled = Instant::now() + DEFAULT_THROTTLE_PERIOD;+ assert_eq!(+ throttle.check_at(loser, WarningType::InvalidOptions, refilled),+ ThrottleDecision::Emit,+ "a loser is not throttled once the budget refills"+ );}#[test]@@ -288,9 +412,9 @@ mod tests {throttle.check("tok_b", WarningType::InvalidOptions),ThrottleDecision::TypeBudgetExhausted);- std::thread::sleep(Duration::from_millis(80));+ let later = Instant::now() + Duration::from_millis(80);assert_eq!(- throttle.check("tok_c", WarningType::InvalidOptions),+ throttle.check_at("tok_c", WarningType::InvalidOptions, later),ThrottleDecision::Emit);}diff --git a/rust/personhog-identity/Cargo.toml b/rust/personhog-identity/Cargo.tomlindex bd6b600f2bc6..97e456fb9790 100644--- a/rust/personhog-identity/Cargo.toml+++ b/rust/personhog-identity/Cargo.toml@@ -10,6 +10,7 @@ personhog-coordination = { path = "../personhog-coordination" }personhog-proto = { path = "../personhog-proto" }assignment-coordination = { path = "../common/assignment-coordination" }common-database = { path = "../common/database" }+common-ingestion-warnings = { path = "../common/ingestion_warnings" }common-alloc = { path = "../common/alloc" }common-kafka = { path = "../common/kafka" }common-metrics = { path = "../common/metrics" }@@ -37,6 +38,8 @@ tracing-subscriber = { workspace = true }uuid = { workspace = true }[dev-dependencies]+metrics-util = { workspace = true }+rstest = "0.26"tokio = { workspace = true, features = ["test-util"] }# Drains the publish outbox identity writes; a second binary of this cratediff --git a/rust/personhog-identity/README.md b/rust/personhog-identity/README.mdindex 4a154dad50bc..66aa0a5054e6 100644--- a/rust/personhog-identity/README.md+++ b/rust/personhog-identity/README.md@@ -49,6 +49,27 @@ See `rust/pgcollector/docs/query-tags.md` for the key vocabulary.A lifecycle op parks when the leader answers a semantic refusal after the point of no return: retrying a definitive refusal cannot succeed, so the op holds its fences and only an explicit retry under the same op id resumes it (the sweeper is barred). Refusals before the point of no return abort instead, recording `skipped_refused` for their sources and releasing fences in the same settlement. The sweeper re-drives interrupted sagas to a terminal state and defaults on; a fleet that disables it converts every orphaned saga into fences an operator must clear. The surface is the `personhog_lifecycle_ops_parked` gauge and the park's ERROR log carrying the op id and reason; resolution is a retry with the recorded op id.+## Ingestion warnings++The service publishes in-product ingestion warnings for the merge verdicts it settles, straight to the warnings topic as finished v2 rows (`source = "personhog-identity"`), through the shared `common-ingestion-warnings` crate's direct-row transport (`src/warnings.rs`).+A verdict warns here when it is final under retry and decided by this service alone; the ingestion consumer keeps the warnings that depend on its own retries or merge-mode policy.++| Verdict | Warning | Emitted from |+| --- | --- | --- |+| source illegal, oversized, or NUL-bearing (`skipped_illegal`) | `cannot_merge_with_illegal_distinct_id` | entrance |+| target illegal, oversized, or NUL-bearing (request rejected) | `cannot_merge_with_illegal_distinct_id`, one per source | entrance |+| `skipped_already_identified` | `cannot_merge_already_identified` | entrance (inline) or saga terminal record |+| `skipped_refused`, `error` | `merge_settled_failure` | saga terminal record |+| `skipped_conflict` replayed as settled by a recorded op | `merge_race_condition` | saga terminal record |+| `skipped_conflict` in a claim abort, `skipped_move_limit`, call failures | none here; the caller's | - |++Saga warnings emit once per committed terminal record, so an op the sweeper finishes warns exactly as one the RPC drove, and a retry that attaches to a finished op emits nothing new.+Inline verdicts re-emit when a retry re-classifies, the same at-least-once the response has; the producer throttles per team, warning type, and source distinct id (one an hour), with a per-pod per-type budget behind it.++`INGESTION_WARNINGS_ENABLED` (default `false`) turns the producer on; `INGESTION_WARNINGS_KAFKA_HOSTS`, `INGESTION_WARNINGS_KAFKA_TLS`, and `INGESTION_WARNINGS_TOPIC` (default `clickhouse_ingestion_warnings`) name the destination, a cluster separate from any event producer with a fixed fire-and-forget policy (leader ack, no retries, bounded queue).+Keep it off until the ingestion consumer stops emitting the same verdicts itself, or customers see each refusal twice.+Health reads from `ingestion_warnings_emitter_enabled{reason}` (absent when off, `0` when enabled but unusable) and `ingestion_warnings_total{source="personhog-identity",outcome}` (`emitted`, `throttled`, `delivered`, `delivery_failed`, ...).+## Delete retries must present a byte-stable requestA same-op-id delete retry is compared byte-for-byte against the frozen request, so the caller must present the identical `person_ids` list (same order, same duplicates) on every retry; a mismatch is refused `op_id_reused` and the deletion must be reissued under a fresh op id.diff --git a/rust/personhog-identity/src/config.rs b/rust/personhog-identity/src/config.rsindex 45eb82a6102c..b453cadeeae1 100644--- a/rust/personhog-identity/src/config.rs+++ b/rust/personhog-identity/src/config.rs@@ -2,6 +2,7 @@ use common_database::PoolConfig;use envconfig::Envconfig;use personhog_common::h2_window::{Http2Windows, WindowSize};use std::net::SocketAddr;+use std::num::NonZeroU32;use std::time::Duration;use crate::pools::Lane;@@ -196,6 +197,53 @@ pub struct Config {#[envconfig(default = "10000")]pub lifecycle_gc_batch_limit: i64,+ /// Off until the ingestion consumer stops emitting the same merge+ /// verdicts itself, or customers see each refusal twice.+ #[envconfig(default = "false")]+ pub ingestion_warnings_enabled: bool,++ #[envconfig(default = "")]+ pub ingestion_warnings_kafka_hosts: String,++ #[envconfig(default = "false")]+ pub ingestion_warnings_kafka_tls: bool,++ #[envconfig(default = "clickhouse_ingestion_warnings")]+ pub ingestion_warnings_topic: String,++ #[envconfig(default = "16")]+ pub ingestion_warnings_kafka_queue_mib: u32,++ #[envconfig(default = "1048576")]+ pub ingestion_warnings_kafka_message_max_bytes: u32,++ /// The defaults below are fire-and-forget: a warning is worth less than+ /// the cost of retrying it, and a slow warnings topic must not hold a merge.+ #[envconfig(default = "1")]+ pub ingestion_warnings_kafka_acks: String,++ #[envconfig(default = "0")]+ pub ingestion_warnings_kafka_retries: u32,++ #[envconfig(default = "100")]+ pub ingestion_warnings_kafka_linger_ms: u32,++ #[envconfig(default = "10000")]+ pub ingestion_warnings_kafka_queue_messages: u32,++ #[envconfig(default = "5000")]+ pub ingestion_warnings_kafka_message_timeout_ms: u32,++ /// Warnings a second per type that one pod sends, shared by every team+ /// on it; the rest are dropped as `type_budget_exhausted`.+ #[envconfig(default = "60")]+ pub ingestion_warnings_type_budget_per_second: NonZeroU32,++ /// Throttle keys (team, distinct id, type) a pod remembers for the hour a+ /// key lives, at roughly 135 bytes each.+ #[envconfig(default = "1000000")]+ pub ingestion_warnings_max_tracked_scopes: usize,+/// Write the publish outbox, one row per create or attach mapping and/// one pointer per completed merge or delete op, for the separate/// personhog-publisher deployment to drain. Off, identity writes nothing@@ -469,6 +517,24 @@ impl Config {pub fn lifecycle_op_retention(&self) -> Duration {Duration::from_secs(self.lifecycle_op_retention_hours * 3600)}++ pub fn ingestion_warnings_settings(&self) -> crate::warnings::WarningsSettings {+ crate::warnings::WarningsSettings {+ enabled: self.ingestion_warnings_enabled,+ kafka_hosts: self.ingestion_warnings_kafka_hosts.clone(),+ kafka_tls: self.ingestion_warnings_kafka_tls,+ topic: self.ingestion_warnings_topic.clone(),+ kafka_queue_mib: self.ingestion_warnings_kafka_queue_mib,+ kafka_message_max_bytes: self.ingestion_warnings_kafka_message_max_bytes,+ kafka_acks: self.ingestion_warnings_kafka_acks.clone(),+ kafka_retries: self.ingestion_warnings_kafka_retries,+ kafka_linger_ms: self.ingestion_warnings_kafka_linger_ms,+ kafka_queue_messages: self.ingestion_warnings_kafka_queue_messages,+ kafka_message_timeout_ms: self.ingestion_warnings_kafka_message_timeout_ms,+ type_budget_per_second: self.ingestion_warnings_type_budget_per_second,+ max_tracked_scopes: self.ingestion_warnings_max_tracked_scopes,+ }+ }}#[cfg(test)]diff --git a/rust/personhog-identity/src/lib.rs b/rust/personhog-identity/src/lib.rsindex 9a8be18e8e1a..2c554bdb0f78 100644--- a/rust/personhog-identity/src/lib.rs+++ b/rust/personhog-identity/src/lib.rs@@ -5,3 +5,4 @@ pub mod pools;pub mod publish;pub mod service;pub mod storage;+pub mod warnings;diff --git a/rust/personhog-identity/src/lifecycle/merge.rs b/rust/personhog-identity/src/lifecycle/merge.rsindex 952c19f39452..39f3c1cfef28 100644--- a/rust/personhog-identity/src/lifecycle/merge.rs+++ b/rust/personhog-identity/src/lifecycle/merge.rs@@ -56,6 +56,7 @@ use crate::lifecycle::engine::{STEP_ABORTED, STEP_COMPLETED,};use crate::pools::{IdentityPools, Lane};+use crate::warnings::{effective_event_uuid, MergePair, MergeWarnings, MERGE_SAGA};use personhog_common::query_tag;// Derived from the shared enum so the op-type string cannot drift from@@ -198,6 +199,8 @@ pub struct MergeSourceRecord {/// Defaulted so rows written before the field existed replay as `None`.#[serde(default)]pub person_id: Option<i64>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub person_uuid: Option<Uuid>,}pub const OUTCOME_MERGED: &str = "merged";@@ -224,6 +227,9 @@ impl AbortOutcome {}}pub const OUTCOME_ERROR: &str = "error";+/// Handler-decided outcomes that never reach the saga.+pub const OUTCOME_SKIPPED_ILLEGAL: &str = "skipped_illegal";+pub const OUTCOME_ATTACHED: &str = "attached";/// Per-person row statuses this driver writes. `marked`/`sealed` are the/// mark-covered set (the partial unique index); everything else releases@@ -325,6 +331,8 @@ struct Disposition {/// The person the did resolved to at claim time; absent when it/// resolved to nothing.person_id: Option<i64>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ person_uuid: Option<Uuid>,decision: String,}@@ -353,6 +361,7 @@ pub struct MergeDriver {leader: Arc<dyn LifecycleLeader>,tables: IdentityTables,leader_call_concurrency: usize,+ warnings: MergeWarnings,outbox_writes: OutboxWrites,}@@ -369,9 +378,148 @@ impl MergeDriver {tables,// Clamped to 1: a zero-width buffered stream never polls.leader_call_concurrency: leader_call_concurrency.max(1),+ warnings: MergeWarnings::disabled(),outbox_writes,}}++ pub fn with_warnings(mut self, warnings: MergeWarnings) -> Self {+ self.warnings = warnings;+ self+ }+}++/// The caller's durability decision: every outcome is final under retry+/// except a claim conflict, and only where a retry actually re-runs it+/// (a discarded claim abort, or an inline answer with no op row).+pub(crate) fn outcome_settled(outcome: &str) -> bool {+ outcome != OUTCOME_SKIPPED_CONFLICT+}++/// Borrowed views of the frozen request and recorded outcome, so emitting+/// never clones the row and serde owns the key names.+#[derive(Deserialize)]+struct RequestView<'a> {+ #[serde(borrow)]+ target_distinct_id: &'a str,+ #[serde(borrow, default)]+ creator_event_uuid: &'a str,+ #[serde(borrow)]+ sources: Vec<SourceView<'a>>,+ /// Verdicts the entrance gave before the saga, by distinct id; a row+ /// frozen without an entrance pass has none.+ #[serde(borrow, default)]+ inline_results: HashMap<&'a str, &'a str>,+}++#[derive(Deserialize)]+struct SourceView<'a> {+ #[serde(borrow)]+ distinct_id: &'a str,+ #[serde(borrow, default)]+ event_uuid: &'a str,+}++#[derive(Deserialize)]+struct OutcomeView<'a> {+ #[serde(borrow, default)]+ survivor: Option<SurvivorView<'a>>,+ #[serde(borrow)]+ results: Vec<RecordView<'a>>,+}++#[derive(Deserialize)]+struct SurvivorView<'a> {+ #[serde(borrow, default)]+ uuid: Option<&'a str>,+}++#[derive(Deserialize)]+struct RecordView<'a> {+ #[serde(borrow)]+ distinct_id: &'a str,+ #[serde(borrow)]+ outcome: &'a str,+ #[serde(default)]+ person_id: Option<i64>,+ #[serde(default)]+ person_uuid: Option<Uuid>,+}++fn emit_terminal_warnings(warnings: &MergeWarnings, op: &OpRow, outcome: &Value) {+ if !warnings.is_enabled() {+ return;+ }+ let request = match RequestView::deserialize(&op.request) {+ Ok(request) => request,+ Err(error) => {+ tracing::warn!(op_id = %op.op_id, %error, "merge warnings skipped: frozen request did not parse");+ return;+ }+ };+ let recorded = match OutcomeView::deserialize(outcome) {+ Ok(recorded) => recorded,+ Err(error) => {+ tracing::warn!(op_id = %op.op_id, %error, "merge warnings skipped: recorded outcome did not parse");+ return;+ }+ };+ let event_uuids: HashMap<&str, &str> = request+ .sources+ .iter()+ .map(|source| (source.distinct_id, source.event_uuid))+ .collect();+ let claim_abort = MergeOpExecutor::is_claim_abort_outcome(outcome);+ let survivor_uuid = recorded+ .survivor+ .as_ref()+ .and_then(|survivor| survivor.uuid)+ .and_then(|uuid| Uuid::parse_str(uuid).ok());+ for record in &recorded.results {+ let event_uuid = effective_event_uuid(+ event_uuids.get(record.distinct_id).copied().unwrap_or(""),+ request.creator_event_uuid,+ );+ warnings.emit_verdict(+ op.team_id,+ MERGE_SAGA,+ record.outcome,+ outcome_settled(record.outcome) || !claim_abort,+ &MergePair {+ source_distinct_id: record.distinct_id,+ target_distinct_id: request.target_distinct_id,+ event_uuid,+ source_person_id: record.person_id,+ source_person_uuid: record.person_uuid,+ survivor_uuid,+ },+ );+ }+ // An inline conflict is unsettled at the entrance, so it warned nothing+ // there; this op finishing without a claim abort is what settles it,+ // the same way the response reports it.+ if claim_abort {+ return;+ }+ for (distinct_id, outcome) in &request.inline_results {+ if outcome_settled(outcome) {+ continue;+ }+ warnings.emit_verdict(+ op.team_id,+ MERGE_SAGA,+ outcome,+ true,+ &MergePair {+ source_distinct_id: distinct_id,+ target_distinct_id: request.target_distinct_id,+ event_uuid: request.creator_event_uuid,+ source_person_id: None,+ source_person_uuid: None,+ survivor_uuid,+ },+ );+ }}/// Everything the merge entrance may do with merge op rows: probe for an@@ -412,9 +560,11 @@ impl MergeOpExecutor {&& row.outcome.as_ref()- .and_then(|o| o.get("claim_abort"))- .and_then(Value::as_bool)- == Some(true)+ .is_some_and(Self::is_claim_abort_outcome)+ }++ pub fn is_claim_abort_outcome(outcome: &Value) -> bool {+ outcome.get("claim_abort").and_then(Value::as_bool) == Some(true)}/// Delete a claim-aborted op; the flag is re-checked in SQL.@@ -674,11 +824,20 @@ impl MergeDriver {.map(|s| Disposition {distinct_id: s.distinct_id.clone(),person_id: None,+ person_uuid: None,decision: OUTCOME_SKIPPED_CONFLICT.to_string(),}).collect();conflicts.push(("target_vanished", dispositions.len() as u64));- return abort_in_claim_tx(tx, &self.tables, op, dispositions, conflicts).await;+ return abort_in_claim_tx(+ tx,+ &self.tables,+ &self.warnings,+ op,+ dispositions,+ conflicts,+ )+ .await;};let (target_person_id, target_person_uuid) = (target.person_id, target.person_uuid);@@ -695,6 +854,7 @@ impl MergeDriver {dispositions.push(Disposition {distinct_id: source.distinct_id.clone(),person_id: None,+ person_uuid: None,decision: OUTCOME_SKIPPED_CONFLICT.to_string(),});continue;@@ -703,6 +863,7 @@ impl MergeDriver {dispositions.push(Disposition {distinct_id: source.distinct_id.clone(),person_id: Some(resolution.person_id),+ person_uuid: Some(resolution.person_uuid),decision: OUTCOME_NOOP_SAME_PERSON.to_string(),});continue;@@ -715,6 +876,7 @@ impl MergeDriver {dispositions.push(Disposition {distinct_id: source.distinct_id.clone(),person_id: Some(resolution.person_id),+ person_uuid: Some(resolution.person_uuid),decision: OUTCOME_SKIPPED_ALREADY_IDENTIFIED.to_string(),});continue;@@ -728,6 +890,7 @@ impl MergeDriver {dispositions.push(Disposition {distinct_id: source.distinct_id.clone(),person_id: Some(resolution.person_id),+ person_uuid: Some(resolution.person_uuid),decision: DECISION_PENDING_MERGE.to_string(),});}@@ -823,7 +986,15 @@ impl MergeDriver {}}conflicts.push(("target_marked", converted));- return abort_in_claim_tx(tx, &self.tables, op, dispositions, conflicts).await;+ return abort_in_claim_tx(+ tx,+ &self.tables,+ &self.warnings,+ op,+ dispositions,+ conflicts,+ )+ .await;}// Sources another live op holds: record the skip (the status keeps@@ -887,7 +1058,15 @@ impl MergeDriver {}}conflicts.push(("target_vanished", converted));- return abort_in_claim_tx(tx, &self.tables, op, dispositions, conflicts).await;+ return abort_in_claim_tx(+ tx,+ &self.tables,+ &self.warnings,+ op,+ dispositions,+ conflicts,+ )+ .await;}let dropped = reconcile_pending_claims(&mut dispositions,@@ -931,7 +1110,15 @@ impl MergeDriver {STATUS_MARKED=> execute(&mut *tx))?;- return abort_in_claim_tx(tx, &self.tables, op, dispositions, conflicts).await;+ return abort_in_claim_tx(+ tx,+ &self.tables,+ &self.warnings,+ op,+ dispositions,+ conflicts,+ )+ .await;}// Persist the claim record on the target row; the terminal outcome@@ -997,6 +1184,7 @@ async fn write_claim_record(async fn abort_in_claim_tx(mut tx: Tx<'_>,tables: &IdentityTables,+ warnings: &MergeWarnings,op: &OpRow,dispositions: Vec<Disposition>,conflicts: Vec<(&'static str, u64)>,@@ -1026,6 +1214,7 @@ async fn abort_in_claim_tx(record_conflicts(conflicts);record_transition(MergeStep::Started.as_str(), STEP_ABORTED);record_outcomes(MergeStep::Started.as_str(), &outcome);+ emit_terminal_warnings(warnings, op, &outcome);Ok(())}@@ -1154,6 +1343,7 @@ impl MergeDriver {tx.commit().await?;record_transition(MergeStep::Claimed.as_str(), STEP_ABORTED);record_outcomes(MergeStep::Claimed.as_str(), &outcome);+ emit_terminal_warnings(&self.warnings, op, &outcome);return Ok(());}@@ -1250,6 +1440,7 @@ impl MergeDriver {1,);record_outcomes(from_step.as_str(), &outcome);+ emit_terminal_warnings(&self.warnings, op, &outcome);// Releases only after the completing CAS proves we still owned the// op; ghosts left by a crash here are healed lazily by the leader.self.release_fences(op, &pairs).await?;@@ -1971,6 +2162,7 @@ impl MergeDriver {tx.commit().await?;record_transition(MergeStep::Flipped.as_str(), STEP_COMPLETED);record_outcomes(MergeStep::Flipped.as_str(), &outcome);+ emit_terminal_warnings(&self.warnings, op, &outcome);Ok(())}}@@ -2066,6 +2258,7 @@ fn outcome_from_dispositions(distinct_id: d.distinct_id.clone(),outcome: outcome.to_string(),person_id: d.person_id,+ person_uuid: d.person_uuid,}}).collect();@@ -2079,12 +2272,83 @@ fn outcome_from_dispositions(#[cfg(test)]mod tests {+ use std::sync::Arc;++ use chrono::Utc;+ use common_ingestion_warnings::test_support::CollectingRowEmitter;+ use common_ingestion_warnings::WarningType;+use super::*;+ fn terminal_row(request: &MergeRequest, outcome: &Value) -> OpRow {+ OpRow {+ op_id: Uuid::now_v7(),+ op_type: OP_TYPE_MERGE.to_string(),+ team_id: 7,+ step: STEP_ABORTED.to_string(),+ attempt: 1,+ request: serde_json::to_value(request).unwrap(),+ outcome: Some(outcome.clone()),+ created_at: Utc::now(),+ completed_at: Some(Utc::now()),+ lease_live: false,+ }+ }++ #[test]+ fn terminal_warnings_read_the_recorded_shapes() {+ let source_uuid = Uuid::new_v4();+ let survivor_uuid = Uuid::new_v4();+ let request = MergeRequest {+ target_distinct_id: "user-1".to_string(),+ sources: vec![MergeSourceEntry {+ distinct_id: "anon-1".to_string(),+ event_uuid: String::new(),+ }],+ event_set: serde_json::json!({"plan": "pro"}),+ event_set_once: serde_json::json!({}),+ allow_identified_sources: false,+ move_limit: 10,+ creator_event_uuid: "creator".to_string(),+ target_born: false,+ };+ let outcome = serde_json::to_value(MergeOutcome {+ aborted: false,+ survivor: Some(serde_json::json!({"id": 9, "uuid": survivor_uuid})),+ results: vec![MergeSourceRecord {+ distinct_id: "anon-1".to_string(),+ outcome: OUTCOME_SKIPPED_REFUSED.to_string(),+ person_id: Some(42),+ person_uuid: Some(source_uuid),+ }],+ })+ .unwrap();+ let row = terminal_row(&request, &outcome);++ let emitter = Arc::new(CollectingRowEmitter::new());+ emit_terminal_warnings(&MergeWarnings::new(emitter.clone()), &row, &outcome);+ let rows = emitter.rows();+ assert_eq!(rows.len(), 1);+ assert_eq!(rows[0].warning, WarningType::MergeSettledFailure);+ assert_eq!(rows[0].team_id, 7);+ let details = rows[0].details();+ assert_eq!(details["sourcePersonDistinctId"], "anon-1");+ assert_eq!(details["targetPersonDistinctId"], "user-1");+ assert_eq!(+ details["eventUuid"], "creator",+ "empty source event falls back"+ );+ assert_eq!(details["sourcePersonId"], "42");+ assert_eq!(details["otherPersonId"], source_uuid.to_string());+ assert_eq!(details["personId"], survivor_uuid.to_string());+ assert_eq!(details["outcome"], OUTCOME_SKIPPED_REFUSED);+ }+fn pending(distinct_id: &str, person_id: i64) -> Disposition {Disposition {distinct_id: distinct_id.to_string(),person_id: Some(person_id),+ person_uuid: None,decision: DECISION_PENDING_MERGE.to_string(),}}diff --git a/rust/personhog-identity/src/lifecycle/validation.rs b/rust/personhog-identity/src/lifecycle/validation.rsindex 3b2d86318fc3..bb1dbac5f717 100644--- a/rust/personhog-identity/src/lifecycle/validation.rs+++ b/rust/personhog-identity/src/lifecycle/validation.rs@@ -93,15 +93,18 @@ pub fn is_distinct_id_illegal(id: &str) -> bool {|| CASE_SENSITIVE_ILLEGAL_IDS.contains(id)}+/// Above i32::MAX the storage layer's `as i32` narrowing would wrap into+/// another tenant's rows.+pub fn is_team_id_valid(team_id: i64) -> bool {+ team_id > 0 && team_id <= i32::MAX as i64+}+// tonic Status is a large Err variant; boxing here would diverge from the// tonic handler signatures these feed into.#[allow(clippy::result_large_err)]/// Validates the request and returns the parsed op_id.pub fn validate_delete_persons(request: &DeletePersonsRequest) -> Result<Uuid, Status> {- // The persons DB stores team_id as int4 and the storage layer narrows- // with `as i32` — an unchecked value above i32::MAX would wrap and read- // or write another tenant's rows.- if request.team_id <= 0 || request.team_id > i32::MAX as i64 {+ if !is_team_id_valid(request.team_id) {return Err(rejected("team_id","team_id must be a positive 32-bit integer",@@ -128,42 +131,84 @@ pub fn validate_delete_persons(request: &DeletePersonsRequest) -> Result<Uuid, SUuid::parse_str(&request.op_id).map_err(|_| rejected("op_id", "op_id must be a valid UUID"))}+/// The id that made a merge request unmergeable, so the entrance warns+/// the customer about that id and no other.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum UnmergeableId {+ Target,+ /// Index into `request.sources`.+ Source(usize),+}++/// A rejected merge request: the gRPC status, plus the offending id when+/// the rejection is one the customer can act on.+pub struct MergeRejection {+ pub status: Status,+ pub unmergeable: Option<UnmergeableId>,+}++impl From<Status> for MergeRejection {+ fn from(status: Status) -> Self {+ Self {+ status,+ unmergeable: None,+ }+ }+}++impl MergeRejection {+ fn unmergeable(status: Status, id: UnmergeableId) -> Self {+ Self {+ status,+ unmergeable: Some(id),+ }+ }+}+// See validate_delete_persons for why result_large_err is allowed.#[allow(clippy::result_large_err)]/// Validates the request and returns the parsed op_id and move_limit./// Illegal SOURCE distinct ids are per-source outcomes, not request/// errors — only the target's legality gates the whole call (nothing can/// merge into a bug).-pub fn validate_merge_persons(request: &MergePersonsRequest) -> Result<(Uuid, i64), Status> {- if request.team_id <= 0 || request.team_id > i32::MAX as i64 {- return Err(rejected(- "team_id",- "team_id must be a positive 32-bit integer",- ));+pub fn validate_merge_persons(+ request: &MergePersonsRequest,+) -> Result<(Uuid, i64), MergeRejection> {+ if !is_team_id_valid(request.team_id) {+ return Err(rejected("team_id", "team_id must be a positive 32-bit integer").into());}if is_distinct_id_oversized(&request.target_distinct_id) {- return Err(rejected(- "target_distinct_id_length",- format!("target_distinct_id exceeds {MAX_DISTINCT_ID_LENGTH} characters"),+ return Err(MergeRejection::unmergeable(+ rejected(+ "target_distinct_id_length",+ format!("target_distinct_id exceeds {MAX_DISTINCT_ID_LENGTH} characters"),+ ),+ UnmergeableId::Target,));}if is_distinct_id_illegal(&request.target_distinct_id) {- return Err(rejected(- "target_distinct_id_illegal",- "target_distinct_id is an illegal distinct id",+ return Err(MergeRejection::unmergeable(+ rejected(+ "target_distinct_id_illegal",+ "target_distinct_id is an illegal distinct id",+ ),+ UnmergeableId::Target,));}// Postgres cannot store NUL in text: an unresolved NUL target would// reach the establish path and fail person creation with an internal// error on every attempt.if request.target_distinct_id.contains('\u{0000}') {- return Err(rejected(- "target_distinct_id_nul",- "target_distinct_id must not contain NUL",+ return Err(MergeRejection::unmergeable(+ rejected(+ "target_distinct_id_nul",+ "target_distinct_id must not contain NUL",+ ),+ UnmergeableId::Target,));}if request.sources.is_empty() {- return Err(rejected("sources_empty", "sources must not be empty"));+ return Err(rejected("sources_empty", "sources must not be empty").into());}if request.sources.len() > MAX_MERGE_BATCH_SIZE {return Err(rejected(@@ -172,18 +217,22 @@ pub fn validate_merge_persons(request: &MergePersonsRequest) -> Result<(Uuid, i6"batch size {} exceeds maximum {MAX_MERGE_BATCH_SIZE}",request.sources.len()),- ));+ )+ .into());}let mut seen = HashSet::with_capacity(request.sources.len());- for source in &request.sources {+ for (index, source) in request.sources.iter().enumerate() {// NUL is a whole-request reject where oversized ids are a// per-source outcome: Postgres cannot store NUL in text at all,// so the frozen op row — which must record every requested// source for retries — would be unwritable jsonb.if source.source_distinct_id.contains('\u{0000}') {- return Err(rejected(- "source_distinct_id_nul",- "source distinct ids must not contain NUL",+ return Err(MergeRejection::unmergeable(+ rejected(+ "source_distinct_id_nul",+ "source distinct ids must not contain NUL",+ ),+ UnmergeableId::Source(index),));}if !seen.insert(source.source_distinct_id.as_str()) {@@ -193,20 +242,21 @@ pub fn validate_merge_persons(request: &MergePersonsRequest) -> Result<(Uuid, i6"duplicate source distinct id: the caller must dedupe (\"{}\")",source.source_distinct_id),- ));+ )+ .into());}}// Unlimited is not a supported mode: the flip's repoint would be an// unbounded statement under statement_timeout.let move_limit = match request.move_limit {Some(limit) if limit >= 1 => limit,- Some(_) => return Err(rejected("move_limit", "move_limit must be positive")),- None => return Err(rejected("move_limit", "move_limit is required")),+ Some(_) => return Err(rejected("move_limit", "move_limit must be positive").into()),+ None => return Err(rejected("move_limit", "move_limit is required").into()),};if request.created_at < 0 {- return Err(rejected("created_at", "created_at must not be negative"));+ return Err(rejected("created_at", "created_at must not be negative").into());}let op_id = Uuid::parse_str(&request.op_id)- .map_err(|_| rejected("op_id", "op_id must be a valid UUID"))?;+ .map_err(|_| MergeRejection::from(rejected("op_id", "op_id must be a valid UUID")))?;Ok((op_id, move_limit))}diff --git a/rust/personhog-identity/src/main.rs b/rust/personhog-identity/src/main.rsindex 9adab1c995f2..fd50cd93635c 100644--- a/rust/personhog-identity/src/main.rs+++ b/rust/personhog-identity/src/main.rs@@ -34,6 +34,7 @@ use personhog_identity::pools::{IdentityPools, Lane};use personhog_identity::service::merge::MergeEntrance;use personhog_identity::service::PersonHogIdentityService;use personhog_identity::storage::postgres::PostgresIdentityStorage;+use personhog_identity::warnings;common_alloc::used!();@@ -175,12 +176,48 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {let sweeper_handle = config.lifecycle_sweeper_enabled.then(|| manager.register("lifecycle_sweeper", ComponentOptions::new()));+ let warnings_handle = config.ingestion_warnings_enabled.then(|| {+ manager.register(+ "ingestion_warnings",+ ComponentOptions::new()+ .with_liveness_deadline(Duration::from_secs(30))+ .is_advisory(true),+ )+ });let readiness = manager.readiness_handler();let liveness = manager.liveness_handler();let monitor = manager.monitor_background();+ // Dense from 250ms to 5s, where merge tails sit.+ const BUCKETS: &[f64] = &[+ 1.0, 5.0, 10.0, 25.0, 50.0, 100.0, 250.0, 500.0, 750.0, 1000.0, 1500.0, 2000.0, 3000.0,+ 5000.0, 10000.0, 30000.0,+ ];+ // Lifecycle ops span "settled in one drive" (tens of ms) to+ // "abandoned, parked, or leader-blocked and resumed by the sweeper"+ // (minutes to an hour); the default latency ladder tops out at 10s+ // and would collapse every resumed op into +Inf.+ const OP_DURATION_BUCKETS: &[f64] = &[+ 10.0, 50.0, 100.0, 250.0, 500.0, 1000.0, 2500.0, 5000.0, 10000.0, 30000.0, 60000.0,+ 300000.0, 1800000.0, 3600000.0,+ ];+ // Batch sizes, not latency; the request caps are 250.+ const PER_CALL_BUCKETS: &[f64] = &[1.0, 2.0, 3.0, 5.0, 10.0, 25.0, 50.0, 100.0, 250.0];+ let recorder_handle = PrometheusBuilder::new()+ .add_global_label("service", "personhog-identity")+ .set_buckets(BUCKETS)+ .unwrap()+ .set_buckets_for_metric(+ Matcher::Full("personhog_lifecycle_op_duration_ms".into()),+ OP_DURATION_BUCKETS,+ )+ .unwrap()+ .set_buckets_for_metric(Matcher::Suffix("_per_call".into()), PER_CALL_BUCKETS)+ .unwrap()+ .install_recorder()+ .expect("Failed to install metrics recorder");// Metrics/health HTTP server (observability handle — stays alive during standard drain)let metrics_port = config.metrics_port;tokio::spawn(async move {@@ -195,34 +232,6 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {}),).route("/_liveness", get(move || async move { liveness.check() }));- // Dense from 250ms to 5s, where merge tails sit.- const BUCKETS: &[f64] = &[- 1.0, 5.0, 10.0, 25.0, 50.0, 100.0, 250.0, 500.0, 750.0, 1000.0, 1500.0, 2000.0, 3000.0,- 5000.0, 10000.0, 30000.0,- ];- // Lifecycle ops span "settled in one drive" (tens of ms) to- // "abandoned, parked, or leader-blocked and resumed by the sweeper"- // (minutes to an hour); the default latency ladder tops out at 10s- // and would collapse every resumed op into +Inf.- const OP_DURATION_BUCKETS: &[f64] = &[- 10.0, 50.0, 100.0, 250.0, 500.0, 1000.0, 2500.0, 5000.0, 10000.0, 30000.0, 60000.0,- 300000.0, 1800000.0, 3600000.0,- ];- // Batch sizes, not latency; the request caps are 250.- const PER_CALL_BUCKETS: &[f64] = &[1.0, 2.0, 3.0, 5.0, 10.0, 25.0, 50.0, 100.0, 250.0];- let recorder_handle = PrometheusBuilder::new()- .add_global_label("service", "personhog-identity")- .set_buckets(BUCKETS)- .unwrap()- .set_buckets_for_metric(- Matcher::Full("personhog_lifecycle_op_duration_ms".into()),- OP_DURATION_BUCKETS,- )- .unwrap()- .set_buckets_for_metric(Matcher::Suffix("_per_call".into()), PER_CALL_BUCKETS)- .unwrap()- .install_recorder()- .expect("Failed to install metrics recorder");let metrics_router = health_router.route("/metrics",get(move || std::future::ready(recorder_handle.render())),@@ -270,6 +279,8 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {config.tables(),outbox_writes,));+ let merge_warnings = warnings::install(&config.ingestion_warnings_settings(), warnings_handle);+ let warnings_to_flush = merge_warnings.clone();// Pre-warm the DB connection pools before accepting traffic.// connect_lazy() starts with zero connections; without this, the first@@ -331,7 +342,8 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {config.tables(),config.lifecycle_leader_call_concurrency,outbox_writes,- );+ )+ .with_warnings(merge_warnings.clone());let sweeper_delete_driver = DeleteDriver::new(lifecycle_leader.clone(),config.tables(),@@ -390,10 +402,12 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {config.tables(),config.lifecycle_leader_call_concurrency,outbox_writes,- ),+ )+ .with_warnings(merge_warnings.clone()),detached_drives.clone(),),- );+ )+ .with_warnings(merge_warnings);let lifecycle_service = PersonHogLifecycleService::new(engine,lifecycle_leader,@@ -478,7 +492,14 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {detached_drives.shutdown().await;});- monitor.wait().await?;+ let waited = monitor.wait().await;++ // Flush before the result propagates: a failed component or a timed-out+ // drain is exactly the shutdown that leaves rows queued.+ if let Err(e) = tokio::task::spawn_blocking(move || warnings_to_flush.flush()).await {+ tracing::warn!(error = %e, "ingestion warnings flush task panicked");+ }+ waited?;Ok(())}diff --git a/rust/personhog-identity/src/service/merge.rs b/rust/personhog-identity/src/service/merge.rsindex 5b54db98f392..c50b0f56c202 100644--- a/rust/personhog-identity/src/service/merge.rs+++ b/rust/personhog-identity/src/service/merge.rs@@ -16,26 +16,24 @@ use serde_json::Value;use tonic::Status;use personhog_proto::personhog::identity::v1::{- MergePersonsRequest, MergePersonsResponse, MergeSourceOutcome, MergeSourceResult,+ MergePersonsRequest, MergePersonsResponse, MergeSource, MergeSourceOutcome, MergeSourceResult,};use personhog_proto::personhog::types::v1::{Person as ProtoPerson, UpdatePersonPropertiesRequest};use crate::leader::{PersonStateReader, PropertyWriter};use crate::lifecycle::engine::{OpRow, STEP_COMPLETED};use crate::lifecycle::merge::{- record_conflict, record_outcome_count, MergeOpExecutor, MergeOutcome, MergeRequest,- MergeSourceEntry, MergeSourceRecord, OP_TYPE_MERGE, OUTCOME_ERROR, OUTCOME_MERGED,- OUTCOME_NOOP_SAME_PERSON, OUTCOME_SKIPPED_ALREADY_IDENTIFIED, OUTCOME_SKIPPED_CONFLICT,- OUTCOME_SKIPPED_MOVE_LIMIT, OUTCOME_SKIPPED_REFUSED,+ outcome_settled, record_conflict, record_outcome_count, MergeOpExecutor, MergeOutcome,+ MergeRequest, MergeSourceEntry, MergeSourceRecord, OP_TYPE_MERGE, OUTCOME_ATTACHED,+ OUTCOME_ERROR, OUTCOME_MERGED, OUTCOME_NOOP_SAME_PERSON, OUTCOME_SKIPPED_ALREADY_IDENTIFIED,+ OUTCOME_SKIPPED_CONFLICT, OUTCOME_SKIPPED_ILLEGAL, OUTCOME_SKIPPED_MOVE_LIMIT,+ OUTCOME_SKIPPED_REFUSED,};use crate::lifecycle::validation::{- is_distinct_id_illegal, is_distinct_id_oversized, validate_merge_persons,+ is_distinct_id_illegal, is_distinct_id_oversized, validate_merge_persons, UnmergeableId,};use crate::storage::{AttachOutcome, IdentityStorage, Person, PersonStub, StubOutcome};--/// Handler-decided outcomes that never reach the saga.-const OUTCOME_SKIPPED_ILLEGAL: &str = "skipped_illegal";-const OUTCOME_ATTACHED: &str = "attached";+use crate::warnings::{effective_event_uuid, MergePair, MergeWarnings, MERGE_ENTRANCE};const MERGE_SOURCES_PER_CALL: &str = "personhog_identity_merge_sources_per_call";const MERGE_PHASE_DURATION: &str = "personhog_identity_merge_phase_duration_ms";@@ -179,6 +177,7 @@ pub struct MergeEntrance {property_writer: Arc<dyn PropertyWriter>,person_state: Arc<dyn PersonStateReader>,ops: MergeOpExecutor,+ warnings: MergeWarnings,}impl MergeEntrance {@@ -193,6 +192,48 @@ impl MergeEntrance {property_writer,person_state,ops,+ warnings: MergeWarnings::disabled(),+ }+ }++ pub fn with_warnings(mut self, warnings: MergeWarnings) -> Self {+ self.warnings = warnings;+ self+ }++ fn emit_rejection_warning(&self, request: &MergePersonsRequest, id: UnmergeableId) {+ if !self.warnings.is_enabled() {+ return;+ }+ // An illegal target is one warning about the target, whatever the+ // batch size; the first source stands in as the other side.+ let source: Option<&MergeSource> = match id {+ UnmergeableId::Target => request.sources.first(),+ UnmergeableId::Source(index) => request.sources.get(index),+ };+ let Some(source) = source else {+ return;+ };+ let pair = MergePair {+ source_distinct_id: &source.source_distinct_id,+ target_distinct_id: &request.target_distinct_id,+ event_uuid: effective_event_uuid(&source.event_uuid, &request.creator_event_uuid),+ source_person_id: None,+ source_person_uuid: None,+ survivor_uuid: None,+ };+ match id {+ UnmergeableId::Target => {+ self.warnings+ .emit_illegal_target(request.team_id, MERGE_ENTRANCE, &pair)+ }+ UnmergeableId::Source(_) => self.warnings.emit_verdict(+ request.team_id,+ MERGE_ENTRANCE,+ OUTCOME_SKIPPED_ILLEGAL,+ true,+ &pair,+ ),}}@@ -216,7 +257,15 @@ impl MergeEntrance {request: MergePersonsRequest,shape: &mut MergeShape,) -> Result<MergePersonsResponse, Status> {- let (op_id, move_limit) = validate_merge_persons(&request)?;+ let (op_id, move_limit) = match validate_merge_persons(&request) {+ Ok(validated) => validated,+ Err(rejection) => {+ if let Some(id) = rejection.unmergeable {+ self.emit_rejection_warning(&request, id);+ }+ return Err(rejection.status);+ }+ };common_metrics::histogram(MERGE_SOURCES_PER_CALL, &[], request.sources.len() as f64);let mut event_set = parse_json_map(&request.event_set, "event_set")?;let mut event_set_once = parse_json_map(&request.event_set_once, "event_set_once")?;@@ -402,6 +451,32 @@ impl MergeEntrance {for (outcome, count) in inline_counts {record_outcome_count(PATH_INLINE, outcome, count);}+ if self.warnings.is_enabled() {+ for source in &request.sources {+ let Some(outcome) = inline_results.get(&source.source_distinct_id) else {+ continue;+ };+ let source_person =+ resolved.get(&(request.team_id, source.source_distinct_id.clone()));+ self.warnings.emit_verdict(+ request.team_id,+ MERGE_ENTRANCE,+ outcome,+ outcome_settled(outcome),+ &MergePair {+ source_distinct_id: &source.source_distinct_id,+ target_distinct_id: &request.target_distinct_id,+ event_uuid: effective_event_uuid(+ &source.event_uuid,+ &request.creator_event_uuid,+ ),+ source_person_id: source_person.map(|p| p.id),+ source_person_uuid: source_person.map(|p| p.uuid),+ survivor_uuid: Some(target_person.uuid),+ },+ );+ }+ }if saga_sources.is_empty() {shape.path = PATH_INLINE;@@ -823,13 +898,6 @@ fn same_merge(recorded: Option<&Value>, incoming: &Value) -> bool {}}-/// The caller's durability decision: every outcome is final under retry-/// except a claim conflict, and only where a retry actually re-runs it-/// (a discarded claim abort, or an inline answer with no op row).-fn outcome_settled(outcome: &str) -> bool {- outcome != OUTCOME_SKIPPED_CONFLICT-}-fn outcome_enum(outcome: &str) -> MergeSourceOutcome {match outcome {OUTCOME_MERGED => MergeSourceOutcome::Merged,diff --git a/rust/personhog-identity/src/service/validation.rs b/rust/personhog-identity/src/service/validation.rsindex 6dd0afcc7870..1827e4c5d7e0 100644--- a/rust/personhog-identity/src/service/validation.rs+++ b/rust/personhog-identity/src/service/validation.rs@@ -2,6 +2,8 @@ use tonic::Status;use personhog_proto::personhog::identity::v1::GetOrCreatePersonEntry;+use crate::lifecycle::validation::is_team_id_valid;+/// Request-shape limits, sourced from service configuration.#[derive(Debug, Clone)]pub struct RequestLimits {@@ -36,7 +38,7 @@ pub(crate) fn rejected(reason: &'static str, message: impl Into<String>) -> Stat/// another tenant's rows.#[allow(clippy::result_large_err)]pub fn validate_team_id(team_id: i64) -> Result<(), Status> {- if team_id <= 0 || team_id > i32::MAX as i64 {+ if !is_team_id_valid(team_id) {return Err(rejected("team_id","team_id must be a positive 32-bit integer",@@ -61,10 +63,7 @@ pub fn validate_entry(limits: &RequestLimits,entry: &GetOrCreatePersonEntry,) -> Result<(), Status> {- // The persons DB stores team_id as int4 and the storage layer narrows- // with `as i32` — an unchecked value above i32::MAX would wrap and read- // or write another tenant's rows.- if entry.team_id <= 0 || entry.team_id > i32::MAX as i64 {+ if !is_team_id_valid(entry.team_id) {return Err(rejected("team_id","team_id must be a positive 32-bit integer",diff --git a/rust/personhog-identity/src/warnings.rs b/rust/personhog-identity/src/warnings.rsnew file mode 100644index 000000000000..46ca521d0025--- /dev/null+++ b/rust/personhog-identity/src/warnings.rs@@ -0,0 +1,690 @@+//! In-product ingestion warnings for the merge verdicts this service+//! settles: a verdict warns here when it is final under retry and decided+//! by this service alone. Unsettled conflicts, the move-limit skip, and+//! call failures stay with the caller, which alone knows its retry budget+//! and merge-mode policy.++use std::num::NonZeroU32;+use std::sync::Arc;+use std::time::Duration;++use common_ingestion_warnings::serializer::Warning;+use common_ingestion_warnings::throttle::{WarningThrottle, DEFAULT_MAX_TRACKED_KEYS};+use common_ingestion_warnings::{+ observe_delivery, KafkaRowWarningEmitter, RowWarningEmitter, WarningSource, WarningType,+ INGESTION_WARNINGS_EMITTER_ENABLED,+};+use common_kafka::config::KafkaConfig;+use common_kafka::kafka_producer::create_threaded_kafka_producer_no_ping;+use uuid::Uuid;++use crate::lifecycle::merge::{+ OUTCOME_ERROR, OUTCOME_SKIPPED_ALREADY_IDENTIFIED, OUTCOME_SKIPPED_CONFLICT,+ OUTCOME_SKIPPED_ILLEGAL, OUTCOME_SKIPPED_REFUSED,+};++pub const SERVICE: &str = "personhog-identity";+const PIPELINE_STEP: &str = "personhog_merge";++pub const MERGE_ENTRANCE: WarningSource = WarningSource {+ service: SERVICE,+ path: "merge_entrance",+ pipeline_step: PIPELINE_STEP,+};++pub const MERGE_SAGA: WarningSource = WarningSource {+ service: SERVICE,+ path: "merge_saga",+ pipeline_step: PIPELINE_STEP,+};++const KAFKA_CLIENT_ID: &str = "personhog-identity-ingestion-warnings";+/// Default for `INGESTION_WARNINGS_TYPE_BUDGET_PER_SECOND`.+pub const DEFAULT_TYPE_BUDGET_PER_SECOND: NonZeroU32 = NonZeroU32::new(60).unwrap();+/// Default for `INGESTION_WARNINGS_MAX_TRACKED_SCOPES`. Keys are per distinct+/// id, so the crate default (sized for capture's per-token keys) would fill+/// within the hour a key lives and silence every team on the pod. The type+/// budgets admit well under this many keys an hour.+pub const DEFAULT_MAX_TRACKED_SCOPES: usize = 1_000_000;+const _: () = assert!(DEFAULT_MAX_TRACKED_SCOPES > DEFAULT_MAX_TRACKED_KEYS);+const THROTTLE_SWEEP_INTERVAL: Duration = Duration::from_secs(60);+/// The distinct id column's own limit: a legal id is never cut, and an+/// oversized one is cut before it is copied into details.+const MAX_DETAIL_ID_CHARS: usize = 400;+const SHUTDOWN_FLUSH: Duration = Duration::from_secs(2);++fn bounded(id: &str) -> &str {+ match id.char_indices().nth(MAX_DETAIL_ID_CHARS) {+ Some((end, _)) => &id[..end],+ None => id,+ }+}++pub fn effective_event_uuid<'a>(event_uuid: &'a str, creator_event_uuid: &'a str) -> &'a str {+ if event_uuid.is_empty() {+ creator_event_uuid+ } else {+ event_uuid+ }+}++pub struct MergePair<'a> {+ pub source_distinct_id: &'a str,+ pub target_distinct_id: &'a str,+ pub event_uuid: &'a str,+ pub source_person_id: Option<i64>,+ pub source_person_uuid: Option<Uuid>,+ pub survivor_uuid: Option<Uuid>,+}++impl MergePair<'_> {+ fn base(&self, warning: WarningType) -> Warning {+ Warning::new(warning)+ .with_detail("sourcePersonDistinctId", bounded(self.source_distinct_id))+ .with_detail("targetPersonDistinctId", bounded(self.target_distinct_id))+ .with_detail("distinctId", bounded(self.target_distinct_id))+ .with_detail("eventUuid", bounded(self.event_uuid))+ }++ fn with_person_ids(&self, mut warning: Warning) -> Warning {+ if let Some(uuid) = self.source_person_uuid {+ warning = warning.with_detail("otherPersonId", uuid.to_string());+ }+ if let Some(uuid) = self.survivor_uuid {+ warning = warning.with_detail("personId", uuid.to_string());+ }+ warning+ }++ fn illegal(&self, illegal_distinct_id: &str, other_distinct_id: &str) -> Warning {+ Warning::new(WarningType::CannotMergeWithIllegalDistinctId)+ .with_detail("illegalDistinctId", bounded(illegal_distinct_id))+ .with_detail("otherDistinctId", bounded(other_distinct_id))+ .with_detail("distinctId", bounded(self.target_distinct_id))+ .with_detail("eventUuid", bounded(self.event_uuid))+ }+}++pub fn verdict_warning(outcome: &str, settled: bool, pair: &MergePair<'_>) -> Option<Warning> {+ if !settled {+ return None;+ }+ match outcome {+ OUTCOME_SKIPPED_ILLEGAL => {+ Some(pair.illegal(pair.source_distinct_id, pair.target_distinct_id))+ }+ OUTCOME_SKIPPED_ALREADY_IDENTIFIED => {+ Some(pair.with_person_ids(pair.base(WarningType::CannotMergeAlreadyIdentified)))+ }+ OUTCOME_SKIPPED_CONFLICT => {+ Some(pair.with_person_ids(pair.base(WarningType::MergeRaceCondition)))+ }+ OUTCOME_SKIPPED_REFUSED | OUTCOME_ERROR => {+ let mut warning = pair+ .with_person_ids(pair.base(WarningType::MergeSettledFailure))+ .with_detail("outcome", outcome);+ if let Some(id) = pair.source_person_id {+ warning = warning.with_detail("sourcePersonId", id.to_string());+ }+ Some(warning)+ }+ _ => None,+ }+}++pub fn illegal_target_warning(pair: &MergePair<'_>) -> Warning {+ pair.illegal(pair.target_distinct_id, pair.source_distinct_id)+}++#[derive(Clone)]+pub struct MergeWarnings {+ emitter: Option<Arc<dyn RowWarningEmitter>>,+}++impl MergeWarnings {+ pub fn new(emitter: Arc<dyn RowWarningEmitter>) -> Self {+ Self {+ emitter: Some(emitter),+ }+ }++ pub fn disabled() -> Self {+ Self { emitter: None }+ }++ /// Lets a caller skip building warnings at all when nothing would send them.+ pub fn is_enabled(&self) -> bool {+ self.emitter.is_some()+ }++ pub fn emit_verdict(+ &self,+ team_id: i64,+ source: WarningSource,+ outcome: &str,+ settled: bool,+ pair: &MergePair<'_>,+ ) {+ let Some(emitter) = &self.emitter else {+ return;+ };+ if let Some(warning) = verdict_warning(outcome, settled, pair) {+ emitter.emit(team_id, pair.source_distinct_id, source, warning);+ }+ }++ /// Scoped by the target, the id the warning is about; scoped by the+ /// source, one bad target would hold a key per visitor and eat the budget.+ pub fn emit_illegal_target(&self, team_id: i64, source: WarningSource, pair: &MergePair<'_>) {+ if let Some(emitter) = &self.emitter {+ emitter.emit(+ team_id,+ pair.target_distinct_id,+ source,+ illegal_target_warning(pair),+ );+ }+ }++ /// Blocking; call from a blocking task once every tracked component that+ /// enqueues warnings has drained. The emitter's own task is advisory and+ /// receives shutdown alongside the gRPC server, so it cannot flush last.+ pub fn flush(&self) {+ if let Some(emitter) = &self.emitter {+ emitter.flush(SHUTDOWN_FLUSH);+ }+ }+}++#[derive(Debug, Clone, PartialEq, Eq)]+pub struct WarningsSettings {+ pub enabled: bool,+ pub kafka_hosts: String,+ pub kafka_tls: bool,+ pub topic: String,+ pub kafka_queue_mib: u32,+ pub kafka_message_max_bytes: u32,+ pub kafka_acks: String,+ pub kafka_retries: u32,+ pub kafka_linger_ms: u32,+ pub kafka_queue_messages: u32,+ pub kafka_message_timeout_ms: u32,+ pub type_budget_per_second: NonZeroU32,+ pub max_tracked_scopes: usize,+}++impl WarningsSettings {+ pub fn kafka_config(&self) -> KafkaConfig {+ KafkaConfig {+ kafka_hosts: self.kafka_hosts.clone(),+ kafka_tls: self.kafka_tls,+ kafka_client_id: KAFKA_CLIENT_ID.to_string(),+ kafka_producer_acks: Some(self.kafka_acks.clone()),+ kafka_producer_retries: Some(self.kafka_retries),+ kafka_producer_linger_ms: self.kafka_linger_ms,+ kafka_producer_queue_messages: self.kafka_queue_messages,+ kafka_message_timeout_ms: self.kafka_message_timeout_ms,+ kafka_producer_queue_mib: self.kafka_queue_mib,+ kafka_producer_message_max_bytes: Some(self.kafka_message_max_bytes),+ ..Default::default()+ }+ }++ pub fn disabled_reason(&self) -> Option<&'static str> {+ if !self.enabled {+ return Some("disabled");+ }+ if self.kafka_hosts.is_empty() {+ return Some("hosts_unset");+ }+ if self.topic.is_empty() {+ return Some("topic_unset");+ }+ None+ }+}++fn report_emitter_enabled(reason: &'static str, enabled: bool) {+ common_metrics::gauge(+ INGESTION_WARNINGS_EMITTER_ENABLED,+ &[("reason".to_string(), reason.to_string())],+ if enabled { 1.0 } else { 0.0 },+ );+}++fn throttle(settings: &WarningsSettings) -> WarningThrottle {+ WarningThrottle::default()+ .with_max_tracked_keys(settings.max_tracked_scopes)+ .with_type_budget(+ Duration::from_secs(1) / settings.type_budget_per_second.get(),+ settings.type_budget_per_second,+ )+}++pub fn install(settings: &WarningsSettings, handle: Option<lifecycle::Handle>) -> MergeWarnings {+ if !settings.enabled {+ return MergeWarnings::disabled();+ }+ if let Some(reason) = settings.disabled_reason() {+ tracing::warn!(+ reason,+ "ingestion warnings enabled but unusable; emitter disabled"+ );+ report_emitter_enabled(reason, false);+ return MergeWarnings::disabled();+ }+ let Some(handle) = handle else {+ tracing::warn!(+ "ingestion warnings enabled but no lifecycle handle was registered; emitter disabled"+ );+ report_emitter_enabled("no_handle", false);+ return MergeWarnings::disabled();+ };+ let producer = match create_threaded_kafka_producer_no_ping(+ &settings.kafka_config(),+ handle.clone(),+ observe_delivery,+ ) {+ Ok(producer) => producer,+ Err(e) => {+ tracing::error!(error = %e, "failed to create ingestion warnings producer; emitter disabled");+ report_emitter_enabled("producer_create_failed", false);+ return MergeWarnings::disabled();+ }+ };+ if settings.max_tracked_scopes <= DEFAULT_MAX_TRACKED_KEYS {+ tracing::warn!(+ max_tracked_scopes = settings.max_tracked_scopes,+ "ingestion warnings scope cap is at or below the per-token default; a busy pod can fill it within the hour and drop every team's warnings"+ );+ }+ let emitter = Arc::new(KafkaRowWarningEmitter::with_throttle(+ producer,+ settings.topic.clone(),+ throttle(settings),+ ));++ // Liveness comes from the producer's stats callback alone, so a wedged+ // poll thread trips the deadline; a heartbeat here would mask it.+ let background = emitter.clone();+ tokio::spawn(async move {+ let mut sweep = tokio::time::interval(THROTTLE_SWEEP_INTERVAL);+ loop {+ tokio::select! {+ _ = sweep.tick() => background.sweep_throttle(),+ _ = handle.shutdown_recv() => break,+ }+ }+ });++ report_emitter_enabled("ok", true);+ tracing::info!(+ topic = settings.topic.as_str(),+ "ingestion warnings emitter enabled"+ );+ MergeWarnings::new(emitter)+}++#[cfg(test)]+mod tests {+ use std::time::Instant;++ use common_ingestion_warnings::row::throttle_key;+ use common_ingestion_warnings::test_support::CollectingRowEmitter;+ use common_ingestion_warnings::throttle::ThrottleDecision;+ use metrics_util::debugging::{DebugValue, DebuggingRecorder};+ use rstest::rstest;+ use serde_json::Value;++ use super::*;+ use crate::lifecycle::merge::{+ OUTCOME_ATTACHED, OUTCOME_MERGED, OUTCOME_NOOP_SAME_PERSON, OUTCOME_SKIPPED_MOVE_LIMIT,+ };++ const SOURCE_UUID: Uuid = Uuid::from_u128(0x1111_2222_3333_4444_5555_6666_7777_8888);+ const SURVIVOR_UUID: Uuid = Uuid::from_u128(0x9999_aaaa_bbbb_cccc_dddd_eeee_ffff_0000);++ fn pair<'a>() -> MergePair<'a> {+ MergePair {+ source_distinct_id: "anon-1",+ target_distinct_id: "user-1",+ event_uuid: "evt-1",+ source_person_id: Some(42),+ source_person_uuid: Some(SOURCE_UUID),+ survivor_uuid: Some(SURVIVOR_UUID),+ }+ }++ fn details(warning: Warning) -> (WarningType, Value) {+ let warning_type = warning.warning_type();+ let row = warning.into_row(7, MERGE_SAGA);+ (+ warning_type,+ serde_json::from_str(row["details"].as_str().unwrap()).unwrap(),+ )+ }++ #[rstest]+ #[case::illegal(+ OUTCOME_SKIPPED_ILLEGAL,+ Some(WarningType::CannotMergeWithIllegalDistinctId)+ )]+ #[case::already_identified(+ OUTCOME_SKIPPED_ALREADY_IDENTIFIED,+ Some(WarningType::CannotMergeAlreadyIdentified)+ )]+ #[case::settled_conflict(OUTCOME_SKIPPED_CONFLICT, Some(WarningType::MergeRaceCondition))]+ #[case::refused(OUTCOME_SKIPPED_REFUSED, Some(WarningType::MergeSettledFailure))]+ #[case::error(OUTCOME_ERROR, Some(WarningType::MergeSettledFailure))]+ #[case::move_limit(OUTCOME_SKIPPED_MOVE_LIMIT, None)]+ #[case::merged(OUTCOME_MERGED, None)]+ #[case::attached(OUTCOME_ATTACHED, None)]+ #[case::noop(OUTCOME_NOOP_SAME_PERSON, None)]+ #[case::unknown("verdict_from_the_future", None)]+ fn each_settled_verdict_maps_to_its_warning_or_nothing(+ #[case] outcome: &str,+ #[case] expected: Option<WarningType>,+ ) {+ let warning = verdict_warning(outcome, true, &pair());+ assert_eq!(warning.as_ref().map(Warning::warning_type), expected);+ }++ #[rstest]+ #[case(OUTCOME_SKIPPED_CONFLICT)]+ #[case(OUTCOME_SKIPPED_ALREADY_IDENTIFIED)]+ #[case(OUTCOME_SKIPPED_REFUSED)]+ fn an_unsettled_verdict_never_warns(#[case] outcome: &str) {+ assert!(verdict_warning(outcome, false, &pair()).is_none());+ }++ #[test]+ fn already_identified_names_both_persons_and_the_pair() {+ let (warning_type, details) =+ details(verdict_warning(OUTCOME_SKIPPED_ALREADY_IDENTIFIED, true, &pair()).unwrap());+ assert_eq!(warning_type, WarningType::CannotMergeAlreadyIdentified);+ assert_eq!(details["sourcePersonDistinctId"], "anon-1");+ assert_eq!(details["targetPersonDistinctId"], "user-1");+ assert_eq!(details["distinctId"], "user-1");+ assert_eq!(details["eventUuid"], "evt-1");+ assert_eq!(details["otherPersonId"], SOURCE_UUID.to_string());+ assert_eq!(details["personId"], SURVIVOR_UUID.to_string());+ assert_eq!(details["category"], "merge");+ assert_eq!(details["severity"], "warning");+ assert_eq!(details["pipelineStep"], PIPELINE_STEP);+ assert_eq!(details["teamId"], 7);+ }++ #[test]+ fn unresolved_persons_leave_their_keys_out() {+ let unresolved = MergePair {+ source_person_id: None,+ source_person_uuid: None,+ survivor_uuid: None,+ ..pair()+ };+ let (_, details) =+ details(verdict_warning(OUTCOME_SKIPPED_REFUSED, true, &unresolved).unwrap());+ assert!(details.get("otherPersonId").is_none());+ assert!(details.get("personId").is_none());+ assert!(details.get("sourcePersonId").is_none());+ assert_eq!(details["outcome"], OUTCOME_SKIPPED_REFUSED);+ }++ #[test]+ fn a_settled_failure_carries_the_verdict_and_the_source_row_id() {+ let (_, details) = details(verdict_warning(OUTCOME_ERROR, true, &pair()).unwrap());+ assert_eq!(details["outcome"], OUTCOME_ERROR);+ assert_eq!(details["sourcePersonId"], "42");+ assert_eq!(details["otherPersonId"], SOURCE_UUID.to_string());+ assert_eq!(details["severity"], "error");+ }++ #[test]+ fn an_illegal_source_names_itself_and_the_target_as_the_other_side() {+ let (_, details) =+ details(verdict_warning(OUTCOME_SKIPPED_ILLEGAL, true, &pair()).unwrap());+ assert_eq!(details["illegalDistinctId"], "anon-1");+ assert_eq!(details["otherDistinctId"], "user-1");+ assert_eq!(details["distinctId"], "user-1");+ assert_eq!(details["eventUuid"], "evt-1");+ assert!(details.get("sourcePersonDistinctId").is_none());+ }++ #[test]+ fn oversized_ids_are_cut_to_the_column_limit_in_details() {+ let huge = "\u{4e16}".repeat(10_000);+ let oversized = MergePair {+ source_distinct_id: &huge,+ target_distinct_id: &huge,+ event_uuid: &huge,+ ..pair()+ };+ let (_, illegal) =+ details(verdict_warning(OUTCOME_SKIPPED_ILLEGAL, true, &oversized).unwrap());+ for key in [+ "illegalDistinctId",+ "otherDistinctId",+ "distinctId",+ "eventUuid",+ ] {+ assert_eq!(+ illegal[key].as_str().unwrap().chars().count(),+ MAX_DETAIL_ID_CHARS,+ "{key}"+ );+ }+ let (_, failure) = details(verdict_warning(OUTCOME_ERROR, true, &oversized).unwrap());+ assert_eq!(+ failure["sourcePersonDistinctId"]+ .as_str()+ .unwrap()+ .chars()+ .count(),+ MAX_DETAIL_ID_CHARS+ );+ let (_, legal) = details(verdict_warning(OUTCOME_ERROR, true, &pair()).unwrap());+ assert_eq!(legal["sourcePersonDistinctId"], "anon-1");+ }++ #[test]+ fn the_disabled_surface_reports_itself_so_callers_can_skip_the_work() {+ assert!(!MergeWarnings::disabled().is_enabled());+ assert!(MergeWarnings::new(Arc::new(CollectingRowEmitter::new())).is_enabled());+ }++ #[test]+ fn an_illegal_target_swaps_the_sides() {+ let (warning_type, details) = details(illegal_target_warning(&pair()));+ assert_eq!(warning_type, WarningType::CannotMergeWithIllegalDistinctId);+ assert_eq!(details["illegalDistinctId"], "user-1");+ assert_eq!(details["otherDistinctId"], "anon-1");+ assert_eq!(details["distinctId"], "user-1");+ }++ #[test]+ fn the_surface_scopes_each_row_by_the_distinct_id_it_is_about() {+ let emitter = Arc::new(CollectingRowEmitter::new());+ let warnings = MergeWarnings::new(emitter.clone());+ warnings.emit_verdict(7, MERGE_ENTRANCE, OUTCOME_SKIPPED_ILLEGAL, true, &pair());+ warnings.emit_verdict(7, MERGE_SAGA, OUTCOME_MERGED, true, &pair());+ warnings.emit_verdict(7, MERGE_SAGA, OUTCOME_SKIPPED_CONFLICT, false, &pair());+ warnings.emit_illegal_target(7, MERGE_ENTRANCE, &pair());++ let rows = emitter.rows();+ assert_eq!(rows.len(), 2);+ assert!(rows.iter().all(|r| r.team_id == 7));+ assert_eq!(rows[0].source, MERGE_ENTRANCE);+ assert_eq!(rows[0].row["source"], SERVICE);+ assert_eq!(rows[0].scope, "anon-1", "a verdict is about its source");+ assert_eq!(rows[1].details()["illegalDistinctId"], "user-1");+ assert_eq!(+ rows[1].scope, "user-1",+ "an illegal target is about the target"+ );+ }++ fn settings(enabled: bool, hosts: &str, topic: &str) -> WarningsSettings {+ WarningsSettings {+ enabled,+ kafka_hosts: hosts.to_string(),+ kafka_tls: false,+ topic: topic.to_string(),+ kafka_queue_mib: 16,+ kafka_message_max_bytes: 1_048_576,+ kafka_acks: "1".to_string(),+ kafka_retries: 0,+ kafka_linger_ms: 100,+ kafka_queue_messages: 10_000,+ kafka_message_timeout_ms: 5_000,+ type_budget_per_second: DEFAULT_TYPE_BUDGET_PER_SECOND,+ max_tracked_scopes: DEFAULT_MAX_TRACKED_SCOPES,+ }+ }++ #[rstest]+ #[case::off(false, "broker:9092", "topic", Some("disabled"))]+ #[case::no_hosts(true, "", "topic", Some("hosts_unset"))]+ #[case::no_topic(true, "broker:9092", "", Some("topic_unset"))]+ #[case::usable(true, "broker:9092", "topic", None)]+ fn unusable_settings_name_their_reason(+ #[case] enabled: bool,+ #[case] hosts: &str,+ #[case] topic: &str,+ #[case] expected: Option<&'static str>,+ ) {+ assert_eq!(settings(enabled, hosts, topic).disabled_reason(), expected);+ }++ #[test]+ fn the_producer_config_carries_every_setting_and_stays_isolated() {+ let config = WarningsSettings {+ kafka_acks: "all".to_string(),+ kafka_retries: 2,+ kafka_linger_ms: 250,+ kafka_queue_messages: 500,+ kafka_message_timeout_ms: 9_000,+ ..settings(true, "broker:9092", "topic")+ }+ .kafka_config();+ assert_eq!(config.kafka_hosts, "broker:9092");+ assert_eq!(config.kafka_client_id, KAFKA_CLIENT_ID);+ assert_eq!(config.kafka_producer_acks.as_deref(), Some("all"));+ assert_eq!(config.kafka_producer_retries, Some(2));+ assert_eq!(config.kafka_producer_linger_ms, 250);+ assert_eq!(config.kafka_producer_queue_messages, 500);+ assert_eq!(config.kafka_message_timeout_ms, 9_000);+ assert_eq!(config.kafka_producer_queue_mib, 16);+ assert_eq!(config.kafka_producer_message_max_bytes, Some(1_048_576));+ assert!(config.kafka_producer_enable_idempotence.is_none());+ assert!(config.kafka_producer_batch_size.is_none());+ }++ #[rstest]+ #[case::hosts_unset("", "hosts_unset")]+ #[case::no_handle("broker:9092", "no_handle")]+ fn an_unusable_install_reports_its_reason_on_the_gauge(+ #[case] hosts: &str,+ #[case] reason: &str,+ ) {+ let recorder = DebuggingRecorder::new();+ let snapshotter = recorder.snapshotter();+ let warnings = metrics::with_local_recorder(&recorder, || {+ install(&settings(true, hosts, "topic"), None)+ });+ assert!(!warnings.is_enabled());+ let gauges: Vec<(String, f64)> = snapshotter+ .snapshot()+ .into_vec()+ .into_iter()+ .filter(|(key, _, _, _)| key.key().name() == INGESTION_WARNINGS_EMITTER_ENABLED)+ .map(|(key, _, _, value)| {+ let reason = key+ .key()+ .labels()+ .find(|label| label.key() == "reason")+ .expect("reason label")+ .value()+ .to_string();+ let DebugValue::Gauge(value) = value else {+ panic!("emitter enabled is a gauge");+ };+ (reason, value.into_inner())+ })+ .collect();+ assert_eq!(gauges, vec![(reason.to_string(), 0.0)]);+ }++ #[test]+ fn the_throttle_tracks_only_admitted_scopes_and_caps_above_the_shared_default() {+ let throttle = throttle(&settings(true, "broker:9092", "topic"));+ let warning = WarningType::CannotMergeAlreadyIdentified;+ let mut admitted = 0;+ for n in 0..=DEFAULT_MAX_TRACKED_KEYS {+ match throttle.check(&throttle_key(7, &n.to_string()), warning) {+ ThrottleDecision::Emit => admitted += 1,+ ThrottleDecision::TypeBudgetExhausted => {}+ other => panic!("scope {n}: {other:?}"),+ }+ }+ assert!(admitted >= DEFAULT_TYPE_BUDGET_PER_SECOND.get() as usize);+ assert_eq!(+ throttle.tracked_keys(),+ admitted,+ "a scope the budget refused must not hold a key"+ );+ }++ #[test]+ fn the_throttle_takes_its_budget_and_cap_from_settings() {+ let throttle = throttle(&WarningsSettings {+ type_budget_per_second: NonZeroU32::new(2).unwrap(),+ max_tracked_scopes: 3,+ ..settings(true, "broker:9092", "topic")+ });+ let warning = WarningType::CannotMergeAlreadyIdentified;+ assert_eq!(+ throttle.check(&throttle_key(7, "a"), warning),+ ThrottleDecision::Emit+ );+ assert_eq!(+ throttle.check(&throttle_key(7, "b"), warning),+ ThrottleDecision::Emit+ );+ assert_eq!(+ throttle.check(&throttle_key(7, "c"), warning),+ ThrottleDecision::TypeBudgetExhausted+ );+ let later = Instant::now() + Duration::from_millis(600);+ assert_eq!(+ throttle.check_at(&throttle_key(7, "c"), warning, later),+ ThrottleDecision::Emit+ );+ assert_eq!(+ throttle.check(&throttle_key(7, "d"), warning),+ ThrottleDecision::CardinalityCapped+ );+ }++ #[test]+ fn the_type_budget_refills_at_the_stated_rate() {+ let throttle = throttle(&settings(true, "broker:9092", "topic"));+ let warning = WarningType::MergeRaceCondition;+ for n in 0..DEFAULT_TYPE_BUDGET_PER_SECOND.get() {+ assert_eq!(+ throttle.check(&throttle_key(7, &n.to_string()), warning),+ ThrottleDecision::Emit,+ "scope {n}"+ );+ }+ assert_eq!(+ throttle.check(&throttle_key(7, "over"), warning),+ ThrottleDecision::TypeBudgetExhausted+ );+ // A budget that refilled one permit a second would still refuse.+ let later = Instant::now() + Duration::from_millis(100);+ assert_eq!(+ throttle.check_at(&throttle_key(7, "later"), warning, later),+ ThrottleDecision::Emit+ );+ }+}diff --git a/rust/personhog-identity/tests/lifecycle_merge_tests.rs b/rust/personhog-identity/tests/lifecycle_merge_tests.rsindex 0ec01fa8ada7..629a4b24dc79 100644--- a/rust/personhog-identity/tests/lifecycle_merge_tests.rs+++ b/rust/personhog-identity/tests/lifecycle_merge_tests.rs@@ -16,6 +16,8 @@ use std::sync::Arc;use chrono::Utc;use common::sim_leader::{LeaderCall, Rpc, SimLeader, FENCED_METADATA_KEY};use common::{RecordingSink, TestContext};+use common_ingestion_warnings::test_support::{CollectingRowEmitter, EmittedRow};+use common_ingestion_warnings::WarningType;use personhog_common::grpc::semantic_refusal;use personhog_common::persons::{person_uuid, COOKIELESS_SENTINEL_VALUE};use serde_json::json;@@ -34,8 +36,10 @@ use personhog_identity::lifecycle::merge::{OUTCOME_NOOP_SAME_PERSON, OUTCOME_SKIPPED_ALREADY_IDENTIFIED, OUTCOME_SKIPPED_CONFLICT,OUTCOME_SKIPPED_MOVE_LIMIT,};+use personhog_identity::lifecycle::validation::MAX_MERGE_BATCH_SIZE;use personhog_identity::publish::config::MergeEventsAllowlist;use personhog_identity::publish::messages::{DistinctIdRow, PersonMergeEvent};+use personhog_identity::warnings::{MergeWarnings, MERGE_ENTRANCE, MERGE_SAGA};use personhog_proto::personhog::types::v1::LifecycleOpType;struct MergeHarness {@@ -44,6 +48,7 @@ struct MergeHarness {leader: Arc<SimLeader>,driver: MergeDriver,drives: DetachedDrives,+ warnings: Arc<CollectingRowEmitter>,}impl MergeHarness {@@ -67,21 +72,52 @@ impl MergeHarness {let ctx = TestContext::new_with_tables(tables).await;let engine = ctx.engine();let leader = Arc::new(SimLeader::new(ctx.pool.clone(), ctx.tables.clone()));+ let warnings = Arc::new(CollectingRowEmitter::new());let driver = MergeDriver::new(leader.clone(),ctx.tables.clone(),common::FAN_OUT_CONCURRENCY,outbox_writes,- );+ )+ .with_warnings(MergeWarnings::new(warnings.clone()));Self {ctx,engine,leader,driver,drives: DetachedDrives::new(common::FAN_OUT_CONCURRENCY),+ warnings,}}+ fn merge_warnings(&self) -> MergeWarnings {+ MergeWarnings::new(self.warnings.clone())+ }++ /// Every warning emitted so far as `(type, scope)`, in emission order.+ fn warned(&self) -> Vec<(WarningType, String)> {+ self.warnings+ .rows()+ .into_iter()+ .map(|row| (row.warning, row.scope))+ .collect()+ }++ fn warning_rows(&self) -> Vec<EmittedRow> {+ self.warnings.rows()+ }++ async fn person_uuid_of(&self, person_id: i64) -> Uuid {+ sqlx::query_scalar(&format!(+ "SELECT uuid FROM {} WHERE id = $1",+ self.ctx.tables.person+ ))+ .bind(person_id)+ .fetch_one(&self.ctx.pool)+ .await+ .expect("person exists")+ }+async fn execute(&self,op_id: Uuid,@@ -1171,7 +1207,9 @@ async fn a_stale_drivers_fold_refusal_defers_instead_of_unfencing_the_new_owners}/// An abandoned merge op is driven through `sweep()`/`resume()` to a-/// merged outcome, while a parked op sitting next to it is skipped.+/// merged outcome, a second one whose source the leader holds identified+/// is driven to an abort that still warns, while a parked op sitting next+/// to them is skipped.////// Isolation: this is the suite's single sweep call (see the engine/// tests' header). Its one-hour lease keeps concurrent tests' fresh@@ -1187,11 +1225,25 @@ async fn the_sweeper_drives_an_abandoned_merge_to_completion() {let op_id = Uuid::now_v7();let request = merge_request("sweep-target", &["sweep-source"]);h.create(op_id, &request).await;- sqlx::query("UPDATE lifecycle_op SET created_at = now() - interval '2 hours' WHERE op_id = $1")- .bind(op_id)- .execute(&h.ctx.pool)- .await- .expect("backdate the abandoned op");+ let warn_source = h+ .ctx+ .insert_person_with_distinct_id("sweep-warn-source")+ .await;+ h.ctx+ .insert_person_with_distinct_id("sweep-warn-target")+ .await;+ h.leader.set_sealed_identified(warn_source, true);+ let warn_op_id = Uuid::now_v7();+ let warn_request = merge_request("sweep-warn-target", &["sweep-warn-source"]);+ h.create(warn_op_id, &warn_request).await;+ sqlx::query(+ "UPDATE lifecycle_op SET created_at = now() - interval '2 hours' WHERE op_id = ANY($1)",+ )+ .bind(vec![op_id, warn_op_id])+ .execute(&h.ctx.pool)+ .await+ .expect("backdate the abandoned ops");+ assert!(h.warned().is_empty(), "creation alone warns nothing");// A parked op that would otherwise be prime sweeper bait (expired// lease): a definitive leader refusal means automatic retry cannot@@ -1222,7 +1274,7 @@ async fn the_sweeper_drives_an_abandoned_merge_to_completion() {h.ctx.tables.clone(),);let resumed = sweep_engine.sweep(&[&h.driver]).await.expect("sweep runs");- assert!(resumed >= 1, "the abandoned merge was resumed");+ assert!(resumed >= 2, "both abandoned merges were resumed");let (step, completed) = op_row_state(&h.ctx.pool, op_id).await;assert_eq!(step, STEP_COMPLETED);@@ -1262,6 +1314,29 @@ async fn the_sweeper_drives_an_abandoned_merge_to_completion() {assert!(!completed);assert!(parked_state(&h.ctx.pool, parked_op_id).await.0);+ let (step, _) = op_row_state(&h.ctx.pool, warn_op_id).await;+ assert_eq!(step, STEP_ABORTED);+ // The sweep's scan is global, so only rows for this test's team count.+ let rows: Vec<EmittedRow> = h+ .warning_rows()+ .into_iter()+ .filter(|row| row.team_id == h.ctx.team_id)+ .collect();+ assert_eq!(+ rows.iter()+ .map(|row| (row.warning, row.scope.clone()))+ .collect::<Vec<_>>(),+ vec![(+ WarningType::CannotMergeAlreadyIdentified,+ "sweep-warn-source".to_string()+ )]+ );+ assert_eq!(rows[0].source, MERGE_SAGA);+ assert_eq!(+ rows[0].details()["eventUuid"],+ warn_request.sources[0].event_uuid+ );+h.ctx.cleanup().await.expect("cleanup");}@@ -1354,6 +1429,23 @@ async fn a_leader_refusal_at_fence_aborts_instead_of_parking() {.expect("the fenced sibling unfroze");assert!(h.leader.death_documents().is_empty());+ assert_eq!(+ h.warned(),+ vec![+ (WarningType::MergeSettledFailure, "sabort-a".to_string()),+ (WarningType::MergeSettledFailure, "sabort-b".to_string()),+ ]+ );+ for row in h.warning_rows() {+ assert_eq!(row.source, MERGE_SAGA);+ assert_eq!(row.details()["outcome"], "skipped_refused");+ assert_eq!(row.details()["targetPersonDistinctId"], "sabort-target");+ }+ h.execute(op_id, &request)+ .await+ .expect("the retry replays the recorded abort");+ assert_eq!(h.warned().len(), 2);+h.ctx.cleanup().await.expect("cleanup");}@@ -1419,6 +1511,17 @@ async fn claim_classification_settles_each_source_without_touching_it() {assert!(mergeable_deleted);assert_eq!(h.pdi_state("cls-mergeable").await.0, target);+ assert_eq!(+ h.warned(),+ vec![+ (WarningType::MergeRaceCondition, "cls-missing".to_string()),+ (+ WarningType::CannotMergeAlreadyIdentified,+ "cls-identified".to_string()+ ),+ ]+ );+h.ctx.cleanup().await.expect("cleanup");}@@ -1427,11 +1530,19 @@ async fn a_target_held_by_another_op_aborts_before_mutating_anything() {let h = MergeHarness::new().await;let target = h.ctx.insert_person_with_distinct_id("held-target").await;let source = h.ctx.insert_person_with_distinct_id("held-source").await;+ let identified = h+ .ctx+ .insert_person_with_distinct_id("held-identified")+ .await;+ h.set_person(identified, "{}", 0, true).await;let foreign_op = h.foreign_mark(target).await;let op_id = Uuid::now_v7();let outcome = h- .execute(op_id, &merge_request("held-target", &["held-source"]))+ .execute(+ op_id,+ &merge_request("held-target", &["held-source", "held-identified"]),+ ).await.expect("op reaches a terminal step");@@ -1439,23 +1550,42 @@ async fn a_target_held_by_another_op_aborts_before_mutating_anything() {assert!(outcome.survivor.is_none());assert_eq!(result_map(&outcome),- HashMap::from([(- "held-source".to_string(),- OUTCOME_SKIPPED_CONFLICT.to_string()- )])+ HashMap::from([+ (+ "held-source".to_string(),+ OUTCOME_SKIPPED_CONFLICT.to_string()+ ),+ (+ "held-identified".to_string(),+ OUTCOME_SKIPPED_ALREADY_IDENTIFIED.to_string()+ ),+ ]));let (step, _) = op_row_state(&h.ctx.pool, op_id).await;assert_eq!(step, STEP_ABORTED);- // The world is unchanged: both persons live, ids in place, the foreign+ // The world is unchanged: every person lives, ids in place, the foreign// op's mark untouched, no leader call ever made.- for (person, did) in [(target, "held-target"), (source, "held-source")] {+ for (person, did) in [+ (target, "held-target"),+ (source, "held-source"),+ (identified, "held-identified"),+ ] {let (is_deleted, _, _) = h.person_state(person).await;assert!(!is_deleted);assert_eq!(h.pdi_state(did).await.0, person);}assert_eq!(h.op_person_status(foreign_op, target).await, "marked");assert!(h.leader.calls().is_empty());+ // The conflict is unsettled (a retry may win the target), but the+ // identified verdict is final and warns even though the op aborted.+ assert_eq!(+ h.warned(),+ vec![(+ WarningType::CannotMergeAlreadyIdentified,+ "held-identified".to_string()+ )]+ );h.ctx.cleanup().await.expect("cleanup");}@@ -1494,6 +1624,21 @@ async fn a_source_held_by_another_op_is_skipped_while_the_rest_merge() {assert_eq!(h.pdi_state("part-held").await.0, held);assert_eq!(h.pdi_state("part-free").await.0, target);+ let rows = h.warning_rows();+ assert_eq!(+ h.warned(),+ vec![(WarningType::MergeRaceCondition, "part-held".to_string())]+ );+ let details = rows[0].details();+ assert_eq!(+ details["personId"],+ h.person_uuid_of(target).await.to_string()+ );+ assert_eq!(+ details["otherPersonId"],+ h.person_uuid_of(held).await.to_string()+ );+h.ctx.cleanup().await.expect("cleanup");}@@ -1593,6 +1738,24 @@ async fn an_identified_source_detected_at_seal_time_drops_with_a_released_fence(assert!(!target_deleted);assert_eq!(h.pdi_state("seal-source").await.0, source);+ let rows = h.warning_rows();+ assert_eq!(+ h.warned(),+ vec![(+ WarningType::CannotMergeAlreadyIdentified,+ "seal-source".to_string()+ )]+ );+ assert_eq!(rows[0].source, MERGE_SAGA);+ let details = rows[0].details();+ assert_eq!(details["sourcePersonDistinctId"], "seal-source");+ assert_eq!(details["targetPersonDistinctId"], "seal-target");+ assert_eq!(+ details["otherPersonId"],+ h.person_uuid_of(source).await.to_string()+ );+ assert!(details.get("personId").is_none());+h.ctx.cleanup().await.expect("cleanup");}@@ -1809,10 +1972,12 @@ impl MergeHarness {self.ctx.tables.clone(),common::FAN_OUT_CONCURRENCY,OutboxWrites::Disabled,- ),+ )+ .with_warnings(self.merge_warnings()),self.drives.clone(),),- ),+ )+ .with_warnings(self.merge_warnings()),common::FAN_OUT_CONCURRENCY,)}@@ -1838,10 +2003,12 @@ impl MergeHarness {self.ctx.tables.clone(),common::FAN_OUT_CONCURRENCY,OutboxWrites::Disabled,- ),+ )+ .with_warnings(self.merge_warnings()),self.drives.clone(),),- ),+ )+ .with_warnings(self.merge_warnings()),common::FAN_OUT_CONCURRENCY,)}@@ -2103,6 +2270,7 @@ async fn the_rpc_runs_the_saga_and_a_retry_returns_the_recorded_answer() {calls_after_first,"a retry of a finished op re-runs nothing");+ assert!(h.warned().is_empty());h.ctx.cleanup().await.expect("cleanup");}@@ -2331,6 +2499,21 @@ async fn inline_cases_settle_without_an_op_row_and_push_the_event_properties() {assert_eq!(h.pdi_state("inline-unresolved").await, (target, false, 1));let survivor = response.survivor.expect("survivor present");assert_eq!(survivor.id, target);+ let rows = h.warning_rows();+ assert_eq!(+ h.warned(),+ vec![(+ WarningType::CannotMergeWithIllegalDistinctId,+ "anonymous".to_string()+ )]+ );+ assert_eq!(rows[0].source, MERGE_ENTRANCE);+ assert_eq!(rows[0].team_id, h.ctx.team_id);+ let details = rows[0].details();+ assert_eq!(details["illegalDistinctId"], "anonymous");+ assert_eq!(details["otherDistinctId"], "inline-target");+ assert_eq!(details["distinctId"], "inline-target");+ assert_eq!(details["eventUuid"], request.sources[1].event_uuid);// The survivor's created_at unit must not depend on which branch// produced it: the leader already answers epoch millis, so the// response must pass it through unscaled.@@ -2515,7 +2698,7 @@ async fn invalid_merge_requests_are_rejected_before_any_work() {let cases: Vec<(&str, MergePersonsRequest, Code)> = vec![("zero team",- rpc_request(0, "t", &["s"], op),+ rpc_request(0, "anonymous", &["s"], op),Code::InvalidArgument,),(@@ -2588,6 +2771,21 @@ async fn invalid_merge_requests_are_rejected_before_any_work() {rpc_request(team_id, "t", &["nul\u{0000}source"], op),Code::InvalidArgument,),+ (+ "illegal target with two sources",+ rpc_request(team_id, "anonymous", &["s1", "s2"], op),+ Code::InvalidArgument,+ ),+ (+ "illegal target with an over-cap batch",+ rpc_request(+ team_id,+ "anonymous",+ &vec!["s"; MAX_MERGE_BATCH_SIZE + 1],+ op,+ ),+ Code::InvalidArgument,+ ),];for (label, request, expected) in cases {let status = service@@ -2598,6 +2796,32 @@ async fn invalid_merge_requests_are_rejected_before_any_work() {}assert!(h.leader.calls().is_empty());+ let illegal_pairs: Vec<(String, String)> = h+ .warning_rows()+ .into_iter()+ .map(|row| {+ assert_eq!(row.warning, WarningType::CannotMergeWithIllegalDistinctId);+ assert_eq!(row.source, MERGE_ENTRANCE);+ let details = row.details();+ (+ details["illegalDistinctId"].as_str().unwrap().to_string(),+ details["otherDistinctId"].as_str().unwrap().to_string(),+ )+ })+ .collect();+ assert_eq!(+ illegal_pairs,+ vec![+ ("anonymous".to_string(), "s".to_string()),+ ("x".repeat(400), "s".to_string()),+ ("nul\u{0000}target".to_string(), "s".to_string()),+ ("nul\u{0000}source".to_string(), "t".to_string()),+ ("anonymous".to_string(), "s1".to_string()),+ ("anonymous".to_string(), "s".to_string()),+ ],+ "an illegal target warns once, whatever the batch size"+ );+h.ctx.cleanup().await.expect("cleanup");}@@ -3278,6 +3502,10 @@ async fn a_move_limited_source_skips_while_the_rest_merge_through_the_rpc() {assert!(small_deleted);let (big_deleted, _, _) = h.person_state(big).await;assert!(!big_deleted, "a move-limited source must stay untouched");+ assert!(+ h.warned().is_empty(),+ "the caller's merge-mode policy decides whether a limit skip is a drop"+ );h.ctx.cleanup().await.expect("cleanup");}@@ -3340,6 +3568,25 @@ async fn an_identified_source_settles_inline_and_still_delivers_the_events_write.await.expect("count op rows");assert_eq!(op_rows, 0);+ let rows = h.warning_rows();+ assert_eq!(+ h.warned(),+ vec![(+ WarningType::CannotMergeAlreadyIdentified,+ "rpc-ident-source".to_string()+ )]+ );+ assert_eq!(rows[0].source, MERGE_ENTRANCE);+ let details = rows[0].details();+ assert_eq!(details["eventUuid"], request.sources[0].event_uuid);+ assert_eq!(+ details["personId"],+ h.person_uuid_of(target).await.to_string()+ );+ assert_eq!(+ details["otherPersonId"],+ h.person_uuid_of(source).await.to_string()+ );// Nothing is recorded, so a retry re-classifies and delivers again:// the same at-least-once semantics as every other inline answer.@@ -3357,6 +3604,7 @@ async fn an_identified_source_settles_inline_and_still_delivers_the_events_write)]);assert_eq!(h.leader.calls().len(), 2);+ assert_eq!(h.warned().len(), 2, "re-classification warns again");h.ctx.cleanup().await.expect("cleanup");}@@ -3778,9 +4026,16 @@ async fn an_oversized_source_settles_per_source_instead_of_failing_the_request()assert_eq!(rpc_outcomes(&response),- vec![(oversized, MergeSourceOutcome::SkippedIllegal)]+ vec![(oversized.clone(), MergeSourceOutcome::SkippedIllegal)]);assert_eq!(response.survivor.expect("survivor").id, target);+ assert_eq!(+ h.warned(),+ vec![(WarningType::CannotMergeWithIllegalDistinctId, oversized)]+ );+ let details = h.warning_rows()[0].details();+ assert_eq!(details["illegalDistinctId"].as_str().unwrap().len(), 400);+ assert_eq!(details["otherDistinctId"], "oversize-target");h.ctx.cleanup().await.expect("cleanup");}@@ -4058,3 +4313,37 @@ async fn merge_events_are_one_per_merged_person_and_gated_by_the_team_allowlist(h.ctx.cleanup().await.expect("cleanup");}++#[tokio::test]+async fn an_inline_conflict_warns_when_the_op_that_settles_it_completes() {+ let h = MergeHarness::new().await;+ h.ctx.insert_person_with_distinct_id("inline-target").await;+ h.ctx.insert_person_with_distinct_id("inline-source").await;+ let mut frozen =+ serde_json::to_value(merge_request("inline-target", &["inline-source"])).unwrap();+ frozen["original"] = json!({"call": "settled"});+ frozen["inline_results"] = json!({ "inline-held": OUTCOME_SKIPPED_CONFLICT });+ h.engine+ .execute(&h.driver, Uuid::now_v7(), h.ctx.team_id, &frozen)+ .await+ .expect("merge completes");++ assert_eq!(+ h.warned(),+ vec![(WarningType::MergeRaceCondition, "inline-held".to_string())]+ );+ assert_eq!(h.warning_rows()[0].source, MERGE_SAGA);++ // A claim abort settles nothing: the retry re-classifies the conflict.+ let mut aborted =+ serde_json::to_value(merge_request("inline-no-target", &["inline-no-source"])).unwrap();+ aborted["original"] = json!({"call": "aborted"});+ aborted["inline_results"] = json!({ "inline-held-again": OUTCOME_SKIPPED_CONFLICT });+ h.engine+ .execute(&h.driver, Uuid::now_v7(), h.ctx.team_id, &aborted)+ .await+ .expect("claim abort is terminal");+ assert_eq!(h.warned().len(), 1);++ h.ctx.cleanup().await.expect("cleanup");+}