: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): admit person writes against the writer's full rejection surface (#72741)
Zach Brown9423e20417d6
diff --git a/rust/Cargo.lock b/rust/Cargo.lockindex e3f08c0bfbcf..56e91ee66687 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -7675,6 +7675,7 @@ dependencies = ["metrics","pin-project","rstest",+ "serde_json","sqlx","tokio","tonic 0.12.3",@@ -7716,6 +7717,7 @@ dependencies = ["chrono","common-alloc","common-database",+ "common-ingestion-warnings","common-kafka","common-metrics","dashmap 6.1.0",@@ -7864,6 +7866,7 @@ dependencies = ["health","lifecycle","metrics",+ "personhog-common","personhog-proto","prost 0.13.5","rdkafka",diff --git a/rust/personhog-common/Cargo.toml b/rust/personhog-common/Cargo.tomlindex 3e4df45081ed..6aa874aedfd1 100644--- a/rust/personhog-common/Cargo.toml+++ b/rust/personhog-common/Cargo.toml@@ -12,6 +12,7 @@ http = { workspace = true }http-body = { workspace = true }http-body-util = { workspace = true }metrics = { workspace = true }+serde_json = { workspace = true }pin-project = "1.1"sqlx = { workspace = true }tokio = { workspace = true }diff --git a/rust/personhog-common/src/lib.rs b/rust/personhog-common/src/lib.rsindex 26ddf8c4e9c7..adb0ff7a9758 100644--- a/rust/personhog-common/src/lib.rs+++ b/rust/personhog-common/src/lib.rs@@ -2,5 +2,6 @@ pub mod async_gzip;pub mod grpc;pub mod partitioning;mod pool_monitor;+pub mod properties;pub use pool_monitor::{spawn_pool_monitor, MonitoredPool};diff --git a/rust/personhog-common/src/properties.rs b/rust/personhog-common/src/properties.rsnew file mode 100644index 000000000000..83debe11f248--- /dev/null+++ b/rust/personhog-common/src/properties.rs@@ -0,0 +1,693 @@+//! Person-property size enforcement, shared by the leader (admission-time+//! trimming and rejection) and anything that needs to reason about the+//! Postgres row the writer will eventually produce.+//!+//! The authority on "too big" is the `check_properties_size` constraint on+//! `posthog_person`: `pg_column_size(properties) <= 655360`. That measures+//! the JSONB *binary encoding*, not the raw JSON text — per-element entry+//! headers, PG's base-10000 numeric format, and alignment padding all+//! count. `jsonb_column_size` reproduces that number exactly so admission+//! enforces the real constraint rather than a proxy with a hoped-for+//! margin; a property test compares it against a live Postgres+//! (`pg_column_size($1::jsonb)`) so any drift from PG's encoding fails+//! loudly. The JSONB on-disk format is stable across PG versions by+//! design (pg_upgrade compatibility), which is what makes reimplementing+//! it sound.++use std::collections::HashSet;+use std::sync::LazyLock;++use serde_json::Value;++/// Properties that must never be trimmed, matching the Node.js ingestion+/// pipeline's `ALL_PROTECTED_PROPERTIES` in `person-property-utils.ts`.+static PROTECTED_PROPERTIES: LazyLock<HashSet<&'static str>> = LazyLock::new(|| {+ HashSet::from([+ // Core person properties+ "email",+ "name",+ // Event-to-person properties (mobile)+ "$app_build",+ "$app_name",+ "$app_namespace",+ "$app_version",+ // Event-to-person properties (web)+ "$browser",+ "$browser_version",+ "$device_type",+ "$current_url",+ "$pathname",+ "$os",+ "$os_name",+ "$os_version",+ "$referring_domain",+ "$referrer",+ "$screen_height",+ "$screen_width",+ "$viewport_height",+ "$viewport_width",+ "$raw_user_agent",+ // UTM and campaign tracking+ "utm_source",+ "utm_medium",+ "utm_campaign",+ "utm_content",+ "utm_name",+ "utm_term",+ "gclid",+ "gad_source",+ "gclsrc",+ "dclid",+ "gbraid",+ "wbraid",+ "fbclid",+ "msclkid",+ "twclid",+ "li_fat_id",+ "mc_cid",+ "igshid",+ "ttclid",+ "rdt_cid",+ "irclid",+ "_kx",+ "epik",+ "qclid",+ "sccid",+ // Session and page tracking+ "$session_id",+ "$window_id",+ "$pageview_id",+ "$host",+ // Identity and device tracking+ "$user_id",+ "$device_id",+ "$anon_distinct_id",+ // Initial/first-touch properties+ "$initial_referrer",+ "$initial_referring_domain",+ "$initial_utm_source",+ "$initial_utm_medium",+ "$initial_utm_campaign",+ "$initial_utm_content",+ "$initial_utm_term",+ ])+});++/// Returns true if the property can be trimmed (is not protected).+pub fn can_trim_property(name: &str) -> bool {+ !PROTECTED_PROPERTIES.contains(name)+}++/// Floats at or above this magnitude are clamped by [`sanitize_for_jsonb`].+/// Postgres renders jsonb numerics in expanded decimal notation (never+/// e-notation), and serde_json's parser overflows on integer expansions of+/// ~1e308 and beyond — so a number in the window [1e308, f64::MAX] applies+/// to PG but can never be read back by a Rust consumer (including the+/// leader's own PG fallback load). 1e307 expands to 308 digits, which+/// parses back exactly.+pub const MAX_JSONB_SAFE_MAGNITUDE: f64 = 1e307;++/// What [`sanitize_for_jsonb`] rewrote, for the caller's counters.+#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]+pub struct SanitizeStats {+ /// Strings (keys or values) that contained `\u{0000}`.+ pub nul_strings: u64,+ /// Floats clamped to ±[`MAX_JSONB_SAFE_MAGNITUDE`].+ pub clamped_numbers: u64,+}++impl SanitizeStats {+ pub fn changed(&self) -> bool {+ self.nul_strings > 0 || self.clamped_numbers > 0+ }+}++/// Rewrite the merged state so that it both applies to Postgres jsonb and+/// round-trips back out of it, at any depth:+///+/// * `\u{0000}` (NUL) becomes `\u{FFFD}` in every string — keys and+/// values — mirroring the Node.js pipeline's `sanitizeJsonbValue`;+/// Postgres refuses NUL outright. A sanitized key can collide with an+/// existing key; the later entry wins, matching what Postgres itself+/// does when parsing JSON text with duplicate keys.+/// * Floats beyond ±[`MAX_JSONB_SAFE_MAGNITUDE`] are clamped to it, so+/// Postgres's expanded numeric rendering stays parseable on the way+/// back (see the constant's doc).+pub fn sanitize_for_jsonb(value: &mut Value) -> SanitizeStats {+ let mut stats = SanitizeStats::default();+ sanitize_value(value, &mut stats);+ stats+}++fn sanitize_value(value: &mut Value, stats: &mut SanitizeStats) {+ match value {+ Value::String(s) => {+ if s.contains('\u{0000}') {+ *s = s.replace('\u{0000}', "\u{FFFD}");+ stats.nul_strings += 1;+ }+ }+ Value::Number(n) => {+ // Only floats can exceed the safe magnitude: i64/u64 top out+ // around 1.8e19.+ if let Some(f) = n.as_f64() {+ if n.is_f64() && f.abs() > MAX_JSONB_SAFE_MAGNITUDE {+ let clamped = MAX_JSONB_SAFE_MAGNITUDE.copysign(f);+ *value = Value::from(clamped);+ stats.clamped_numbers += 1;+ }+ }+ }+ Value::Array(items) => {+ for item in items {+ sanitize_value(item, stats);+ }+ }+ Value::Object(map) => {+ if map.keys().any(|k| k.contains('\u{0000}')) {+ let entries: Vec<(String, Value)> = std::mem::take(map).into_iter().collect();+ for (key, mut val) in entries {+ sanitize_value(&mut val, stats);+ let key = if key.contains('\u{0000}') {+ stats.nul_strings += 1;+ key.replace('\u{0000}', "\u{FFFD}")+ } else {+ key+ };+ map.insert(key, val);+ }+ } else {+ for val in map.values_mut() {+ sanitize_value(val, stats);+ }+ }+ }+ _ => {}+ }+}++/// Rewrite number tokens that serde_json refuses so the document parses,+/// mimicking `JSON.parse`'s rounding. Postgres renders jsonb numerics in+/// expanded decimal (never e-notation), and serde_json rejects expansions+/// near `f64::MAX` even when the value itself is representable — while+/// every JS consumer reads the same bytes fine, because `JSON.parse`+/// rounds to the nearest double instead of erroring. Legacy and+/// Node-written rows can therefore hold numerics the leader's strict+/// parser chokes on.+///+/// Tokens serde_json accepts are copied verbatim (no precision change);+/// rejected tokens whose value fits a double are rewritten to its+/// shortest representation — the exact value `JSON.parse` yields — and+/// magnitudes beyond `f64::MAX` (unreachable from JS; Python bigints and+/// raw SQL) are clamped to ±[`MAX_JSONB_SAFE_MAGNITUDE`], where today's+/// pipeline reads `Infinity` and rewrites it as `null`. String content is+/// copied verbatim, so digits inside strings are never touched. Intended+/// for the rare failure path only: callers parse normally first and+/// rewrite only when that fails.+pub fn rewrite_out_of_range_numbers(text: &str) -> String {+ let bytes = text.as_bytes();+ let mut out = String::with_capacity(text.len());+ let mut i = 0;+ while i < bytes.len() {+ match bytes[i] {+ b'"' => {+ // Copy the whole string token verbatim, escape-aware.+ let start = i;+ i += 1;+ while i < bytes.len() {+ match bytes[i] {+ b'\\' => i = (i + 2).min(bytes.len()),+ b'"' => {+ i += 1;+ break;+ }+ _ => i += 1,+ }+ }+ out.push_str(&text[start..i]);+ }+ b'-' | b'0'..=b'9' => {+ let start = i;+ while i < bytes.len()+ && matches!(bytes[i], b'0'..=b'9' | b'.' | b'e' | b'E' | b'+' | b'-')+ {+ i += 1;+ }+ let token = &text[start..i];+ if token.parse::<serde_json::Number>().is_ok() {+ out.push_str(token);+ } else {+ match token.parse::<f64>() {+ // std's parser rounds to nearest like JSON.parse,+ // so a finite result is the double JS reads.+ Ok(f) if f.is_finite() => out.push_str(+ &serde_json::Number::from_f64(f)+ .expect("finite float converts")+ .to_string(),+ ),+ _ => {+ let sign = if token.starts_with('-') { "-" } else { "" };+ out.push_str(&format!("{sign}{MAX_JSONB_SAFE_MAGNITUDE:e}"));+ }+ }+ }+ }+ _ => {+ // Structural bytes and whitespace; non-ASCII only occurs+ // inside strings, which the arm above copies as slices.+ let start = i;+ while i < bytes.len() && !matches!(bytes[i], b'"' | b'-' | b'0'..=b'9') {+ i += 1;+ }+ out.push_str(&text[start..i]);+ }+ }+ }+ out+}++/// The size Postgres will report for this value as a `jsonb` column —+/// `pg_column_size(value::jsonb)` — computed without touching Postgres.+pub fn jsonb_column_size(value: &Value) -> usize {+ // 4-byte varlena header, then the root container. Scalars at the root+ // are wrapped in a one-element pseudo-array container.+ let mut offset = 4usize;+ offset = match value {+ Value::Object(_) | Value::Array(_) => container_size(value, offset),+ scalar => scalar_container_size(scalar, offset),+ };+ offset+}++/// A root-level scalar is stored as a one-element array container with the+/// scalar flag; the layout matches a one-element array.+fn scalar_container_size(scalar: &Value, offset: usize) -> usize {+ // Container header + one JEntry.+ let mut offset = offset + 4 + 4;+ offset += element_size(scalar, offset);+ offset+}++/// Size contribution of a container (object or array) starting at+/// `offset` bytes from the start of the varlena datum. Returns the offset+/// just past the container. `offset` matters because numerics and nested+/// containers are padded to 4-byte alignment relative to the datum start.+fn container_size(value: &Value, offset: usize) -> usize {+ match value {+ Value::Object(map) => {+ // Header + one JEntry per key and per value, then all key+ // bytes, then all values. Keys are processed in PG's storage+ // order (length, then bytewise) because alignment padding for+ // numeric/container values depends on the running offset.+ let mut offset = offset + 4 + 8 * map.len();+ let mut keys: Vec<&String> = map.keys().collect();+ keys.sort_by(|a, b| {+ a.len()+ .cmp(&b.len())+ .then_with(|| a.as_bytes().cmp(b.as_bytes()))+ });+ for key in &keys {+ offset += key.len();+ }+ for key in &keys {+ offset += element_size(&map[key.as_str()], offset);+ }+ offset+ }+ Value::Array(items) => {+ let mut offset = offset + 4 + 4 * items.len();+ for item in items {+ offset += element_size(item, offset);+ }+ offset+ }+ _ => unreachable!("container_size only called for objects and arrays"),+ }+}++/// Data-section size of one element whose data begins at `offset` from+/// the datum start (its JEntry is accounted for by the parent container).+fn element_size(value: &Value, offset: usize) -> usize {+ match value {+ Value::Null | Value::Bool(_) => 0,+ Value::String(s) => s.len(),+ Value::Number(n) => {+ // Numerics are stored as a full numeric datum, padded to+ // 4-byte alignment from the datum start.+ let padding = (4 - offset % 4) % 4;+ padding + numeric_datum_size(&n.to_string())+ }+ Value::Object(_) | Value::Array(_) => {+ let padding = (4 - offset % 4) % 4;+ padding + (container_size(value, offset + padding) - (offset + padding))+ }+ }+}++/// The size of the numeric datum PG builds from this JSON number literal:+/// 4-byte varlena header, a 2-byte short (or 4-byte long) numeric header,+/// and two bytes per base-10000 digit group, mirroring `numeric_in`.+fn numeric_datum_size(literal: &str) -> usize {+ let (weight, groups, dscale) = parse_numeric(literal);+ let header = if short_header_fits(weight, dscale) {+ 2+ } else {+ 4+ };+ 4 + header + 2 * groups+}++/// PG's short numeric header packs the sign, a 6-bit display scale, and a+/// 7-bit signed weight; it fits when dscale <= 63 and weight is in+/// [-64, 63] base-10000 units (NUMERIC_SHORT_WEIGHT_MIN/MAX in numeric.c).+fn short_header_fits(weight: i32, dscale: u32) -> bool {+ dscale <= 0x3F && (-64..=63).contains(&weight)+}++/// Parse a JSON number literal the way `numeric_in` does, returning the+/// base-10000 weight, the count of stored base-10000 digit groups (with+/// zero groups stripped from both ends, as PG does), and the display+/// scale (count of decimal fraction digits after expanding any exponent).+fn parse_numeric(literal: &str) -> (i32, usize, u32) {+ let s = literal.strip_prefix('-').unwrap_or(literal);+ let (mantissa, exponent) = match s.find(['e', 'E']) {+ Some(pos) => (&s[..pos], s[pos + 1..].parse::<i64>().unwrap_or(0)),+ None => (s, 0),+ };+ let (int_part, frac_part) = match mantissa.find('.') {+ Some(pos) => (&mantissa[..pos], &mantissa[pos + 1..]),+ None => (mantissa, ""),+ };++ // Expand the exponent into a plain decimal digit string with a point+ // position. `digits` is the full significand; `point` is how many of+ // those digits sit before the decimal point (may be <= 0).+ let mut digits: Vec<u8> = int_part.bytes().chain(frac_part.bytes()).collect();+ let mut point = int_part.len() as i64 + exponent;++ // Strip leading zeros (they only shift the logical point position+ // bookkeeping below, which works on the trimmed significand).+ let leading = digits.iter().take_while(|&&b| b == b'0').count();+ digits.drain(..leading);+ point -= leading as i64;+ // dscale is the number of decimal fraction digits PG displays: digits+ // after the point, floored at zero, including trailing zeros as+ // written.+ let dscale = (digits.len() as i64 - point).max(0) as u32;+ // Trailing zeros do not become stored digits (PG strips zero groups),+ // but they already counted toward dscale above.+ while digits.last() == Some(&b'0') {+ digits.pop();+ }++ if digits.is_empty() {+ // Zero: no digit groups; weight 0.+ return (0, 0, dscale);+ }++ // Group into base-10000 digits aligned to the decimal point: the+ // first group holds ((point - 1) mod 4) + 1 leading decimal digits.+ let first_group_len = (((point - 1).rem_euclid(4)) + 1) as usize;+ let weight = ((point - first_group_len as i64) / 4) as i32;+ let mut groups = 0usize;+ let mut index = 0usize;+ let mut group_len = first_group_len.min(digits.len());+ let mut leading_zero_groups = 0usize;+ let mut seen_nonzero = false;+ while index < digits.len() {+ let group = &digits[index..(index + group_len).min(digits.len())];+ let is_zero = group.iter().all(|&b| b == b'0');+ if is_zero && !seen_nonzero {+ leading_zero_groups += 1;+ } else {+ seen_nonzero = true;+ }+ groups += 1;+ index += group_len;+ group_len = 4;+ }+ // Strip leading zero groups (weight shrinks with them) and trailing+ // zero groups (partially-filled last groups pad with zeros, and fully+ // zero tails are not stored).+ let weight = weight - leading_zero_groups as i32;+ groups -= leading_zero_groups;+ // Trailing zero groups: recompute by walking backwards over the+ // grouped digits. A trailing group is zero only if every digit in it+ // is zero; digits had trailing zeros stripped already, so only a+ // group that lies entirely past the last stored digit is zero — which+ // cannot happen after the strip. Nothing further to remove.+ (weight, groups, dscale)+}++/// Trim person properties under `target_bytes` (measured as+/// `jsonb_column_size`, the constraint's own metric) by removing+/// non-protected properties in alphabetical order, matching the Node.js+/// `trimPropertiesToFitSize` algorithm. Returns `None` when the value+/// already fits (no trimming needed) — and also when trimming every+/// non-protected property still cannot fit, which callers distinguish by+/// re-checking the size; see `TrimResult` for the ergonomic wrapper.+pub enum TrimResult {+ /// Already within the target; nothing to do.+ Fits,+ /// Trimming non-protected properties got it under the target.+ Trimmed(Value),+ /// Protected properties alone exceed the target; nothing to trim.+ CannotFit,+}++pub fn trim_properties_to_fit_size(properties: &Value, target_bytes: usize) -> TrimResult {+ let mut current = jsonb_column_size(properties);+ if current <= target_bytes {+ return TrimResult::Fits;+ }+ let Some(map) = properties.as_object() else {+ return TrimResult::CannotFit;+ };++ // Removal runs in batches sized by each pair's estimated contribution+ // (two 4-byte JEntries, the key bytes, and the value's content measured+ // at offset 0), with one exact re-measure per batch. Alignment padding+ // makes per-pair contributions position-dependent, so the estimate can+ // be off by a few bytes per numeric — the re-measure keeps the result+ // exact and the deficit shrinks geometrically, bounding the total cost+ // at O(document) per pass for a handful of passes. This can remove a+ // key or two more than the strict minimum in padding-heavy edge cases.+ // Removal order stays alphabetical, matching the pipeline's trim.+ let mut trimmed = map.clone();+ let mut candidates: Vec<String> = map+ .keys()+ .filter(|k| can_trim_property(k))+ .cloned()+ .collect();+ candidates.sort();+ let mut candidates = candidates.into_iter();++ while current > target_bytes {+ let deficit = current - target_bytes;+ let mut estimated_freed = 0usize;+ let mut removed_any = false;+ for key in candidates.by_ref() {+ let Some(value) = trimmed.remove(&key) else {+ continue;+ };+ estimated_freed += 8 + key.len() + element_size(&value, 0);+ removed_any = true;+ if estimated_freed >= deficit {+ break;+ }+ }+ if !removed_any {+ return TrimResult::CannotFit;+ }+ // Measure the map without cloning it: wrap, measure, unwrap.+ let wrapped = Value::Object(std::mem::take(&mut trimmed));+ current = jsonb_column_size(&wrapped);+ let Value::Object(unwrapped) = wrapped else {+ unreachable!("wrapped as an object above");+ };+ trimmed = unwrapped;+ }++ TrimResult::Trimmed(Value::Object(trimmed))+}++#[cfg(test)]+mod tests {+ use super::*;+ use serde_json::json;++ #[test]+ fn trim_of_many_small_keys_is_not_quadratic() {+ // ~1.3MB document of 20k tiny trimmable keys plus protected state.+ // The former per-removal clone-and-remeasure loop needs billions of+ // operations here and effectively never finishes in a debug build;+ // the batched trim completes in well under a second. Completion IS+ // the assertion of linearity; correctness is asserted on the result.+ let mut map = serde_json::Map::new();+ map.insert("email".to_string(), json!("[email protected]"));+ for i in 0..20_000 {+ map.insert(format!("k{i:05}"), json!("v".repeat(40)));+ }+ let value = Value::Object(map);+ let TrimResult::Trimmed(trimmed) = trim_properties_to_fit_size(&value, 524_288) else {+ panic!("a document of trimmable keys must trim");+ };+ assert!(jsonb_column_size(&trimmed) <= 524_288);+ assert_eq!(trimmed["email"], "[email protected]");+ }++ #[test]+ fn protected_properties_are_not_trimmable() {+ assert!(!can_trim_property("email"));+ assert!(!can_trim_property("$browser"));+ assert!(!can_trim_property("utm_source"));+ assert!(!can_trim_property("$user_id"));+ assert!(!can_trim_property("$initial_referrer"));+ assert!(can_trim_property("custom_field"));+ }++ #[test]+ fn empty_containers_have_known_jsonb_sizes() {+ // varlena header (4) + container header (4).+ assert_eq!(jsonb_column_size(&json!({})), 8);+ assert_eq!(jsonb_column_size(&json!([])), 8);+ }++ #[test]+ fn trim_removes_custom_properties_alphabetically() {+ let target = 1024;+ let mut map = serde_json::Map::new();+ map.insert("email".to_string(), json!("[email protected]"));+ map.insert("$browser".to_string(), json!("Chrome"));+ let big_value = "x".repeat(500);+ map.insert("aaa_custom".to_string(), json!(big_value.clone()));+ map.insert("bbb_custom".to_string(), json!(big_value.clone()));+ map.insert("ccc_custom".to_string(), json!(big_value));++ match trim_properties_to_fit_size(&Value::Object(map), target) {+ TrimResult::Trimmed(trimmed) => {+ let trimmed = trimmed.as_object().unwrap();+ assert!(trimmed.contains_key("email"));+ assert!(trimmed.contains_key("$browser"));+ assert!(!trimmed.contains_key("aaa_custom"));+ }+ _ => panic!("expected a trim"),+ }+ }++ #[test]+ fn trim_reports_fits_and_cannot_fit() {+ let small = json!({"email": "[email protected]"});+ assert!(matches!(+ trim_properties_to_fit_size(&small, 1024),+ TrimResult::Fits+ ));++ let protected_oversized = json!({"email": "x".repeat(2_000)});+ assert!(matches!(+ trim_properties_to_fit_size(&protected_oversized, 1024),+ TrimResult::CannotFit+ ));+ }++ #[test]+ fn sanitize_replaces_nul_in_values_keys_and_nested_structures() {+ let mut value = serde_json::json!({+ "clean": "ok",+ "bad\u{0000}key": "still\u{0000}bad",+ "nested": {"inner": ["a\u{0000}b", 1, null]},+ });+ let stats = sanitize_for_jsonb(&mut value);+ assert_eq!(stats.nul_strings, 3);+ let map = value.as_object().unwrap();+ assert_eq!(map["bad\u{FFFD}key"], "still\u{FFFD}bad");+ assert_eq!(map["nested"]["inner"][0], "a\u{FFFD}b");+ assert_eq!(map["clean"], "ok");+ }++ #[test]+ fn sanitize_clamps_floats_beyond_the_safe_magnitude() {+ let mut value = serde_json::json!({+ "huge": 1.7976931348623157e308,+ "neg_huge": [-1.5e308],+ "fine": 1e306,+ "int": u64::MAX,+ });+ let stats = sanitize_for_jsonb(&mut value);+ assert_eq!(stats.clamped_numbers, 2);+ assert_eq!(value["huge"], 1e307);+ assert_eq!(value["neg_huge"][0], -1e307);+ assert_eq!(value["fine"], 1e306);+ assert_eq!(value["int"], u64::MAX);+ }++ #[test]+ fn sanitize_leaves_clean_values_untouched() {+ let mut value = serde_json::json!({"a": "b", "n": [1, 2.5, "x"]});+ let before = value.clone();+ assert!(!sanitize_for_jsonb(&mut value).changed());+ assert_eq!(value, before);+ }++ /// PG's expanded rendering of JS `Number.MAX_VALUE`: the mantissa+ /// digits followed by 292 zeros — serde_json rejects it, JSON.parse+ /// rounds it to exactly `f64::MAX`.+ fn max_value_expansion() -> String {+ format!("17976931348623157{}", "0".repeat(292))+ }++ #[test]+ fn rewrite_rounds_representable_expansions_to_the_double_js_reads() {+ let text = format!("{{\"x\": {}}}", max_value_expansion());+ assert!(serde_json::from_str::<Value>(&text).is_err());+ let parsed: Value = serde_json::from_str(&rewrite_out_of_range_numbers(&text)).unwrap();+ assert_eq!(parsed["x"].as_f64().unwrap(), f64::MAX);+ }++ #[test]+ fn rewrite_clamps_beyond_f64_preserving_sign() {+ // 2e308 and a Python-bigint-scale integer, positive and negative.+ let text = format!(+ "{{\"a\": 2{z308}, \"b\": -2{z308}, \"c\": 1{z400}}}",+ z308 = "0".repeat(308),+ z400 = "0".repeat(400),+ );+ assert!(serde_json::from_str::<Value>(&text).is_err());+ let parsed: Value = serde_json::from_str(&rewrite_out_of_range_numbers(&text)).unwrap();+ assert_eq!(parsed["a"].as_f64().unwrap(), MAX_JSONB_SAFE_MAGNITUDE);+ assert_eq!(parsed["b"].as_f64().unwrap(), -MAX_JSONB_SAFE_MAGNITUDE);+ assert_eq!(parsed["c"].as_f64().unwrap(), MAX_JSONB_SAFE_MAGNITUDE);+ }++ #[test]+ fn rewrite_never_touches_strings_or_parseable_numbers() {+ // Digit runs inside strings — including one shaped exactly like+ // an offending token, behind an escaped quote — plus in-range+ // numbers, must all pass through byte-identical.+ let text = format!(+ "{{\"note\": \"big: 2{z}\", \"esc\": \"say \\\"1{z}\\\" loud\", \+ \"n\": 1e307, \"tiny\": 0.000123, \"neg\": -42}}",+ z = "0".repeat(308),+ );+ assert_eq!(rewrite_out_of_range_numbers(&text), text);+ }++ #[test]+ fn rewrite_output_reparses_for_every_probe_shape() {+ // The PG probe fixtures that motivated the rewriter, as one doc.+ let text = format!(+ "[{max}, 2{z308}, 1{z400}, 1e-308, 0.5, \"x\"]",+ max = max_value_expansion(),+ z308 = "0".repeat(308),+ z400 = "0".repeat(400),+ );+ let parsed: Value = serde_json::from_str(&rewrite_out_of_range_numbers(&text)).unwrap();+ let items = parsed.as_array().unwrap();+ assert_eq!(items[0].as_f64().unwrap(), f64::MAX);+ assert_eq!(items[1].as_f64().unwrap(), MAX_JSONB_SAFE_MAGNITUDE);+ assert_eq!(items[2].as_f64().unwrap(), MAX_JSONB_SAFE_MAGNITUDE);+ assert_eq!(items[3].as_f64().unwrap(), 1e-308);+ assert_eq!(items[4].as_f64().unwrap(), 0.5);+ assert_eq!(items[5], "x");+ }+}diff --git a/rust/personhog-common/tests/jsonb_size_pg.rs b/rust/personhog-common/tests/jsonb_size_pg.rsnew file mode 100644index 000000000000..a7f505aaf789--- /dev/null+++ b/rust/personhog-common/tests/jsonb_size_pg.rs@@ -0,0 +1,135 @@+//! Welds `jsonb_column_size` to the ground truth: for every fixture, the+//! Rust computation must equal `pg_column_size($1::jsonb)` from a real+//! Postgres. The JSONB binary format is stable across PG versions+//! (pg_upgrade compatibility), so a failure here means our encoder — not+//! PG — changed or was wrong. Fixtures deliberately sweep the encoder's+//! branches: alignment padding at every residue, numeric weight and+//! dscale boundaries, exponent literals, nesting, and near-threshold+//! sizes.++use personhog_common::properties::jsonb_column_size;+use serde_json::{json, Value};+use sqlx::postgres::PgPoolOptions;+use sqlx::Row;++const DB_URL: &str = "postgres://posthog:posthog@localhost:5432/posthog_persons";++fn fixtures() -> Vec<Value> {+ let mut cases = vec![+ // Root scalars (wrapped in a pseudo-array container).+ json!(null),+ json!(true),+ json!(false),+ json!(0),+ json!(1),+ json!(-1),+ json!(9),+ json!(9999),+ json!(10000),+ json!(99999999),+ json!(100000000),+ json!(-10000),+ json!(100),+ json!(1000),+ json!(123.45),+ json!(0.1),+ json!(0.0001),+ json!(0.00001),+ json!(1e-10),+ json!(1.5e10),+ json!(u64::MAX),+ json!(i64::MIN),+ json!(-0.007),+ json!(1.234567890123456),+ // Short/long numeric header boundary: PG's short header holds+ // weights -64..=63 (base-10000), so the long header starts at+ // 1e256 (weight 64). Negative-exponent cases cross the dscale+ // limit instead (dscale > 63 forces the long header).+ json!(1e252),+ json!(1e256),+ json!(1e300),+ json!(-1e256),+ json!(1e-256),+ json!(1e-300),+ json!(""),+ json!("a"),+ json!("hello"),+ json!("héllo wörld ✨"),+ // Containers.+ json!({}),+ json!([]),+ json!([1, 2, 3]),+ json!(["a", "bb", "ccc"]),+ json!([null, true, false]),+ json!({"a": 1}),+ json!({"email": "[email protected]", "name": "Test"}),+ json!({"nested": {"a": [1, 2, {"b": "c"}]}}),+ json!([[], {}, [[]], {"x": {}}]),+ json!({"n": [0.5, -3, 12345.6789, 1e5]}),+ ];++ // Alignment sweep: a string of every length residue before a numeric+ // and before a nested container, at object and array level.+ for pad in 0..8 {+ let s = "x".repeat(pad);+ cases.push(json!({ "k": s, "n": 123.456 }));+ cases.push(json!({ "k": s, "o": {"inner": 1} }));+ cases.push(json!([s, 42, s.clone(), {"a": 7.7}, 0.001]));+ }++ // Many-key objects (sorted-key processing order + JEntry accounting).+ let mut wide = serde_json::Map::new();+ for i in 0..64 {+ wide.insert(format!("key_{i:03}"), json!(i));+ }+ cases.push(Value::Object(wide));++ // Mixed-length keys so PG's (length, bytewise) key order differs from+ // alphabetical — padding depends on processing order.+ cases.push(json!({+ "zz": 1.5, "a": "x", "mmmm": [1.25, "y"], "b": 2, "ccc": {"d": 0.75}+ }));++ // A large, near-threshold person shape.+ let mut big = serde_json::Map::new();+ big.insert("email".to_string(), json!("[email protected]"));+ for i in 0..500 {+ big.insert(format!("prop_{i}"), json!("v".repeat(1000)));+ }+ big.insert("counter".to_string(), json!(123456.789));+ cases.push(Value::Object(big));++ cases+}++#[tokio::test]+async fn jsonb_column_size_matches_postgres() {+ let pool = PgPoolOptions::new()+ .max_connections(2)+ .connect(DB_URL)+ .await+ .expect("local posthog_persons Postgres must be running (docker compose)");++ for value in fixtures() {+ // Send the exact bytes the leader would produce, so PG parses the+ // same literals our sizer measured.+ let text = serde_json::to_string(&value).unwrap();+ let row = sqlx::query("SELECT pg_column_size($1::jsonb) AS size")+ .bind(&text)+ .fetch_one(&pool)+ .await+ .unwrap();+ let pg_size: i32 = row.get("size");+ let ours = jsonb_column_size(&value);+ assert_eq!(+ ours,+ pg_size as usize,+ "jsonb size mismatch for {}: ours={ours} pg={pg_size}",+ if text.len() > 120 {+ &text[..120]+ } else {+ &text+ }+ );+ }+}diff --git a/rust/personhog-leader/Cargo.toml b/rust/personhog-leader/Cargo.tomlindex f1a21d130222..08175b613d95 100644--- a/rust/personhog-leader/Cargo.toml+++ b/rust/personhog-leader/Cargo.toml@@ -10,6 +10,7 @@ personhog-common = { path = "../personhog-common" }personhog-coordination = { path = "../personhog-coordination" }assignment-coordination = { path = "../common/assignment-coordination" }common-kafka = { path = "../common/kafka" }+common-ingestion-warnings = { path = "../common/ingestion_warnings" }common-metrics = { path = "../common/metrics" }common-alloc = { path = "../common/alloc" }lifecycle = { path = "../common/lifecycle" }@@ -30,13 +31,13 @@ tokio = { workspace = true }tonic = { workspace = true }tracing = { workspace = true }tracing-subscriber = { workspace = true }+uuid = { workspace = true }[dev-dependencies]health = { path = "../common/health" }tokio = { workspace = true, features = ["test-util"] }tokio-stream = "0.1"tokio-util = { workspace = true }-uuid = { workspace = true }[lints]workspace = truediff --git a/rust/personhog-leader/README.md b/rust/personhog-leader/README.mdindex 58b30e503dc0..7351bfea43db 100644--- a/rust/personhog-leader/README.md+++ b/rust/personhog-leader/README.md@@ -51,6 +51,46 @@ TBD:- below the offset: state is durably in Postgres- at or above the offset: state is PG + the changes in our distributed log (the kafka topic)+#### Admission++Every record the leader produces to the changelog must be applyable by the+writer's upsert verbatim: the changelog is the source of truth, Postgres is a+downstream consumer of it, and a record the writer cannot apply would leave+acked state that never lands (the writer halts rather than skip, since every+later snapshot for a person builds on the same state). Admission enforces+this before the ack, under the per-person lock, on the merged result of each+update:++1. **Sanitize** (`personhog_common::properties::sanitize_for_jsonb`): NUL+ (`\u0000`) becomes `\u{FFFD}` in every string, matching the Node+ pipeline's `sanitizeJsonbValue` — Postgres jsonb refuses NUL. Floats+ beyond ±1e307 are clamped: Postgres renders jsonb numerics in expanded+ decimal, and serde_json cannot parse expansions of ~1e308+, so larger+ values would apply but never load back.+2. **Measure** (`jsonb_column_size`): an exact reimplementation of+ `pg_column_size` for JSONB, welded byte-equal to a live Postgres by+ `personhog-common/tests/jsonb_size_pg.rs`. A merged result above the+ threshold (the `check_properties_size` ceiling) follows the Node+ pipeline's policy (`handleOversizedPersonProperties`): if the stored+ row was already over the threshold, it is remediated — non-protected+ properties trimmed alphabetically to the target, the triggering+ update's property changes discarded; if the row was within limits, the+ update is rejected with `INVALID_ARGUMENT`. Errors carry sizes, never+ values, and remediation that cannot fit (protected properties alone+ exceed the target) also rejects. `PropertySizeLimits::new` refuses+ inverted configuration at startup.+3. **Assert** (`assert_writeable`): identity fields that originate from+ earlier state (uuid parses, team_id fits the column's integer,+ created_at within sane bounds) — corrupt state must never reach the+ changelog.++Trims and rejections emit `person_properties_size_violation` ingestion+warnings (`src/warnings.rs`), throttled per (team, type) to match the Node+pipeline's limiter. The writer-side weld+(`personhog-writer/tests/admission_weld.rs`) runs hostile property fixtures+through these exact functions and the writer's real statement against live+Postgres, asserting byte-exact round-trips.+#### Cache warming on partition handoffWhen a partition moves between leader pods, the new owner repopulates@@ -155,7 +195,8 @@ graph TBsubgraph POD[PersonHog Leader BE]direction TBVALIDATE[Validate ownership] --> COMPUTE[Compute write]- COMPUTE --> CACHE[Update in-memory cache]+ COMPUTE --> ADMIT[Admission: sanitize, measure, reject/remediate]+ ADMIT --> CACHE[Update in-memory cache]CACHE --> KAFKA[Durably store to Kafka]enddiff --git a/rust/personhog-leader/src/config.rs b/rust/personhog-leader/src/config.rsindex 123579cd6f70..c64c7b152720 100644--- a/rust/personhog-leader/src/config.rs+++ b/rust/personhog-leader/src/config.rs@@ -125,6 +125,30 @@ pub struct Config {#[envconfig(default = "5000")]pub warm_retry_max_backoff_ms: u64,+ // ── Property size admission ──────────────────────────────────+ /// Ceiling for a person's properties, measured exactly as the+ /// `check_properties_size` constraint on `posthog_person` measures it:+ /// `pg_column_size(properties)`, the JSONB binary size. An update+ /// that would newly push a within-limit row over this is rejected; a+ /// row already over it (predating the constraint, or from another+ /// writer) is remediated by trimming to the target below, discarding+ /// the triggering update — mirroring the Node pipeline's policy. So+ /// every acked record is applyable by the writer verbatim: the cache,+ /// the changelog, and Postgres can never disagree about an acked row.+ #[envconfig(default = "655360")]+ pub properties_size_threshold: usize,++ /// Size to trim already-oversized properties down to during+ /// remediation, comfortably below the threshold so remediated rows+ /// keep headroom under the constraint.+ #[envconfig(default = "524288")]+ pub properties_trim_target: usize,++ /// Topic for in-product ingestion warnings emitted when admission+ /// trims or rejects an update.+ #[envconfig(default = "clickhouse_ingestion_warnings")]+ pub ingestion_warnings_topic: String,+// ── Dirty index / changelog recovery ─────────────────────────/// How often to poll the writer's committed offsets and prune dirty/// index marks the writer has applied to PG. A tick costs one batcheddiff --git a/rust/personhog-leader/src/lib.rs b/rust/personhog-leader/src/lib.rsindex b2175a4bddf8..5d68386cdff5 100644--- a/rust/personhog-leader/src/lib.rs+++ b/rust/personhog-leader/src/lib.rs@@ -8,3 +8,4 @@ pub mod pg;pub mod recovery;pub mod service;pub mod warming;+pub mod warnings;diff --git a/rust/personhog-leader/src/main.rs b/rust/personhog-leader/src/main.rsindex 4f650b050d14..3131728a751b 100644--- a/rust/personhog-leader/src/main.rs+++ b/rust/personhog-leader/src/main.rs@@ -28,10 +28,11 @@ use personhog_leader::config::Config;use personhog_leader::coordination::LeaderHandoffHandler;use personhog_leader::inflight::InflightTracker;use personhog_leader::recovery::{ChangelogRecovery, RecoveryConfig};-use personhog_leader::service::{sweep_idle_locks, PersonHogLeaderService};+use personhog_leader::service::{sweep_idle_locks, PersonHogLeaderService, PropertySizeLimits};use personhog_leader::warming::{fetch_writer_committed_offsets, WarmingConfig, WarmingRetryPolicy,};+use personhog_leader::warnings::WarningsProducer;common_alloc::used!();@@ -192,9 +193,13 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {}).expect("Failed to build changelog recovery consumer pool"),);+ let warnings = WarningsProducer::new(+ kafka_producer.clone(),+ config.ingestion_warnings_topic.clone(),+ );let service = PersonHogLeaderService::new(Arc::clone(&cache),- kafka_producer,+ kafka_producer.clone(),config.kafka_person_state_topic.clone(),fallback_pool,Arc::clone(&locks),@@ -202,6 +207,11 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {num_partitions,Arc::clone(&dirty_index),Arc::clone(&recovery),+ PropertySizeLimits::new(+ config.properties_size_threshold,+ config.properties_trim_target,+ ),+ warnings.clone(),);let handler = LeaderHandoffHandler::new(@@ -247,13 +257,15 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {}});- // Periodic sweep of idle per-key locks+ // Periodic sweep of idle per-key locks and refilled warning-throttle keyslet sweep_locks = Arc::clone(&locks);+ let sweep_warnings = warnings.clone();tokio::spawn(async move {let mut interval = tokio::time::interval(Duration::from_secs(60));loop {interval.tick().await;sweep_idle_locks(&sweep_locks);+ sweep_warnings.sweep_throttle();}});diff --git a/rust/personhog-leader/src/pg.rs b/rust/personhog-leader/src/pg.rsindex 7140bf424758..d14ac0b294a2 100644--- a/rust/personhog-leader/src/pg.rs+++ b/rust/personhog-leader/src/pg.rs@@ -1,4 +1,5 @@use metrics::{counter, histogram};+use personhog_common::properties::rewrite_out_of_range_numbers;use sqlx::postgres::PgPool;use sqlx::Row;@@ -15,8 +16,14 @@ pub async fn load_person_from_pg(let team_id_i32 = i32::try_from(key.team_id).map_err(|_| sqlx::Error::Protocol(format!("team_id {} exceeds i32 range", key.team_id)))?;+ // properties comes back as text and is parsed here rather than through+ // sqlx's jsonb decode: rows written by other services can hold numerics+ // whose PG-expanded rendering serde_json rejects, and the leniency+ // lives in our parse step (see below). The cost is identical — sqlx's+ // jsonb decode parses the same text under the hood.let row = sqlx::query(- "SELECT id, team_id, uuid::text, properties, created_at, version, is_identified+ "SELECT id, team_id, uuid::text, properties::text AS properties, created_at, version, \+ is_identifiedFROM posthog_personWHERE team_id = $1 AND id = $2",)@@ -36,11 +43,40 @@ pub async fn load_person_from_pg(let id: i64 = row.get("id");let team_id: i32 = row.get("team_id");let uuid: String = row.get("uuid");- let properties: serde_json::Value = row.get("properties");+ // Borrowed from the row buffer — no copy; parse cost matches what+ // sqlx's own jsonb decode would spend on the same bytes.+ let properties_text: &str = row.get("properties");let created_at: chrono::DateTime<chrono::Utc> = row.get("created_at");let version: Option<i64> = row.get("version");let is_identified: bool = row.get("is_identified");+ let properties = match serde_json::from_str(properties_text) {+ Ok(value) => value,+ // Out-of-range numerics from other writers: rewrite to what+ // JSON.parse would read (rounding, clamping beyond f64) instead+ // of leaving the person permanently unloadable. Admission's+ // sanitizer persists the healed form on the next write-through.+ Err(strict_err) => {+ match serde_json::from_str(&rewrite_out_of_range_numbers(properties_text)) {+ Ok(value) => {+ counter!("personhog_leader_pg_properties_rewritten_total").increment(1);+ tracing::warn!(+ team_id,+ person_id = id,+ "rewrote out-of-range numerics in stored person properties"+ );+ value+ }+ Err(rewritten_err) => {+ return Err(sqlx::Error::Protocol(format!(+ "person properties unparseable (team_id={team_id}, person_id={id}): \+ {strict_err}; after numeric rewrite: {rewritten_err}"+ )));+ }+ }+ }+ };+counter!("personhog_leader_pg_fallback_total", "outcome" => "found").increment(1);Ok(Some(CachedPerson {diff --git a/rust/personhog-leader/src/service.rs b/rust/personhog-leader/src/service.rsindex 005ed1ed19f7..133a3e7a3653 100644--- a/rust/personhog-leader/src/service.rs+++ b/rust/personhog-leader/src/service.rs@@ -13,6 +13,7 @@ use rdkafka::producer::FutureProducer;use sqlx::postgres::PgPool;use tokio::sync::Mutex;use tonic::{Request, Response, Status};+use uuid::Uuid;use personhog_common::partitioning::partition_for_person;@@ -24,6 +25,39 @@ use crate::kafka::produce_person_changelog;use crate::person_update::{apply_property_updates, compute_event_property_updates};use crate::pg::load_person_from_pg;use crate::recovery::ChangelogRecovery;+use crate::warnings::{SizeViolationWarning, WarningsProducer};+use personhog_common::properties::{+ jsonb_column_size, sanitize_for_jsonb, trim_properties_to_fit_size, TrimResult,+};++/// Admission-time property size limits, in `pg_column_size` (JSONB+/// binary) terms — the same units as the `check_properties_size`+/// constraint they exist to enforce.+#[derive(Clone, Copy)]+pub struct PropertySizeLimits {+ /// Reject or trim above this (the constraint's ceiling).+ pub threshold: usize,+ /// Trim down to this, leaving headroom under the threshold.+ pub trim_target: usize,+}++impl PropertySizeLimits {+ /// Panics if `trim_target > threshold`: an inverted configuration would+ /// let admission pass documents above the threshold untrimmed, silently+ /// weakening the applyability guarantee. Refusing to construct makes the+ /// admission path's `TrimResult::Fits` arm unreachable.+ pub fn new(threshold: usize, trim_target: usize) -> Self {+ assert!(+ trim_target <= threshold,+ "properties_trim_target ({trim_target}) must not exceed \+ properties_size_threshold ({threshold})"+ );+ Self {+ threshold,+ trim_target,+ }+ }+}pub struct PersonHogLeaderService {cache: Arc<PartitionedCache>,@@ -46,6 +80,8 @@ pub struct PersonHogLeaderService {/// the changelog, unmarked persons' PG rows are known current.dirty_index: Arc<DirtyIndex>,recovery: Arc<ChangelogRecovery>,+ size_limits: PropertySizeLimits,+ warnings: WarningsProducer,}impl PersonHogLeaderService {@@ -60,6 +96,8 @@ impl PersonHogLeaderService {num_partitions: u32,dirty_index: Arc<DirtyIndex>,recovery: Arc<ChangelogRecovery>,+ size_limits: PropertySizeLimits,+ warnings: WarningsProducer,) -> Self {Self {cache,@@ -71,6 +109,8 @@ impl PersonHogLeaderService {num_partitions,dirty_index,recovery,+ size_limits,+ warnings,}}@@ -293,6 +333,39 @@ impl PersonHogLeaderService {}}+/// The changelog contract: every produced record must be applyable by the+/// writer's upsert verbatim. Properties are guaranteed by admission+/// (NUL sanitization plus the exact size measure); this checks the+/// identity fields against the writer's bind conversions — uuid must+/// parse, team_id must fit the column's `integer`, and created_at must+/// sit inside a sanity range ([1970, 9999]) any legitimately created+/// person satisfies.+///+/// These three are the only fields that need checking because they are+/// the only writer-bound fields representable in `CachedPerson`: the+/// legacy jsonb columns and `last_seen_at` have no cache field and are+/// unconditionally empty in `cached_person_to_proto`, so a leader-produced+/// record structurally cannot carry values the writer would refuse there.+fn assert_writeable(p: &CachedPerson) -> Result<(), String> {+ const MAX_EPOCH_SECS_YEAR_9999: i64 = 253_402_300_799;+ if Uuid::parse_str(&p.uuid).is_err() {+ return Err("uuid does not parse as a UUID".to_string());+ }+ if p.team_id <= 0 || p.team_id > i32::MAX as i64 {+ return Err(format!(+ "team_id {} is outside the column's integer range",+ p.team_id+ ));+ }+ if p.created_at < 0 || p.created_at > MAX_EPOCH_SECS_YEAR_9999 {+ return Err(format!(+ "created_at epoch {} is outside sane bounds",+ p.created_at+ ));+ }+ Ok(())+}+fn cached_person_to_proto(p: &CachedPerson) -> Person {let properties_bytes = serde_json::to_vec(&p.properties).unwrap_or_default();Person {@@ -400,6 +473,36 @@ impl PersonHogLeader for PersonHogLeaderService {})?};+ // Sanitize the request values before diffing so no-op detection+ // compares in sanitized space: cached state holds the sanitized+ // form, and an unsanitized repeat of the same value must hit the+ // no-change fast path instead of producing a fresh record every+ // time. The post-merge sanitize below stays as the admission+ // guarantee (it also covers legacy dirt already in the cache).+ let mut set_properties = set_properties;+ let mut set_once_properties = set_once_properties;+ let input_stats = {+ let mut stats = sanitize_for_jsonb(&mut set_properties);+ let once = sanitize_for_jsonb(&mut set_once_properties);+ stats.nul_strings += once.nul_strings;+ stats.clamped_numbers += once.clamped_numbers;+ stats+ };+ if input_stats.nul_strings > 0 {+ counter!("personhog_leader_properties_nul_sanitized_total")+ .increment(input_stats.nul_strings);+ }+ if input_stats.clamped_numbers > 0 {+ counter!("personhog_leader_properties_numbers_clamped_total")+ .increment(input_stats.clamped_numbers);+ }+ // Unset targets must match keys as stored, i.e. sanitized.+ let unset_properties: Vec<String> = req+ .unset_properties+ .iter()+ .map(|k| k.replace('\u{0000}', "\u{FFFD}"))+ .collect();+// Per-key lock serializes concurrent updates for the same personlet mutex = self.locks@@ -430,7 +533,7 @@ impl PersonHogLeader for PersonHogLeaderService {&req.event_name,&set_properties,&set_once_properties,- &req.unset_properties,+ &unset_properties,&person.properties,);@@ -456,6 +559,104 @@ impl PersonHogLeader for PersonHogLeaderService {}));}+ // Admission-time size enforcement, hoisted from the writer: every+ // acked record must be applyable by the writer verbatim, or the+ // cache and changelog would carry state Postgres never gets (the+ // stale-serve hole the dirty index exists to close). The measure+ // is the constraint's own — pg_column_size of the JSONB encoding+ // — so admitted rows cannot violate it at apply time.+ let mut new_properties = new_properties;++ // Rewrite the merged state into jsonb-safe form before measuring:+ // NUL sanitization (Node-pipeline parity — Postgres refuses it)+ // and extreme-float clamping (Postgres's expanded numeric+ // rendering would otherwise be unparseable on the way back). The+ // measured size is then the stored size.+ let sanitize_stats = sanitize_for_jsonb(&mut new_properties);+ if sanitize_stats.nul_strings > 0 {+ counter!("personhog_leader_properties_nul_sanitized_total")+ .increment(sanitize_stats.nul_strings);+ }+ if sanitize_stats.clamped_numbers > 0 {+ counter!("personhog_leader_properties_numbers_clamped_total")+ .increment(sanitize_stats.clamped_numbers);+ }++ let jsonb_size = jsonb_column_size(&new_properties);+ if jsonb_size > self.size_limits.threshold {+ // Policy mirror of the Node pipeline's+ // `handleOversizedPersonProperties`: trimming is remediation+ // for rows already oversized in storage (they predate the+ // constraint, or another writer produced them) — the stored+ // properties are trimmed to the target and the triggering+ // update's property changes are discarded, exactly as Node+ // retries with trimmed existing state. An update that would+ // newly push a within-limit row over the ceiling is rejected+ // outright: a rejection with a warning is a deliberate,+ // visible outcome where a silent trim would be arbitrary+ // deferred data loss. Warnings and errors carry sizes, never+ // property values.+ let existing_size = jsonb_column_size(&person.properties);+ if existing_size >= self.size_limits.threshold {+ match trim_properties_to_fit_size(&person.properties, self.size_limits.trim_target)+ {+ TrimResult::Trimmed(trimmed) => {+ counter!("personhog_leader_properties_trimmed_total").increment(1);+ self.warnings.emit(&SizeViolationWarning {+ team_id: cache_key.team_id,+ person_uuid: person.uuid.clone(),+ message: "Oversized person properties were trimmed to fit the size \+ limit; the update that surfaced them was discarded"+ .to_string(),+ });+ new_properties = trimmed;+ }+ // Reachable only when trim_target == threshold and the+ // stored size sits exactly on it: nothing to trim, but+ // the update still cannot apply — keep the stored+ // state, discarding the update like the arm above.+ TrimResult::Fits => {+ new_properties = person.properties.clone();+ }+ TrimResult::CannotFit => {+ counter!(+ "personhog_leader_updates_total",+ "outcome" => "rejected_unremediable"+ )+ .increment(1);+ self.warnings.emit(&SizeViolationWarning {+ team_id: cache_key.team_id,+ person_uuid: person.uuid.clone(),+ message: "Person properties exceed the size limit and could not be \+ trimmed; the update was rejected"+ .to_string(),+ });+ return Err(Status::invalid_argument(format!(+ "person properties exceed the size limit: stored state is \+ {existing_size} bytes (jsonb) and protected properties alone exceed \+ the {} trim target",+ self.size_limits.trim_target,+ )));+ }+ }+ } else {+ counter!("personhog_leader_updates_total", "outcome" => "rejected_oversized")+ .increment(1);+ self.warnings.emit(&SizeViolationWarning {+ team_id: cache_key.team_id,+ person_uuid: person.uuid.clone(),+ message: "Person properties update would exceed the size limit and was \+ rejected"+ .to_string(),+ });+ return Err(Status::invalid_argument(format!(+ "person properties update would exceed the size limit: {jsonb_size} bytes \+ (jsonb) over the {} ceiling",+ self.size_limits.threshold,+ )));+ }+ }+let updated_person = CachedPerson {id: person.id,uuid: person.uuid.clone(),@@ -465,6 +666,24 @@ impl PersonHogLeader for PersonHogLeaderService {version: person.version + 1,is_identified: person.is_identified,};++ // Final applyability assertions on the identity fields, which+ // originate from earlier state rather than this request. A record+ // the writer cannot bind must never reach the changelog — no+ // consumer downstream can apply or repair it.+ if let Err(reason) = assert_writeable(&updated_person) {+ counter!("personhog_leader_unwriteable_state_total").increment(1);+ tracing::error!(+ team_id = cache_key.team_id,+ person_id = cache_key.person_id,+ reason,+ "refusing to produce an unapplyable changelog record"+ );+ return Err(Status::internal(format!(+ "person state is not writeable: {reason}"+ )));+ }+let proto = cached_person_to_proto(&updated_person);// Produce to Kafka first, then update the cache on success.@@ -551,13 +770,13 @@ mod tests {let liveness = HealthRegistry::new("test").register("kafka".to_string(), Duration::from_secs(60)).await;- let producer = ClientConfig::new()+ let producer: rdkafka::producer::FutureProducer<KafkaContext> = ClientConfig::new().set("bootstrap.servers", "127.0.0.1:1").create_with_context(KafkaContext::from(liveness)).unwrap();PersonHogLeaderService::new(Arc::new(PartitionedCache::new(16)),- producer,+ producer.clone(),"personhog_updates".to_string(),None,Arc::new(DashMap::new()),@@ -574,9 +793,17 @@ mod tests {}).expect("build recovery pool"),),+ PropertySizeLimits::new(655360, 524288),+ WarningsProducer::new(producer, "clickhouse_ingestion_warnings".to_string()),)}+ #[test]+ #[should_panic(expected = "must not exceed")]+ fn inverted_size_limits_refuse_to_construct() {+ PropertySizeLimits::new(655_360, 655_361);+ }+#[tokio::test]async fn unmarked_miss_fails_closed_once_partition_is_released() {let service = make_test_service().await;diff --git a/rust/personhog-leader/src/warnings.rs b/rust/personhog-leader/src/warnings.rsnew file mode 100644index 000000000000..a199fbf76a54--- /dev/null+++ b/rust/personhog-leader/src/warnings.rs@@ -0,0 +1,126 @@+use std::sync::Arc;++use metrics::counter;+use rdkafka::producer::{FutureProducer, FutureRecord};+use tracing::warn;++use common_ingestion_warnings::registry::WarningType;+use common_ingestion_warnings::serializer::Warning as WarningPayload;+use common_ingestion_warnings::throttle::{ThrottleDecision, WarningThrottle};+use common_ingestion_warnings::WarningSource;+use common_kafka::kafka_producer::KafkaContext;++/// Warnings emitted from the leader's admission check, ahead of the write+/// path proper. `pipeline_step` lands in the v2 table's `pipeline_step`+/// column via the row's details.+const LEADER_ADMISSION: WarningSource = WarningSource {+ service: "personhog-leader",+ path: "admission",+ pipeline_step: "personhog_admission",+};++/// An in-product ingestion warning about a person's property size —+/// emitted when admission trims an update to fit the Postgres constraint+/// or rejects one that cannot fit. Carries no property values, only+/// identifiers and sizes.+pub struct SizeViolationWarning {+ pub team_id: i64,+ /// The person's UUID — the pipeline convention for `personId` in+ /// warning details (row ids stay internal).+ pub person_uuid: String,+ pub message: String,+}++/// Produces ingestion warnings to Kafka so users see property size+/// violations in-product, with the payload built by the shared+/// ingestion-warnings crate so type and classification come from the+/// pipeline registry. Shares the leader's changelog producer (rdkafka+/// producers are topic-agnostic), so buffered warnings flush with it on+/// shutdown; emission is fire-and-forget and never blocks or fails the+/// update that triggered it.+///+/// Emission is throttled per `(team, type)` with the pipeline's default+/// budget (one per hour), matching the Node consumers' warning limiter:+/// one oversized person being hammered with updates yields one warning an+/// hour, not one per update. Cloning shares the throttle, so every handle+/// draws from the same budget.+#[derive(Clone)]+pub struct WarningsProducer {+ producer: FutureProducer<KafkaContext>,+ topic: String,+ throttle: Arc<WarningThrottle>,+}++impl WarningsProducer {+ pub fn new(producer: FutureProducer<KafkaContext>, topic: String) -> Self {+ Self::with_throttle(producer, topic, WarningThrottle::default())+ }++ /// Construct with an explicit throttle — tests use a larger burst so+ /// consecutive enforcement actions for one team all surface.+ pub fn with_throttle(+ producer: FutureProducer<KafkaContext>,+ topic: String,+ throttle: WarningThrottle,+ ) -> Self {+ Self {+ producer,+ topic,+ throttle: Arc::new(throttle),+ }+ }++ pub fn emit(&self, warning: &SizeViolationWarning) {+ let warning_type = WarningType::PersonPropertiesSizeViolation;+ match self+ .throttle+ .check(&warning.team_id.to_string(), warning_type)+ {+ ThrottleDecision::Emit => {}+ ThrottleDecision::Throttled => {+ counter!(+ "personhog_leader_ingestion_warnings_suppressed_total",+ "outcome" => "throttled"+ )+ .increment(1);+ return;+ }+ ThrottleDecision::CardinalityCapped => {+ counter!(+ "personhog_leader_ingestion_warnings_suppressed_total",+ "outcome" => "cardinality_capped"+ )+ .increment(1);+ return;+ }+ }++ // teamId, category, severity, and pipelineStep are injected by the+ // terminal.+ let payload = WarningPayload::new(warning_type)+ .with_detail("personId", warning.person_uuid.clone())+ .with_detail("message", warning.message.clone())+ .into_row(warning.team_id, LEADER_ADMISSION);++ let payload_bytes = serde_json::to_vec(&payload).unwrap_or_default();+ let key = warning.team_id.to_string();+ let record = FutureRecord::to(&self.topic)+ .payload(&payload_bytes)+ .key(&key);++ match self.producer.send_result(record) {+ Ok(_future) => {+ counter!("personhog_leader_ingestion_warnings_emitted_total").increment(1);+ }+ Err((e, _)) => {+ warn!(error = %e, "failed to enqueue ingestion warning");+ }+ }+ }++ /// Evict fully refilled throttle keys, bounding memory. Called from the+ /// leader's periodic maintenance task.+ pub fn sweep_throttle(&self) {+ self.throttle.sweep();+ }+}diff --git a/rust/personhog-leader/tests/common/mod.rs b/rust/personhog-leader/tests/common/mod.rsindex bacc6a5b8466..23c366649759 100644--- a/rust/personhog-leader/tests/common/mod.rs+++ b/rust/personhog-leader/tests/common/mod.rs@@ -29,7 +29,8 @@ use personhog_leader::cache::{CachedPerson, DirtyIndex, PartitionedCache, Personuse personhog_leader::coordination::LeaderHandoffHandler;use personhog_leader::inflight::InflightTracker;use personhog_leader::recovery::{ChangelogRecovery, RecoveryConfig};-use personhog_leader::service::PersonHogLeaderService;+use personhog_leader::service::{PersonHogLeaderService, PropertySizeLimits};+use personhog_leader::warnings::WarningsProducer;use personhog_proto::personhog::leader::v1::person_hog_leader_client::PersonHogLeaderClient;use personhog_proto::personhog::leader::v1::person_hog_leader_server::PersonHogLeaderServer;use tokio::net::TcpListener;@@ -350,7 +351,7 @@ pub async fn start_leader_pod(// gRPC leader service sharing the same cachelet service = PersonHogLeaderService::new(Arc::clone(&cache),- kafka_producer,+ kafka_producer.clone(),CHANGELOG_TOPIC.to_string(),None,Arc::new(DashMap::new()),@@ -358,6 +359,8 @@ pub async fn start_leader_pod(NUM_PARTITIONS,Arc::clone(&dirty_index),recovery,+ PropertySizeLimits::new(655360, 524288),+ WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),);let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();let leader_addr = listener.local_addr().unwrap();@@ -419,7 +422,7 @@ pub async fn start_leader_pod_with_lease_ttl(let service = PersonHogLeaderService::new(Arc::clone(&cache),- kafka_producer,+ kafka_producer.clone(),CHANGELOG_TOPIC.to_string(),None,Arc::new(DashMap::new()),@@ -427,6 +430,8 @@ pub async fn start_leader_pod_with_lease_ttl(NUM_PARTITIONS,Arc::clone(&dirty_index),recovery,+ PropertySizeLimits::new(655360, 524288),+ WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),);let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();let leader_addr = listener.local_addr().unwrap();@@ -501,7 +506,7 @@ pub async fn start_leader_with_pg_fallback(let service = PersonHogLeaderService::new(Arc::clone(&cache),- kafka_producer,+ kafka_producer.clone(),CHANGELOG_TOPIC.to_string(),Some(pool),Arc::new(DashMap::new()),@@ -509,6 +514,8 @@ pub async fn start_leader_with_pg_fallback(NUM_PARTITIONS,Arc::new(DirtyIndex::new(1_000_000)),test_recovery(&mock_cluster.bootstrap_servers()),+ PropertySizeLimits::new(655360, 524288),+ WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),);let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();diff --git a/rust/personhog-leader/tests/integration.rs b/rust/personhog-leader/tests/integration.rsindex 6dd4efe9fe2f..fb1080848ec4 100644--- a/rust/personhog-leader/tests/integration.rs+++ b/rust/personhog-leader/tests/integration.rs@@ -1,7 +1,10 @@mod common;+use std::num::NonZeroU32;use std::sync::Arc;-use std::time::Duration;+use std::time::{Duration, Instant};++use common_ingestion_warnings::throttle::{WarningThrottle, DEFAULT_THROTTLE_PERIOD};use dashmap::DashMap;@@ -20,7 +23,8 @@ use personhog_leader::cache::{};use personhog_leader::coordination::LeaderHandoffHandler;use personhog_leader::inflight::InflightTracker;-use personhog_leader::service::PersonHogLeaderService;+use personhog_leader::service::{PersonHogLeaderService, PropertySizeLimits};+use personhog_leader::warnings::WarningsProducer;use personhog_proto::personhog::leader::v1::person_hog_leader_server::PersonHogLeaderServer;use personhog_proto::personhog::types::v1::{GetPersonRequest, Person, UpdatePersonPropertiesRequest,@@ -170,7 +174,7 @@ async fn unowned_partition_returns_failed_precondition() {let (_mock_cluster, kafka_producer) = create_test_kafka().await;let service = PersonHogLeaderService::new(Arc::clone(&cache),- kafka_producer,+ kafka_producer.clone(),CHANGELOG_TOPIC.to_string(),None,Arc::new(DashMap::new()),@@ -178,6 +182,8 @@ async fn unowned_partition_returns_failed_precondition() {NUM_PARTITIONS,Arc::new(DirtyIndex::new(1_000_000)),test_recovery(KAFKA_BOOTSTRAP),+ PropertySizeLimits::new(655360, 524288),+ WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),);let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();@@ -246,7 +252,7 @@ async fn missing_partition_metadata_returns_invalid_argument() {let (_mock_cluster, kafka_producer) = create_test_kafka().await;let service = PersonHogLeaderService::new(Arc::clone(&cache),- kafka_producer,+ kafka_producer.clone(),CHANGELOG_TOPIC.to_string(),None,Arc::new(DashMap::new()),@@ -254,6 +260,8 @@ async fn missing_partition_metadata_returns_invalid_argument() {NUM_PARTITIONS,Arc::new(DirtyIndex::new(1_000_000)),test_recovery(KAFKA_BOOTSTRAP),+ PropertySizeLimits::new(655360, 524288),+ WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),);// Warm the partition and seed the person so the only failure mode@@ -325,7 +333,7 @@ async fn mismatched_partition_metadata_returns_invalid_argument() {let (_mock_cluster, kafka_producer) = create_test_kafka().await;let service = PersonHogLeaderService::new(Arc::clone(&cache),- kafka_producer,+ kafka_producer.clone(),CHANGELOG_TOPIC.to_string(),None,Arc::new(DashMap::new()),@@ -333,6 +341,8 @@ async fn mismatched_partition_metadata_returns_invalid_argument() {NUM_PARTITIONS,Arc::new(DirtyIndex::new(1_000_000)),test_recovery(KAFKA_BOOTSTRAP),+ PropertySizeLimits::new(655360, 524288),+ WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),);// Key (1, 42) hashes to some true partition; pick a different one and@@ -410,7 +420,7 @@ async fn writes_fenced_after_drain_reads_still_served() {let recovery = test_recovery(KAFKA_BOOTSTRAP);let service = PersonHogLeaderService::new(Arc::clone(&cache),- kafka_producer,+ kafka_producer.clone(),CHANGELOG_TOPIC.to_string(),None,Arc::new(DashMap::new()),@@ -418,6 +428,8 @@ async fn writes_fenced_after_drain_reads_still_served() {NUM_PARTITIONS,Arc::clone(&dirty_index),Arc::clone(&recovery),+ PropertySizeLimits::new(655360, 524288),+ WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),);// The handler shares the cache, inflight tracker, dirty index, and// recovery pool with the service, exactly as main.rs wires them.@@ -519,7 +531,7 @@ async fn drain_fences_before_waiting_on_inflight() {let recovery = test_recovery(KAFKA_BOOTSTRAP);let service = PersonHogLeaderService::new(Arc::clone(&cache),- kafka_producer,+ kafka_producer.clone(),CHANGELOG_TOPIC.to_string(),None,Arc::new(DashMap::new()),@@ -527,6 +539,8 @@ async fn drain_fences_before_waiting_on_inflight() {NUM_PARTITIONS,Arc::clone(&dirty_index),Arc::clone(&recovery),+ PropertySizeLimits::new(655360, 524288),+ WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),);let handler = Arc::new(LeaderHandoffHandler::new(Arc::clone(&cache),@@ -826,7 +840,7 @@ async fn update_produces_person_state_to_kafka() {let cache = Arc::new(PartitionedCache::new(100));let service = PersonHogLeaderService::new(Arc::clone(&cache),- kafka_producer,+ kafka_producer.clone(),CHANGELOG_TOPIC.to_string(),None,Arc::new(DashMap::new()),@@ -834,6 +848,8 @@ async fn update_produces_person_state_to_kafka() {NUM_PARTITIONS,Arc::new(DirtyIndex::new(1_000_000)),test_recovery(KAFKA_BOOTSTRAP),+ PropertySizeLimits::new(655360, 524288),+ WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),);cache.create_partition(routing_partition);@@ -934,7 +950,7 @@ async fn kafka_produce_failure_leaves_cache_unchanged() {let service = PersonHogLeaderService::new(Arc::clone(&cache),- kafka_producer,+ kafka_producer.clone(),CHANGELOG_TOPIC.to_string(),None,Arc::new(DashMap::new()),@@ -942,6 +958,8 @@ async fn kafka_produce_failure_leaves_cache_unchanged() {NUM_PARTITIONS,Arc::new(DirtyIndex::new(1_000_000)),test_recovery(KAFKA_BOOTSTRAP),+ PropertySizeLimits::new(655360, 524288),+ WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),);cache.create_partition(0);@@ -1040,7 +1058,7 @@ async fn e2e_update_produces_to_local_kafka() {let service = PersonHogLeaderService::new(Arc::clone(&cache),- kafka_producer,+ kafka_producer.clone(),CHANGELOG_TOPIC.to_string(),None,Arc::new(DashMap::new()),@@ -1048,6 +1066,8 @@ async fn e2e_update_produces_to_local_kafka() {NUM_PARTITIONS,Arc::new(DirtyIndex::new(1_000_000)),test_recovery(KAFKA_BOOTSTRAP),+ PropertySizeLimits::new(655360, 524288),+ WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),);cache.create_partition(0);@@ -1191,6 +1211,59 @@ async fn pg_fallback_loads_person_on_cache_miss() {cancel.cancel();}+/// Rows written by other services can hold numerics whose PG-expanded+/// rendering serde_json rejects even though JSON.parse reads them fine+/// (JS `Number.MAX_VALUE` is the canonical case — a common "unlimited"+/// sentinel). The fallback must load such rows the way JS would — rounding+/// representable values, clamping beyond-f64 garbage — never panic or+/// leave the person permanently unloadable.+#[tokio::test]+async fn pg_fallback_reads_numerics_the_leaders_parser_rejects() {+ let pool = common::create_persons_pool().await;+ let team_id: i32 = 99_060;+ sqlx::query("DELETE FROM posthog_person WHERE team_id = $1")+ .bind(team_id)+ .execute(&pool)+ .await+ .unwrap();++ // Written exactly as Node's pg driver would: e-notation literals that+ // PG stores as full-precision numerics and renders back expanded.+ let row: (i64,) = sqlx::query_as(+ "INSERT INTO posthog_person (created_at, properties, is_identified, uuid, version, team_id)+ VALUES (now(),+ '{\"credits\": 1.7976931348623157e+308, \"overflow\": 2e308, \"plan\": \"pro\"}'::jsonb,+ false, gen_random_uuid(), 1, $1)+ RETURNING id",+ )+ .bind(team_id)+ .fetch_one(&pool)+ .await+ .unwrap();++ let key = PersonCacheKey {+ team_id: team_id as i64,+ person_id: row.0,+ };+ let person = personhog_leader::pg::load_person_from_pg(&pool, &key)+ .await+ .expect("load must not fail")+ .expect("person exists");++ // The representable sentinel reads as the exact double JS reads;+ // beyond-f64 garbage clamps instead of poisoning the row; neighbors+ // are untouched.+ assert_eq!(person.properties["credits"].as_f64().unwrap(), f64::MAX);+ assert_eq!(person.properties["overflow"].as_f64().unwrap(), 1e307);+ assert_eq!(person.properties["plan"], "pro");++ sqlx::query("DELETE FROM posthog_person WHERE team_id = $1")+ .bind(team_id)+ .execute(&pool)+ .await+ .unwrap();+}+// ============================================================// Test 9: PG fallback returns NotFound for non-existent person// ============================================================@@ -1292,7 +1365,7 @@ async fn evicted_dirty_person_recovers_from_changelog() {let recovery = test_recovery(&mock_cluster.bootstrap_servers());let service = PersonHogLeaderService::new(Arc::clone(&cache),- kafka_producer,+ kafka_producer.clone(),CHANGELOG_TOPIC.to_string(),None,Arc::new(DashMap::new()),@@ -1300,6 +1373,8 @@ async fn evicted_dirty_person_recovers_from_changelog() {NUM_PARTITIONS,Arc::clone(&dirty_index),Arc::clone(&recovery),+ PropertySizeLimits::new(655360, 524288),+ WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),);cache.create_partition(routing_partition);@@ -1388,7 +1463,7 @@ async fn dirty_person_with_failed_recovery_is_unavailable_not_stale() {let recovery = test_recovery(&mock_cluster.bootstrap_servers());let service = PersonHogLeaderService::new(Arc::clone(&cache),- kafka_producer,+ kafka_producer.clone(),CHANGELOG_TOPIC.to_string(),None,Arc::new(DashMap::new()),@@ -1396,6 +1471,8 @@ async fn dirty_person_with_failed_recovery_is_unavailable_not_stale() {NUM_PARTITIONS,Arc::clone(&dirty_index),Arc::clone(&recovery),+ PropertySizeLimits::new(655360, 524288),+ WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),);cache.create_partition(routing_partition);@@ -1490,7 +1567,7 @@ async fn writes_shed_when_dirty_index_is_full() {let dirty_index = Arc::new(DirtyIndex::new(1));let service = PersonHogLeaderService::new(Arc::clone(&cache),- kafka_producer,+ kafka_producer.clone(),CHANGELOG_TOPIC.to_string(),None,Arc::new(DashMap::new()),@@ -1498,6 +1575,8 @@ async fn writes_shed_when_dirty_index_is_full() {NUM_PARTITIONS,Arc::clone(&dirty_index),test_recovery(&mock_cluster.bootstrap_servers()),+ PropertySizeLimits::new(655360, 524288),+ WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),);cache.create_partition(partition);@@ -1583,7 +1662,7 @@ async fn recovery_fails_when_record_version_disagrees_with_the_mark() {let recovery = test_recovery(&mock_cluster.bootstrap_servers());let service = PersonHogLeaderService::new(Arc::clone(&cache),- kafka_producer,+ kafka_producer.clone(),CHANGELOG_TOPIC.to_string(),None,Arc::new(DashMap::new()),@@ -1591,6 +1670,8 @@ async fn recovery_fails_when_record_version_disagrees_with_the_mark() {NUM_PARTITIONS,Arc::clone(&dirty_index),Arc::clone(&recovery),+ PropertySizeLimits::new(655360, 524288),+ WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),);cache.create_partition(routing_partition);@@ -1686,7 +1767,7 @@ async fn recovery_reuses_the_partition_consumer_across_fetches() {let recovery = test_recovery(&mock_cluster.bootstrap_servers());let service = PersonHogLeaderService::new(Arc::clone(&cache),- kafka_producer,+ kafka_producer.clone(),CHANGELOG_TOPIC.to_string(),None,Arc::new(DashMap::new()),@@ -1694,6 +1775,8 @@ async fn recovery_reuses_the_partition_consumer_across_fetches() {NUM_PARTITIONS,Arc::clone(&dirty_index),Arc::clone(&recovery),+ PropertySizeLimits::new(655360, 524288),+ WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),);cache.create_partition(partition);@@ -1868,3 +1951,445 @@ async fn cancelled_recovery_returns_its_consumer_to_the_pool() {.expect("the pool must survive cancellations");assert_eq!(recovered.id, 7);}++// ============================================================+// Admission-time property size enforcement, mirroring the Node+// pipeline's policy: an update that would newly push a within-limit+// row over the ceiling is rejected; a row already over it is+// remediated (existing properties trimmed, the update discarded) —+// so every acked record is applyable by the writer verbatim.+// ============================================================++#[tokio::test]+async fn oversize_updates_are_rejected_and_oversized_rows_remediated() {+ const PERSON_ID: i64 = 9;+ let routing_partition: u32 = partition_for_person(1, PERSON_ID, NUM_PARTITIONS);+ let (mock_cluster, kafka_producer) = create_test_kafka_with_partitions(4).await;+ // The warnings topic is not auto-created; the fire-and-forget emit+ // would silently drop without it.+ mock_cluster+ .create_topic("clickhouse_ingestion_warnings", 1, 1)+ .unwrap();++ let cache = Arc::new(PartitionedCache::new(100));+ let dirty_index = Arc::new(DirtyIndex::new(1_000_000));+ let recovery = test_recovery(&mock_cluster.bootstrap_servers());+ let service = PersonHogLeaderService::new(+ Arc::clone(&cache),+ kafka_producer.clone(),+ CHANGELOG_TOPIC.to_string(),+ None,+ Arc::new(DashMap::new()),+ Arc::new(InflightTracker::new()),+ NUM_PARTITIONS,+ Arc::clone(&dirty_index),+ recovery,+ PropertySizeLimits::new(655360, 524288),+ // Burst 2 so the trim and reject below — same team, same type —+ // both clear the throttle; the third enforcement action then+ // exercises suppression.+ WarningsProducer::with_throttle(+ kafka_producer,+ "clickhouse_ingestion_warnings".to_string(),+ WarningThrottle::new(DEFAULT_THROTTLE_PERIOD, NonZeroU32::new(2).unwrap()),+ ),+ );++ cache.create_partition(routing_partition);+ let person = CachedPerson {+ id: PERSON_ID,+ ..test_cached_person()+ };+ seed_person(&cache, routing_partition, person);++ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();+ let addr = listener.local_addr().unwrap();+ let cancel = CancellationToken::new();+ let token = cancel.child_token();+ tokio::spawn(async move {+ Server::builder()+ .add_service(PersonHogLeaderServer::new(service))+ .serve_with_incoming_shutdown(+ tokio_stream::wrappers::TcpListenerStream::new(listener),+ token.cancelled(),+ )+ .await+ .unwrap();+ });+ tokio::time::sleep(Duration::from_millis(10)).await;+ let mut client = create_leader_client(addr).await;++ // New violation: the seeded person is within limits and this update+ // would push the merged state over the ceiling — rejected outright,+ // nothing stored, matching the Node pipeline's+ // attempt_to_violate_limit path.+ let big = "x".repeat(400_000);+ let err = client+ .update_person_properties(with_partition(+ UpdatePersonPropertiesRequest {+ team_id: 1,+ person_id: PERSON_ID,+ event_name: "$set".to_string(),+ set_properties: serde_json::to_vec(&serde_json::json!({+ "email": "[email protected]", "custom_a": big, "custom_b": big,+ }))+ .unwrap(),+ set_once_properties: vec![],+ unset_properties: vec![],+ },+ routing_partition,+ ))+ .await+ .expect_err("a newly violating update must be rejected");+ assert_eq!(err.code(), tonic::Code::InvalidArgument);+ assert!(err.message().contains("size limit"));+ assert!(+ !err.message().contains("xxx"),+ "the error must carry sizes, never property values"+ );++ // Rejection leaves no residue: the rejected update's keys are absent+ // from a strong read, and a normal update still works.+ let read = client+ .get_person(with_partition(+ GetPersonRequest {+ team_id: 1,+ person_id: PERSON_ID,+ read_options: None,+ },+ routing_partition,+ ))+ .await+ .unwrap()+ .into_inner();+ let read_props: serde_json::Value =+ serde_json::from_slice(&read.person.unwrap().properties).unwrap();+ assert!(!read_props.as_object().unwrap().contains_key("custom_a"));+ let response = client+ .update_person_properties(with_partition(+ UpdatePersonPropertiesRequest {+ team_id: 1,+ person_id: PERSON_ID,+ event_name: "$set".to_string(),+ set_properties: serde_json::to_vec(&serde_json::json!({"name": "after"})).unwrap(),+ set_once_properties: vec![],+ unset_properties: vec![],+ },+ routing_partition,+ ))+ .await+ .unwrap()+ .into_inner();+ assert!(response.updated);++ // Remediation: a row already over the ceiling (legacy rows, and rows+ // from the Node writer during dual-write) is healed on its next+ // update — existing properties trimmed alphabetically to the target+ // and the triggering update's changes discarded, matching the Node+ // pipeline's existing_record_violates_limit path. custom_a goes+ // (alphabetically first) and custom_b, which alone fits the target,+ // survives.+ const OVERSIZED_PERSON_ID: i64 = 10;+ let oversized_partition = partition_for_person(1, OVERSIZED_PERSON_ID, NUM_PARTITIONS);+ if oversized_partition != routing_partition {+ cache.create_partition(oversized_partition);+ }+ seed_person(+ &cache,+ oversized_partition,+ CachedPerson {+ id: OVERSIZED_PERSON_ID,+ properties: serde_json::json!({+ "email": "[email protected]", "custom_a": big, "custom_b": big,+ }),+ ..test_cached_person()+ },+ );+ let response = client+ .update_person_properties(with_partition(+ UpdatePersonPropertiesRequest {+ team_id: 1,+ person_id: OVERSIZED_PERSON_ID,+ event_name: "$set".to_string(),+ set_properties: serde_json::to_vec(&serde_json::json!({"name": "discarded"}))+ .unwrap(),+ set_once_properties: vec![],+ unset_properties: vec![],+ },+ oversized_partition,+ ))+ .await+ .unwrap()+ .into_inner();+ assert!(response.updated);+ let stored: serde_json::Value =+ serde_json::from_slice(&response.person.unwrap().properties).unwrap();+ let stored = stored.as_object().unwrap();+ assert_eq!(stored["email"], "[email protected]", "protected properties survive");+ assert!(+ !stored.contains_key("custom_a"),+ "custom_a must be trimmed (alphabetically first)"+ );+ assert!(stored.contains_key("custom_b"));+ assert!(+ !stored.contains_key("name"),+ "the triggering update's changes are discarded, as in Node"+ );++ // The stored state IS the remediated state: a strong read agrees+ // with the update response.+ let read = client+ .get_person(with_partition(+ GetPersonRequest {+ team_id: 1,+ person_id: OVERSIZED_PERSON_ID,+ read_options: None,+ },+ oversized_partition,+ ))+ .await+ .unwrap()+ .into_inner();+ let read_props: serde_json::Value =+ serde_json::from_slice(&read.person.unwrap().properties).unwrap();+ assert!(!read_props.as_object().unwrap().contains_key("custom_a"));++ // Unremediable: the stored row is over the ceiling and its protected+ // property alone exceeds the trim target — nothing can be trimmed,+ // so the update is rejected. (Its warning lands after the throttle+ // burst of 2 and is suppressed; the error is asserted directly.)+ const UNREMEDIABLE_PERSON_ID: i64 = 12;+ let unremediable_partition = partition_for_person(1, UNREMEDIABLE_PERSON_ID, NUM_PARTITIONS);+ if unremediable_partition != routing_partition && unremediable_partition != oversized_partition+ {+ cache.create_partition(unremediable_partition);+ }+ let huge_email = "e".repeat(700_000);+ seed_person(+ &cache,+ unremediable_partition,+ CachedPerson {+ id: UNREMEDIABLE_PERSON_ID,+ properties: serde_json::json!({ "email": huge_email }),+ ..test_cached_person()+ },+ );+ let err = client+ .update_person_properties(with_partition(+ UpdatePersonPropertiesRequest {+ team_id: 1,+ person_id: UNREMEDIABLE_PERSON_ID,+ event_name: "$set".to_string(),+ set_properties: serde_json::to_vec(&serde_json::json!({"name": "x"})).unwrap(),+ set_once_properties: vec![],+ unset_properties: vec![],+ },+ unremediable_partition,+ ))+ .await+ .expect_err("an unremediable row's update must be rejected");+ assert_eq!(err.code(), tonic::Code::InvalidArgument);+ assert!(err.message().contains("trim target"));+ assert!(+ !err.message().contains("eee"),+ "the error must carry sizes, never property values"+ );++ // The first two enforcement actions emitted in-product warnings from+ // the leader: one rejection, one remediation trim.+ let consumer: BaseConsumer = ClientConfig::new()+ .set("bootstrap.servers", mock_cluster.bootstrap_servers())+ .set("group.id", "warnings-check")+ .create()+ .unwrap();+ let mut tpl = TopicPartitionList::new();+ tpl.add_partition_offset(+ "clickhouse_ingestion_warnings",+ 0,+ rdkafka::Offset::Beginning,+ )+ .unwrap();+ consumer.assign(&tpl).unwrap();+ let mut warnings = Vec::new();+ let deadline = Instant::now() + Duration::from_secs(10);+ while warnings.len() < 2 && Instant::now() < deadline {+ if let Some(Ok(message)) = consumer.poll(Duration::from_millis(200)) {+ let payload: serde_json::Value =+ serde_json::from_slice(message.payload().unwrap()).unwrap();+ assert_eq!(payload["type"], "person_properties_size_violation");+ assert_eq!(payload["source"], "personhog-leader");+ // The pipeline's canonical shape: a ClickHouse-format+ // timestamp, and category/severity in details (the v2 table+ // materializes columns from those exact keys).+ let timestamp = payload["timestamp"].as_str().unwrap();+ assert!(+ timestamp.len() == 23 && timestamp.as_bytes()[10] == b' ',+ "timestamp must be ClickHouse-format, got {timestamp}"+ );+ let details: serde_json::Value =+ serde_json::from_str(payload["details"].as_str().unwrap()).unwrap();+ assert_eq!(details["category"], "size");+ assert_eq!(details["severity"], "error");+ assert_eq!(details["pipelineStep"], "personhog_admission");+ assert!(+ details["personId"].as_str().unwrap().contains('-'),+ "personId is the uuid"+ );+ warnings.push(payload["details"].as_str().unwrap().to_string());+ }+ }+ assert_eq!(+ warnings.len(),+ 2,+ "expected a trim warning and a reject warning"+ );+ assert!(warnings.iter().any(|w| w.contains("trimmed")));+ assert!(warnings.iter().any(|w| w.contains("rejected")));++ // Team 1's (team, type) budget is exhausted: another enforcement+ // action still rejects, but its warning is suppressed. A fresh+ // team's warning still emits, and — the warnings topic being a+ // single partition — arriving as the very next message proves the+ // suppressed one was never produced.+ const TEAM_2_PERSON_ID: i64 = 11;+ let team2_partition = partition_for_person(2, TEAM_2_PERSON_ID, NUM_PARTITIONS);+ if team2_partition != routing_partition {+ cache.create_partition(team2_partition);+ }+ seed_person(+ &cache,+ team2_partition,+ CachedPerson {+ id: TEAM_2_PERSON_ID,+ team_id: 2,+ ..test_cached_person()+ },+ );++ let oversized_update = serde_json::to_vec(&serde_json::json!({+ "email": "[email protected]", "custom_y": big, "custom_z": big,+ }))+ .unwrap();+ client+ .update_person_properties(with_partition(+ UpdatePersonPropertiesRequest {+ team_id: 1,+ person_id: PERSON_ID,+ event_name: "$set".to_string(),+ set_properties: oversized_update.clone(),+ set_once_properties: vec![],+ unset_properties: vec![],+ },+ routing_partition,+ ))+ .await+ .expect_err("throttling gates the warning, not the enforcement");++ client+ .update_person_properties(with_partition(+ UpdatePersonPropertiesRequest {+ team_id: 2,+ person_id: TEAM_2_PERSON_ID,+ event_name: "$set".to_string(),+ set_properties: oversized_update,+ set_once_properties: vec![],+ unset_properties: vec![],+ },+ team2_partition,+ ))+ .await+ .expect_err("team 2's newly violating update is rejected too");++ let deadline = Instant::now() + Duration::from_secs(10);+ let next = loop {+ match consumer.poll(Duration::from_millis(200)) {+ Some(Ok(message)) => break message,+ _ => assert!(Instant::now() < deadline, "team 2's warning must arrive"),+ }+ };+ let payload: serde_json::Value = serde_json::from_slice(next.payload().unwrap()).unwrap();+ assert_eq!(+ payload["team_id"], 2,+ "team 1's third warning must be suppressed by the throttle"+ );++ // NUL bytes are sanitized at admission (`\u{0000}` → `\u{FFFD}`,+ // matching the Node pipeline): Postgres jsonb refuses NUL, so an+ // unsanitized record would be unapplyable by the writer. The stored+ // state — response and strong read alike — carries the sanitized form.+ let response = client+ .update_person_properties(with_partition(+ UpdatePersonPropertiesRequest {+ team_id: 1,+ person_id: PERSON_ID,+ event_name: "$set".to_string(),+ set_properties: serde_json::to_vec(&serde_json::json!({+ "nul\u{0000}key": "nul\u{0000}value",+ }))+ .unwrap(),+ set_once_properties: vec![],+ unset_properties: vec![],+ },+ routing_partition,+ ))+ .await+ .unwrap()+ .into_inner();+ assert!(response.updated);+ let stored: serde_json::Value =+ serde_json::from_slice(&response.person.unwrap().properties).unwrap();+ let stored = stored.as_object().unwrap();+ assert_eq!(stored["nul\u{FFFD}key"], "nul\u{FFFD}value");+ assert!(!stored.contains_key("nul\u{0000}key"));++ let read = client+ .get_person(with_partition(+ GetPersonRequest {+ team_id: 1,+ person_id: PERSON_ID,+ read_options: None,+ },+ routing_partition,+ ))+ .await+ .unwrap()+ .into_inner();+ let read_person = read.person.unwrap();+ let read_props: serde_json::Value = serde_json::from_slice(&read_person.properties).unwrap();+ assert_eq!(read_props["nul\u{FFFD}key"], "nul\u{FFFD}value");+ let version_after_nul = read_person.version;++ // Resending the identical NUL-bearing update must hit the no-change+ // fast path: inputs are sanitized before diffing, so the raw NUL form+ // compares equal to its stored U+FFFD form instead of producing a+ // fresh record and version bump on every repeat.+ let response = client+ .update_person_properties(with_partition(+ UpdatePersonPropertiesRequest {+ team_id: 1,+ person_id: PERSON_ID,+ event_name: "$set".to_string(),+ set_properties: serde_json::to_vec(&serde_json::json!({+ "nul\u{0000}key": "nul\u{0000}value",+ }))+ .unwrap(),+ set_once_properties: vec![],+ unset_properties: vec![],+ },+ routing_partition,+ ))+ .await+ .unwrap()+ .into_inner();+ assert!(+ !response.updated,+ "a sanitized repeat must be detected as a no-op"+ );+ assert_eq!(+ response.person.unwrap().version,+ version_after_nul,+ "a no-op repeat must not bump the version"+ );++ cancel.cancel();+}diff --git a/rust/personhog-writer/Cargo.toml b/rust/personhog-writer/Cargo.tomlindex c31a7ad75376..c59b18d4a7b8 100644--- a/rust/personhog-writer/Cargo.toml+++ b/rust/personhog-writer/Cargo.toml@@ -29,6 +29,7 @@ uuid = { workspace = true }[dev-dependencies]health = { path = "../common/health" }+personhog-common = { path = "../personhog-common" }tokio = { workspace = true, features = ["test-util"] }[lints]diff --git a/rust/personhog-writer/README.md b/rust/personhog-writer/README.mdindex 53de6310475d..6b65f72fb937 100644--- a/rust/personhog-writer/README.md+++ b/rust/personhog-writer/README.md@@ -15,36 +15,31 @@ personhog_updates (Kafka, compacted)│ ┌────────────────┐ ┌───────────────────┐ ││ │ Kafka recv │ │ PG batch upsert │ ││ │ Proto decode │────────│ Per-row fallback │ │-│ │ Buffer dedup │ channel│ Property trimming │ │-│ │ Flush triggers │ │ Offset commit │ │-│ └────────────────┘ └───────────────────┘ │-│ │ │-│ ▼ │-│ ┌───────────────────┐ │-│ │ Warnings Producer │ │-│ │ (ingestion warns) │ │-│ └───────────────────┘ │+│ │ Buffer dedup │ channel│ Offset commit │ │+│ │ Flush triggers │ └───────────────────┘ │+│ └────────────────┘ │└──────────────────────────────────────────────────────┘- │ │- ▼ ▼-personhog_person_tmp (PG) client_iwarnings_ingestion (Kafka)+ │+ ▼+personhog_person_tmp (PG)```The service runs two concurrent tokio tasks connected by a bounded channel:- **Consumer task**: reads from Kafka, decodes Person protobuf messages, deduplicates in an in-memory buffer keyed by (team_id, person_id), and sends batches to the writer task on flush triggers.-- **Writer task**: receives batches, upserts to Postgres via `INSERT ... ON CONFLICT`, handles errors with per-row fallback and property trimming, commits Kafka offsets only after a successful write, and emits ingestion warnings for user-facing visibility.+- **Writer task**: receives batches, upserts to Postgres via `INSERT ... ON CONFLICT`, isolates failures with per-row fallback, and commits Kafka offsets only after every row in the flush has been applied.++The writer is a pure applier: the leader admits every record against this service's exact rejection surface (the `pg_column_size` measure, jsonb content rules, bindability of every column) before acking, so everything on the topic applies verbatim. The writer never corrects, trims, or skips — any writer-side edit or drop would permanently diverge Postgres from the leader's cache and changelog, because every later snapshot for the person builds on the same state.## Code organization| Module | Responsibility ||--------|---------------|-| `kafka.rs` | Kafka consumer (`PersonConsumer`) and warnings producer (`WarningsProducer`). Owns all Kafka config construction. |+| `kafka.rs` | Kafka consumer (`PersonConsumer`). Owns all Kafka config construction. || `consumer.rs` | Consumer loop: recv, decode, buffer, flush triggers, backpressure. || `writer.rs` | Writer loop: batch dispatch, retry orchestration, offset commit. Generic over `PersonStore` for testability. |-| `store.rs` | Batch orchestration: parallel chunk execution, outcome partitioning, per-row fallback with property trimming. Defines the `PersonDb` trait; holds `Arc<D: PersonDb>`. |+| `store.rs` | Batch orchestration: parallel chunk execution, outcome partitioning, per-row violation isolation. Defines the `PersonDb` trait; holds `Arc<D: PersonDb>`. || `pg.rs` | PG implementation of `PersonDb`: UNNEST-based chunk upsert, single-row upsert, type conversion, sqlx error classification. |-| `properties.rs` | Property trimming algorithm matching the Node.js pipeline. Protected properties list. || `buffer.rs` | In-memory dedup buffer keyed by (team_id, person_id), keeps highest version. || `config.rs` | Envconfig-based configuration. |@@ -61,7 +56,7 @@ The consumer flushes the buffer when any of these conditions are met:The upsert uses `WHERE EXCLUDED.version > COALESCE(table.version, -1)`, so out-of-order or replayed messages from Kafka are safely ignored. The `COALESCE` handles nullable version columns (existing rows with NULL version will accept any update).-Persons with invalid UUIDs are filtered out before the batch INSERT to prevent unique constraint violations from multiple nil UUIDs in the same batch.+A person whose fields cannot be bound losslessly (malformed uuid, `team_id` beyond the column's integer range, non-UTF-8 JSON bytes, out-of-range timestamp) fails its chunk as a `Data` error rather than being silently dropped or repaired; the per-row pass then isolates it as an invariant violation (see below).## Error handling@@ -69,14 +64,14 @@ Failures are handled at chunk granularity: the store splits each batch into chun- **Transient** (connection loss, pool timeout, deadlock): retry just the failed chunks with exponential backoff (1s, 2s, 4s). Successful chunks are not re-executed. After 3 consecutive failures, signal unhealthy and shut down.- **Data** (constraint violation, invalid input): fall back to per-row inserts for the failed chunks' rows, isolating the bad records. Per-row upserts run with bounded concurrency (`ROW_FALLBACK_CONCURRENCY`). Successful chunks are not re-executed.-- **Properties size violation**: trim non-protected properties alphabetically until under 512KB, then retry. If untrimable (only protected properties exceed the limit), skip the row and emit an ingestion warning.+- **Non-transient row failure** (constraint violation, unbindable field): an invariant violation — the leader admitted a record Postgres cannot apply, so admission has a gap. The flush halts via `signal_failure` without committing; Kafka redelivers after restart, and the alarm stands until the gap is fixed. Skipping is never an option: it would permanently diverge PG from the cache and changelog.- **Chunk task panic**: a spawned chunk task that panics cannot hand its persons back — the task's stack is unwound. The writer treats this as a fatal error, signals failure, and exits. Because Kafka offsets are committed only on full batch success, redelivery after restart recovers the records; the panic payload is captured in the error message for diagnosis.-Ingestion warnings are produced to the `client_iwarnings_ingestion` Kafka topic so users see property size violations in-product. The producer is fire-and-forget (enqueued into rdkafka's internal buffer) to avoid blocking the write path, with a flush on graceful shutdown.+User-facing size warnings are emitted by the leader at admission time, where the client also gets synchronous feedback; the writer emits none.## JSON handling-The leader serializes person properties via `serde_json::RawValue` into proto bytes, which are already valid JSON. The writer passes these through as `text[]` in the UNNEST query and lets PostgreSQL cast `::jsonb`, avoiding unnecessary parse/serialize cycles on the hot path. JSON is only parsed in the error path when property trimming is needed.+The leader serializes a parsed `serde_json::Value` into proto bytes, so they are valid JSON by construction. The writer passes them through as `text[]` in the UNNEST query and lets PostgreSQL cast `::jsonb` — it never parses JSON itself. The `tests/admission_weld.rs` suite welds the leader's admission functions to this exact statement against a live Postgres.## Backpressure@@ -94,17 +89,15 @@ When the writer is slow (PG latency, connection pool exhaustion), the bounded ch|--------|------|-------------|| `personhog_writer_messages_consumed_total` | counter | Messages decoded from Kafka || `personhog_writer_decode_errors_total` | counter | Proto decode failures |-| `personhog_writer_invalid_uuid_total` | counter | Persons skipped due to invalid UUIDs |-| `personhog_writer_invalid_team_id_total` | counter | Persons skipped because `team_id` exceeds i32 range |-| `personhog_writer_invalid_json_total` | counter | Non-UTF8 JSON fields defaulted || `personhog_writer_kafka_errors_total` | counter | Kafka recv errors || `personhog_writer_flushes_total` | counter | Total flush events || `personhog_writer_flushes_by_trigger_total{trigger}` | counter | Flush trigger breakdown (timer, size, backpressure, shutdown) || `personhog_writer_rows_upserted_total{mode}` | counter | Rows PG reported as affected (mode: chunk, row) || `personhog_writer_rows_version_skipped_total{mode}` | counter | Rows skipped by version guard (mode: chunk, row) |-| `personhog_writer_rows_skipped_total` | counter | Rows skipped due to per-row errors || `personhog_writer_upsert_errors_total{mode}` | counter | PG write failures (mode: chunk, row) || `personhog_writer_batch_fallback_total` | counter | Batches that fell back to per-row |+| `personhog_writer_unbindable_field_total{field}` | counter | Rows whose field could not be bound losslessly (invariant violation) |+| `personhog_writer_unapplyable_rows_total{kind}` | counter | Rows PG refused non-transiently (invariant violation, halts the flush) || `personhog_writer_chunk_fallback_rows_total` | counter | Rows from data-failed chunks sent to per-row fallback || `personhog_writer_chunk_retry_rows_total` | counter | Rows from transient-failed chunks retried as a batch || `personhog_writer_chunk_fatal_total` | counter | Chunk tasks that panicked or were cancelled |@@ -112,9 +105,6 @@ When the writer is slow (PG latency, connection pool exhaustion), the bounded ch| `personhog_writer_row_fallback_in_flight` | gauge | Concurrent per-row upserts in flight during fallback || `personhog_writer_pg_pool_size` | gauge | Total sqlx pool connections (sampled every 5s) || `personhog_writer_pg_pool_idle` | gauge | Idle sqlx pool connections (sampled every 5s) |-| `personhog_writer_properties_trimmed_total` | counter | Properties trimming attempted |-| `personhog_writer_properties_trimmed_writes_total` | counter | Rows written after trimming |-| `personhog_writer_ingestion_warnings_emitted_total` | counter | Warnings produced to Kafka || `personhog_writer_offset_commits_total` | counter | Successful offset commits || `personhog_writer_offset_commit_errors_total` | counter | Failed offset commits || `personhog_writer_flush_duration_seconds` | histogram | PG write latency per flush |@@ -137,7 +127,6 @@ Consumer lag per partition is monitored externally via KMinion (`kminion_kafka_c| `KAFKA_TOPIC` | `personhog_updates` | Topic to consume || `KAFKA_CONSUMER_GROUP` | `personhog-writer` | Consumer group ID || `KAFKA_CONSUMER_OFFSET_RESET` | `earliest` | Offset reset policy |-| `KAFKA_INGESTION_WARNINGS_TOPIC` | `client_iwarnings_ingestion` | Topic for ingestion warnings || `DATABASE_URL` | (required) | Postgres connection string || `PG_MAX_CONNECTIONS` | `20` | Connection pool size || `PG_TARGET_TABLE` | `personhog_person_tmp` | Target table (`posthog_person` for production cutover) |diff --git a/rust/personhog-writer/src/config.rs b/rust/personhog-writer/src/config.rsindex 93625d1789e6..8a83c1b63953 100644--- a/rust/personhog-writer/src/config.rs+++ b/rust/personhog-writer/src/config.rs@@ -57,29 +57,11 @@ pub struct Config {#[envconfig(default = "16")]pub row_fallback_concurrency: usize,- /// Raw-bytes threshold for the properties field above which a person- /// is trimmed preflight (before the batch upsert). Matches the PG- /// `check_properties_size` constraint; trimmed persons rejoin the- /// main batch so a single oversized row can't torpedo the whole write.- #[envconfig(default = "655360")]- pub properties_size_threshold: usize,-- /// Target raw-bytes size to trim oversized properties down to. Should- /// be comfortably below `properties_size_threshold` so the trim result- /// definitely fits the PG constraint even if JSONB encoding inflates- /// the stored size relative to the raw JSON we trimmed.- #[envconfig(default = "524288")]- pub properties_trim_target: usize,-/// Channel capacity between consumer and writer tasks./// Higher values allow more buffered batches but use more memory.#[envconfig(default = "8")]pub flush_channel_capacity: usize,- // ── Ingestion warnings ────────────────────────────────────────- #[envconfig(default = "client_iwarnings_ingestion")]- pub kafka_ingestion_warnings_topic: String,-// ── Service ──────────────────────────────────────────────────#[envconfig(default = "9103")]pub metrics_port: u16,diff --git a/rust/personhog-writer/src/kafka.rs b/rust/personhog-writer/src/kafka.rsindex 646c03b28d78..9adca5b80e7f 100644--- a/rust/personhog-writer/src/kafka.rs+++ b/rust/personhog-writer/src/kafka.rs@@ -1,16 +1,9 @@use std::collections::HashMap;-use std::time::Duration;use common_kafka::config::KafkaConfig;-use common_kafka::kafka_producer::KafkaContext;-use metrics::counter;use rdkafka::consumer::{CommitMode, Consumer, StreamConsumer};use rdkafka::message::BorrowedMessage;-use rdkafka::producer::{FutureProducer, FutureRecord, Producer};use rdkafka::{ClientConfig, TopicPartitionList};-use tracing::warn;--use crate::store::IngestionWarning;// ── Consumer ────────────────────────────────────────────────────@@ -97,63 +90,3 @@ impl PersonConsumer {&self.topic}}--// ── Warnings producer ───────────────────────────────────────────--/// Produces ingestion warnings to Kafka so users see property size-/// violations in-product.-pub struct WarningsProducer {- producer: FutureProducer<KafkaContext>,- topic: String,-}--impl WarningsProducer {- pub fn new(producer: FutureProducer<KafkaContext>, topic: String) -> Self {- Self { producer, topic }- }-- /// Enqueue an ingestion warning into rdkafka's internal buffer.- /// Fire-and-forget: rdkafka handles retries and delivery in the- /// background. Call `flush()` on shutdown to drain pending messages.- pub fn emit(&self, warning: &IngestionWarning) {- let now = std::time::SystemTime::now()- .duration_since(std::time::UNIX_EPOCH)- .unwrap_or_default()- .as_secs();-- let details = serde_json::json!({- "personId": warning.person_id.to_string(),- "teamId": warning.team_id,- "message": warning.message,- });-- let payload = serde_json::json!({- "team_id": warning.team_id,- "type": "person_properties_size_violation",- "source": "personhog-writer",- "details": details.to_string(),- "timestamp": now.to_string(),- });-- let payload_bytes = serde_json::to_vec(&payload).unwrap_or_default();- let key = warning.team_id.to_string();- let record = FutureRecord::to(&self.topic)- .payload(&payload_bytes)- .key(&key);-- match self.producer.send_result(record) {- Ok(_future) => {- counter!("personhog_writer_ingestion_warnings_emitted_total").increment(1);- }- Err((e, _)) => {- warn!(error = %e, "failed to enqueue ingestion warning");- }- }- }-- /// Flush any buffered messages, waiting up to the given timeout for- /// delivery. Called during graceful shutdown.- pub fn flush(&self, timeout: Duration) {- self.producer.flush(timeout).ok();- }-}diff --git a/rust/personhog-writer/src/lib.rs b/rust/personhog-writer/src/lib.rsindex 53c8db105137..3997678bd150 100644--- a/rust/personhog-writer/src/lib.rs+++ b/rust/personhog-writer/src/lib.rs@@ -4,6 +4,5 @@ pub mod consumer;pub mod error;pub mod kafka;pub mod pg;-pub mod properties;pub mod store;pub mod writer;diff --git a/rust/personhog-writer/src/main.rs b/rust/personhog-writer/src/main.rsindex a9dfeeed44c6..3d473151664f 100644--- a/rust/personhog-writer/src/main.rs+++ b/rust/personhog-writer/src/main.rs@@ -13,11 +13,10 @@ use tracing_subscriber::layer::SubscriberExt;use tracing_subscriber::util::SubscriberInitExt;use tracing_subscriber::EnvFilter;-use common_kafka::kafka_producer::create_kafka_producer;use personhog_writer::buffer::PersonBuffer;use personhog_writer::config::Config;use personhog_writer::consumer::ConsumerTask;-use personhog_writer::kafka::{PersonConsumer, WarningsProducer};+use personhog_writer::kafka::PersonConsumer;use personhog_writer::pg::PgStore;use personhog_writer::store::PersonWriteStore;use personhog_writer::writer::WriterTask;@@ -137,23 +136,6 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {)?);tracing::info!("Subscribed to Kafka topic: {}", config.kafka_topic);- // Ingestion warnings producer- let warnings_producer = create_kafka_producer(&config.kafka, writer_handle.clone())- .await- .map(|producer| {- WarningsProducer::new(producer, config.kafka_ingestion_warnings_topic.clone())- })- .ok();-- if warnings_producer.is_some() {- tracing::info!(- "Ingestion warnings enabled (topic: {})",- config.kafka_ingestion_warnings_topic- );- } else {- tracing::warn!("Ingestion warnings disabled (Kafka producer creation failed)");- }-// Writer tasklet pg_store = PgStore::new(pool, config.pg_target_table.clone());let store = PersonWriteStore::new(@@ -161,17 +143,9 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {personhog_writer::store::StoreConfig {chunk_size: config.upsert_batch_size,row_fallback_concurrency: config.row_fallback_concurrency,- properties_size_threshold: config.properties_size_threshold,- properties_trim_target: config.properties_trim_target,},);- let writer_task = WriterTask::new(- Arc::clone(&kafka_consumer),- store,- flush_rx,- writer_handle,- warnings_producer,- );+ let writer_task = WriterTask::new(Arc::clone(&kafka_consumer), store, flush_rx, writer_handle);tokio::spawn(async move {writer_task.run().await;diff --git a/rust/personhog-writer/src/pg.rs b/rust/personhog-writer/src/pg.rsindex 3343c9d49cf7..7fc89da60c42 100644--- a/rust/personhog-writer/src/pg.rs+++ b/rust/personhog-writer/src/pg.rs@@ -1,9 +1,12 @@use async_trait::async_trait;+use std::str::from_utf8;+use chrono::{DateTime, TimeZone, Utc};use metrics::counter;use personhog_proto::personhog::types::v1::Person;use sqlx::postgres::PgPool;-use tracing::{error, warn};+use tracing::error;+use uuid::Uuid;use crate::error::{WriteError, WriteErrorKind};use crate::store::PersonDb;@@ -22,18 +25,12 @@ pub struct PgStore {#[async_trait]impl PersonDb for PgStore {async fn execute_chunk(&self, chunk: &[Person]) -> Result<(), WriteError> {- let arrays = prepare_chunk(chunk);+ let arrays = prepare_chunk(chunk)?;run_upsert(&self.pool, &self.upsert_sql, &arrays, "chunk").await}- async fn execute_row(- &self,- person: &Person,- properties_override: Option<&str>,- ) -> Result<(), WriteError> {- let Some(arrays) = prepare_single(person, properties_override) else {- return Ok(()); // Invalid input, already logged- };+ async fn execute_row(&self, person: &Person) -> Result<(), WriteError> {+ let arrays = prepare_single(person)?;run_upsert(&self.pool, &self.upsert_sql, &arrays, "row").await}}@@ -81,109 +78,74 @@ impl PgStore {/// Build bind arrays from a slice of persons. Borrows string data directly/// from each Person's byte buffers; `PreparedArrays` is tied to the slice's/// lifetime and must not outlive `persons`.-fn prepare_chunk(persons: &[Person]) -> PreparedArrays<'_> {+///+/// Any field that cannot be bound losslessly (malformed uuid, team_id+/// beyond the column's `integer` range, non-UTF-8 JSON bytes, timestamp+/// outside chrono's range) is a `Data` error: the record is unapplyable+/// as produced, which post-admission is an invariant violation the caller+/// must halt on. Nothing is ever dropped or substituted here — a silent+/// repair would diverge PG from the cache and changelog.+fn prepare_chunk(persons: &[Person]) -> Result<PreparedArrays<'_>, WriteError> {let cap = persons.len();let mut arrays = PreparedArrays::with_capacity(cap);-- for p in persons {- let uuid = match uuid::Uuid::parse_str(&p.uuid) {- Ok(u) => u,- Err(e) => {- counter!("personhog_writer_invalid_uuid_total").increment(1);- warn!(- team_id = p.team_id,- person_id = p.id,- uuid = %p.uuid,- error = %e,- "skipping person with invalid UUID"- );- continue;- }- };-- let team_id = match i32::try_from(p.team_id) {- Ok(t) => t,- Err(_) => {- counter!("personhog_writer_invalid_team_id_total").increment(1);- warn!(- team_id = p.team_id,- person_id = p.id,- "skipping person with out-of-range team_id (exceeds i32)"- );- continue;- }- };-- arrays.push(- p.id,- team_id,- uuid,- bytes_to_json_str(&p.properties, "{}"),- bytes_to_optional_json_str(&p.properties_last_updated_at),- bytes_to_optional_json_str(&p.properties_last_operation),- epoch_secs_to_datetime(p.created_at),- Some(p.version),- p.is_identified,- p.last_seen_at.map(epoch_secs_to_datetime),- );+ for person in persons {+ push_person(&mut arrays, person)?;}-- arrays+ Ok(arrays)}-/// Build a single-row PreparedArrays for the per-row path. Returns None if-/// the person has an invalid UUID (already logged).-fn prepare_single<'a>(- person: &'a Person,- properties_override: Option<&'a str>,-) -> Option<PreparedArrays<'a>> {- let uuid = match uuid::Uuid::parse_str(&person.uuid) {- Ok(u) => u,- Err(e) => {- counter!("personhog_writer_invalid_uuid_total").increment(1);- warn!(- team_id = person.team_id,- person_id = person.id,- uuid = %person.uuid,- error = %e,- "skipping person with invalid UUID"- );- return None;- }- };+/// Build a single-row `PreparedArrays` for the per-row path.+fn prepare_single(person: &Person) -> Result<PreparedArrays<'_>, WriteError> {+ let mut arrays = PreparedArrays::with_capacity(1);+ push_person(&mut arrays, person)?;+ Ok(arrays)+}- let team_id = match i32::try_from(person.team_id) {- Ok(t) => t,- Err(_) => {- counter!("personhog_writer_invalid_team_id_total").increment(1);- warn!(- team_id = person.team_id,- person_id = person.id,- "skipping person with out-of-range team_id (exceeds i32)"- );- return None;+fn push_person<'a>(arrays: &mut PreparedArrays<'a>, p: &'a Person) -> Result<(), WriteError> {+ let unbindable = |field: &str, detail: String| {+ counter!("personhog_writer_unbindable_field_total", "field" => field.to_string())+ .increment(1);+ WriteError {+ message: format!(+ "unbindable {field} for team_id={} person_id={}: {detail}",+ p.team_id, p.id+ ),+ kind: WriteErrorKind::Data,}};- let properties = match properties_override {- Some(s) => s,- None => bytes_to_json_str(&person.properties, "{}"),+ let uuid = Uuid::parse_str(&p.uuid).map_err(|e| unbindable("uuid", e.to_string()))?;+ let team_id = i32::try_from(p.team_id)+ .map_err(|_| unbindable("team_id", "exceeds the column's integer range".to_string()))?;+ let properties =+ bytes_to_json_str(&p.properties, "{}").map_err(|e| unbindable("properties", e))?;+ let properties_last_updated_at = bytes_to_optional_json_str(&p.properties_last_updated_at)+ .map_err(|e| unbindable("properties_last_updated_at", e))?;+ let properties_last_operation = bytes_to_optional_json_str(&p.properties_last_operation)+ .map_err(|e| unbindable("properties_last_operation", e))?;+ let created_at = epoch_secs_to_datetime(p.created_at)+ .ok_or_else(|| unbindable("created_at", format!("epoch {} out of range", p.created_at)))?;+ let last_seen_at = match p.last_seen_at {+ None => None,+ Some(secs) => Some(+ epoch_secs_to_datetime(secs)+ .ok_or_else(|| unbindable("last_seen_at", format!("epoch {secs} out of range")))?,+ ),};- let mut arrays = PreparedArrays::with_capacity(1);arrays.push(- person.id,+ p.id,team_id,uuid,properties,- bytes_to_optional_json_str(&person.properties_last_updated_at),- bytes_to_optional_json_str(&person.properties_last_operation),- epoch_secs_to_datetime(person.created_at),- Some(person.version),- person.is_identified,- person.last_seen_at.map(epoch_secs_to_datetime),+ properties_last_updated_at,+ properties_last_operation,+ created_at,+ Some(p.version),+ p.is_identified,+ last_seen_at,);- Some(arrays)+ Ok(())}async fn run_upsert(@@ -270,10 +232,11 @@ fn classify_error(e: &sqlx::Error) -> WriteErrorKind {/// Column-oriented bind arrays for the upsert statement. String fields/// borrow from each Person's byte buffer to avoid per-row allocations; the/// struct's lifetime is tied to the source slice.+#[derive(Debug)]struct PreparedArrays<'a> {ids: Vec<i64>,team_ids: Vec<i32>,- uuids: Vec<uuid::Uuid>,+ uuids: Vec<Uuid>,properties: Vec<&'a str>,properties_last_updated_at: Vec<Option<&'a str>>,properties_last_operation: Vec<Option<&'a str>>,@@ -304,7 +267,7 @@ impl<'a> PreparedArrays<'a> {&mut self,id: i64,team_id: i32,- uuid: uuid::Uuid,+ uuid: Uuid,properties: &'a str,properties_last_updated_at: Option<&'a str>,properties_last_operation: Option<&'a str>,@@ -328,43 +291,29 @@ impl<'a> PreparedArrays<'a> {}}-/// Interpret proto bytes as a JSON string. The leader serializes via-/// serde_json::RawValue, so these are already valid JSON UTF-8. We pass-/// them through to PG as text and let the `::jsonb` cast validate. Returns-/// a borrow into `bytes`; on invalid UTF-8 or empty input, the static-/// default (coerces to any lifetime).-fn bytes_to_json_str<'a>(bytes: &'a [u8], default: &'static str) -> &'a str {+/// Interpret proto bytes as a JSON string. The leader serializes a parsed+/// `serde_json::Value`, so these are valid JSON UTF-8 by construction; the+/// `::jsonb` cast in the statement re-validates at PG. Empty bytes are the+/// proto default and decode to `default`. Invalid UTF-8 is an error, never+/// a substitution.+fn bytes_to_json_str<'a>(bytes: &'a [u8], default: &'static str) -> Result<&'a str, String> {if bytes.is_empty() {- return default;- }- match std::str::from_utf8(bytes) {- Ok(s) => s,- Err(e) => {- counter!("personhog_writer_invalid_json_total").increment(1);- warn!(error = %e, "non-UTF8 in JSON field, using default");- default- }+ return Ok(default);}+ from_utf8(bytes).map_err(|e| format!("non-UTF-8 JSON bytes: {e}"))}-fn bytes_to_optional_json_str(bytes: &[u8]) -> Option<&str> {+fn bytes_to_optional_json_str(bytes: &[u8]) -> Result<Option<&str>, String> {if bytes.is_empty() {- return None;- }- match std::str::from_utf8(bytes) {- Ok(s) => Some(s),- Err(e) => {- counter!("personhog_writer_invalid_json_total").increment(1);- warn!(error = %e, "non-UTF8 in optional JSON field, treating as null");- None- }+ return Ok(None);}+ from_utf8(bytes)+ .map(Some)+ .map_err(|e| format!("non-UTF-8 JSON bytes: {e}"))}-fn epoch_secs_to_datetime(epoch_secs: i64) -> DateTime<Utc> {- Utc.timestamp_opt(epoch_secs, 0)- .single()- .unwrap_or_default()+fn epoch_secs_to_datetime(epoch_secs: i64) -> Option<DateTime<Utc>> {+ Utc.timestamp_opt(epoch_secs, 0).single()}#[cfg(test)]@@ -390,31 +339,36 @@ mod tests {#[test]fn bytes_to_json_str_valid() {- let s = bytes_to_json_str(b"{\"email\":\"[email protected]\"}", "{}");+ let s = bytes_to_json_str(b"{\"email\":\"[email protected]\"}", "{}").unwrap();assert_eq!(s, "{\"email\":\"[email protected]\"}");}#[test]fn bytes_to_json_str_empty_returns_default() {- let s = bytes_to_json_str(b"", "{}");- assert_eq!(s, "{}");+ assert_eq!(bytes_to_json_str(b"", "{}").unwrap(), "{}");+ }++ #[test]+ fn bytes_to_json_str_rejects_invalid_utf8() {+ assert!(bytes_to_json_str(&[0xff, 0xfe], "{}").is_err());}#[test]fn bytes_to_optional_json_str_empty_returns_none() {- assert!(bytes_to_optional_json_str(b"").is_none());+ assert!(bytes_to_optional_json_str(b"").unwrap().is_none());}#[test]fn bytes_to_optional_json_str_valid() {- let s = bytes_to_optional_json_str(b"{\"key\":\"val\"}");+ let s = bytes_to_optional_json_str(b"{\"key\":\"val\"}").unwrap();assert_eq!(s.unwrap(), "{\"key\":\"val\"}");}#[test]fn epoch_secs_conversion() {- let dt = epoch_secs_to_datetime(1700000000);+ let dt = epoch_secs_to_datetime(1700000000).unwrap();assert_eq!(dt.timestamp(), 1700000000);+ assert!(epoch_secs_to_datetime(i64::MAX).is_none());}#[tokio::test]@@ -435,27 +389,31 @@ mod tests {Person {id,team_id,- uuid: uuid::Uuid::new_v4().to_string(),+ uuid: Uuid::new_v4().to_string(),version: 1,..Default::default()}}#[test]- fn prepare_chunk_skips_out_of_range_team_id() {+ fn prepare_chunk_errors_on_out_of_range_team_id() {+ // One unbindable row fails the whole chunk: silently dropping it+ // would permanently diverge PG from the cache and changelog.let good = person_with(1, 42);let bad = person_with(2, (i32::MAX as i64) + 1);let persons = [good, bad];- let arrays = prepare_chunk(&persons);- // Only the in-range person made it into the bind arrays.- assert_eq!(arrays.ids, vec![1]);- assert_eq!(arrays.team_ids, vec![42]);+ let err = prepare_chunk(&persons).expect_err("unbindable row must error");+ assert!(matches!(err.kind, WriteErrorKind::Data));+ assert!(err.message.contains("team_id"));}#[test]- fn prepare_single_rejects_out_of_range_team_id() {- let bad = person_with(1, (i32::MAX as i64) + 1);- assert!(prepare_single(&bad, None).is_none());+ fn prepare_single_errors_on_malformed_uuid() {+ let mut bad = person_with(1, 42);+ bad.uuid = "not-a-uuid".to_string();+ let err = prepare_single(&bad).expect_err("malformed uuid must error");+ assert!(matches!(err.kind, WriteErrorKind::Data));+ assert!(err.message.contains("uuid"));}}diff --git a/rust/personhog-writer/src/properties.rs b/rust/personhog-writer/src/properties.rsdeleted file mode 100644index 24a84ac99023..000000000000--- a/rust/personhog-writer/src/properties.rs+++ /dev/null@@ -1,241 +0,0 @@-use std::collections::HashSet;-use std::sync::LazyLock;--use metrics::counter;-use tracing::debug;--/// Properties that must never be trimmed, matching the Node.js ingestion-/// pipeline's `ALL_PROTECTED_PROPERTIES` in `person-property-utils.ts`.-static PROTECTED_PROPERTIES: LazyLock<HashSet<&'static str>> = LazyLock::new(|| {- HashSet::from([- // Core person properties- "email",- "name",- // Event-to-person properties (mobile)- "$app_build",- "$app_name",- "$app_namespace",- "$app_version",- // Event-to-person properties (web)- "$browser",- "$browser_version",- "$device_type",- "$current_url",- "$pathname",- "$os",- "$os_name",- "$os_version",- "$referring_domain",- "$referrer",- "$screen_height",- "$screen_width",- "$viewport_height",- "$viewport_width",- "$raw_user_agent",- // UTM and campaign tracking- "utm_source",- "utm_medium",- "utm_campaign",- "utm_content",- "utm_name",- "utm_term",- "gclid",- "gad_source",- "gclsrc",- "dclid",- "gbraid",- "wbraid",- "fbclid",- "msclkid",- "twclid",- "li_fat_id",- "mc_cid",- "igshid",- "ttclid",- "rdt_cid",- "irclid",- "_kx",- "epik",- "qclid",- "sccid",- // Session and page tracking- "$session_id",- "$window_id",- "$pageview_id",- "$host",- // Identity and device tracking- "$user_id",- "$device_id",- "$anon_distinct_id",- // Initial/first-touch properties- "$initial_referrer",- "$initial_referring_domain",- "$initial_utm_source",- "$initial_utm_medium",- "$initial_utm_campaign",- "$initial_utm_content",- "$initial_utm_term",- ])-});--/// Returns true if the property can be trimmed (is not protected).-pub fn can_trim_property(name: &str) -> bool {- !PROTECTED_PROPERTIES.contains(name)-}--/// Trim person properties to fit within the target size by removing-/// non-protected properties in alphabetical order.-///-/// Matches the Node.js `trimPropertiesToFitSize` algorithm:-/// 1. Sort all property keys alphabetically-/// 2. For each trimmable property, delete it and recalculate size-/// 3. Stop when under target size-///-/// Returns the trimmed properties and whether any trimming occurred.-pub fn trim_properties_to_fit_size(- properties: &serde_json::Value,- team_id: i64,- person_id: i64,- target_bytes: usize,-) -> Option<serde_json::Value> {- let map = properties.as_object()?;-- let json_str = serde_json::to_string(properties).ok()?;- let current_size = json_str.len();-- if current_size <= target_bytes {- return None; // Already fits, no trimming needed- }-- let mut trimmed = map.clone();- let mut keys: Vec<&String> = map.keys().collect();- keys.sort();-- let mut removed_count = 0;-- for key in keys {- if !can_trim_property(key) {- continue;- }-- trimmed.remove(key.as_str());- removed_count += 1;-- let new_size = serde_json::to_string(&trimmed)- .map(|s| s.len())- .unwrap_or(current_size);-- if new_size <= target_bytes {- break;- }- }-- let final_size = serde_json::to_string(&trimmed)- .map(|s| s.len())- .unwrap_or(0);-- // If trimmable keys were exhausted and the result still exceeds the- // target, the person can't fit — typically means protected properties- // alone are oversized. Signal this as `None` so the caller skips without- // attempting another doomed PG write.- if final_size > target_bytes {- debug!(- team_id,- person_id,- original_size = current_size,- final_size,- target_size = target_bytes,- properties_removed = removed_count,- final_property_count = trimmed.len(),- "person properties still exceed target after trimming all trimmable keys; giving up"- );- return None;- }-- debug!(- team_id,- person_id,- original_size = current_size,- final_size,- target_size = target_bytes,- properties_removed = removed_count,- final_property_count = trimmed.len(),- "trimmed person properties to fit size"- );-- counter!("personhog_writer_properties_trimmed_total").increment(1);-- Some(serde_json::Value::Object(trimmed))-}--#[cfg(test)]-mod tests {- use super::*;- use serde_json::json;-- #[test]- fn protected_properties_are_not_trimmable() {- assert!(!can_trim_property("email"));- assert!(!can_trim_property("$browser"));- assert!(!can_trim_property("utm_source"));- assert!(!can_trim_property("$user_id"));- assert!(!can_trim_property("$initial_referrer"));- }-- #[test]- fn custom_properties_are_trimmable() {- assert!(can_trim_property("custom_field"));- assert!(can_trim_property("my_property"));- assert!(can_trim_property("some_random_key"));- }-- #[test]- fn trim_returns_none_when_already_fits() {- let props = json!({"email": "[email protected]", "name": "Test"});- assert!(trim_properties_to_fit_size(&props, 1, 1, 1024).is_none());- }-- #[test]- fn trim_removes_custom_properties_alphabetically() {- // Small target so the test runs with small data.- let target = 1024;- let mut map = serde_json::Map::new();- map.insert("email".to_string(), json!("[email protected]")); // protected- map.insert("$browser".to_string(), json!("Chrome")); // protected-- // Add large custom properties that push us over the target.- let big_value = "x".repeat(500);- map.insert("aaa_custom".to_string(), json!(big_value.clone()));- map.insert("bbb_custom".to_string(), json!(big_value.clone()));- map.insert("ccc_custom".to_string(), json!(big_value));-- let props = serde_json::Value::Object(map);- let result = trim_properties_to_fit_size(&props, 1, 1, target);-- assert!(result.is_some());- let trimmed = result.unwrap();- let trimmed_map = trimmed.as_object().unwrap();-- // Protected properties are preserved- assert!(trimmed_map.contains_key("email"));- assert!(trimmed_map.contains_key("$browser"));-- // Custom properties are removed alphabetically until under target.- assert!(!trimmed_map.contains_key("aaa_custom"));- }-- #[test]- fn trim_returns_none_when_only_protected_keys_exceed_target() {- // If protected properties alone exceed the target, trim can't fit and- // signals failure via `None`. Caller skips straight to skipped.- let target = 1024;- let mut map = serde_json::Map::new();- let big_value = "x".repeat(2_000);- map.insert("email".to_string(), json!(big_value)); // protected, over target-- let props = serde_json::Value::Object(map);- let result = trim_properties_to_fit_size(&props, 1, 1, target);-- assert!(result.is_none());- }-}diff --git a/rust/personhog-writer/src/store.rs b/rust/personhog-writer/src/store.rsindex 054009fc2417..bb140323ddfd 100644--- a/rust/personhog-writer/src/store.rs+++ b/rust/personhog-writer/src/store.rs@@ -1,6 +1,6 @@//! Write store layer: orchestrates batch execution across parallel chunks,-//! handles per-row fallback with property trimming, and surfaces outcomes-//! as `BatchOutcome` (for batches) or `RowResult` (for single rows).+//! handles per-row fallback, and surfaces outcomes as `BatchOutcome` (for+//! batches) or `RowFallbackOutcome` (for the per-row isolation pass).//!//! The `PersonDb` trait abstracts the DB layer so orchestration can be//! unit-tested against a mock. `PgStore` in `pg.rs` is the production impl.@@ -11,7 +11,6 @@//! transient retry or per-row fallback. Both share the `WriteErrorKind`//! taxonomy from the DB layer.-use std::str::from_utf8;use std::sync::Arc;use std::time::Instant;@@ -20,13 +19,11 @@ use futures::stream::{self, StreamExt};use metrics::{counter, gauge, histogram};use personhog_proto::personhog::types::v1::Person;use tokio::task::{JoinError, JoinSet};-use tracing::{error, warn};+use tracing::error;// Re-exported so callers importing from `store::` keep working.pub use crate::error::{FatalError, WriteError, WriteErrorKind};-use crate::properties;-/// The database primitive the store layer orchestrates against. Implemented/// by `PgStore` for production and by mocks for testing.#[async_trait]@@ -34,13 +31,8 @@ pub trait PersonDb: Send + Sync {/// Execute a single upsert statement covering a chunk of persons.async fn execute_chunk(&self, chunk: &[Person]) -> Result<(), WriteError>;- /// Execute a single-row upsert. If `properties_override` is provided,- /// that JSON string is used instead of the person's proto bytes.- async fn execute_row(- &self,- person: &Person,- properties_override: Option<&str>,- ) -> Result<(), WriteError>;+ /// Execute a single-row upsert.+ async fn execute_row(&self, person: &Person) -> Result<(), WriteError>;}/// Outcome of a batch upsert. Reports which chunks (if any) need retry,@@ -60,20 +52,27 @@ pub enum BatchOutcome {Fatal(FatalError),}-/// Outcome of writing a single person.-#[derive(Debug)]-pub enum RowResult {- Written,- Trimmed(IngestionWarning),- Skipped(IngestionWarning),-}--/// Information needed to emit an ingestion warning.+/// A person Postgres cannot apply for a non-transient reason. The leader+/// admits every record against the writer's own rejection surface, so a+/// violation means admission has a gap — the writer refuses to commit past+/// it rather than skip (a skip would permanently diverge PG from the+/// cache and changelog, since every later snapshot for the person builds+/// on the same unapplyable state).#[derive(Debug)]-pub struct IngestionWarning {+pub struct RowViolation {pub team_id: i64,pub person_id: i64,- pub message: String,+ pub kind: WriteErrorKind,+}++/// Outcome of the per-row fallback pass over a data-failed chunk.+#[derive(Debug, Default)]+pub struct RowFallbackOutcome {+ /// Rows that failed transiently; the caller retries them with backoff.+ pub transient: Vec<Person>,+ /// Rows PG cannot apply — invariant violations that must halt the+ /// flush without committing.+ pub violations: Vec<RowViolation>,}/// Knobs that shape how the store batches, parallelizes, and trims. Scoped@@ -87,19 +86,15 @@ pub struct IngestionWarning {pub struct StoreConfig {pub chunk_size: usize,pub row_fallback_concurrency: usize,- pub properties_size_threshold: usize,- pub properties_trim_target: usize,}/// Production person write store. Splits batches into chunks, runs them in/// parallel against a `PersonDb`, partitions outcomes by failure class, and-/// handles per-row fallback with property trimming.+/// handles per-row fallback.pub struct PersonWriteStore<D: PersonDb> {db: Arc<D>,chunk_size: usize,row_fallback_concurrency: usize,- properties_size_threshold: usize,- properties_trim_target: usize,}impl<D: PersonDb + 'static> PersonWriteStore<D> {@@ -108,90 +103,9 @@ impl<D: PersonDb + 'static> PersonWriteStore<D> {db: Arc::new(db),chunk_size: cfg.chunk_size.max(1),row_fallback_concurrency: cfg.row_fallback_concurrency.max(1),- properties_size_threshold: cfg.properties_size_threshold,- properties_trim_target: cfg.properties_trim_target,}}- /// Preflight oversized persons out of a batch. For each person whose raw- /// properties bytes exceed the configured threshold, attempt to trim via- /// `properties::trim_properties_to_fit_size`; if the trim brings it below- /// the threshold the person rejoins the batch with its properties replaced,- /// otherwise it's skipped with an ingestion warning.- ///- /// This avoids a single oversized row forcing the whole chunk down the- /// per-row fallback path.- pub fn preflight_trim_batch(- &self,- persons: Vec<Person>,- ) -> (Vec<Person>, Vec<IngestionWarning>) {- let mut kept = Vec::with_capacity(persons.len());- let mut warnings = Vec::new();-- for mut person in persons {- if person.properties.len() <= self.properties_size_threshold {- kept.push(person);- continue;- }-- counter!("personhog_writer_properties_preempted_total").increment(1);-- match self.try_trim_properties(&person) {- TrimOutcome::Trimmed(bytes) => {- counter!("personhog_writer_properties_trimmed_writes_total").increment(1);- person.properties = bytes;- warnings.push(trimmed_warning(&person));- kept.push(person);- }- TrimOutcome::InvalidJson => {- counter!("personhog_writer_invalid_json_total").increment(1);- counter!("personhog_writer_rows_skipped_total").increment(1);- warn!(- team_id = person.team_id,- person_id = person.id,- "oversized person has invalid JSON properties, skipping"- );- warnings.push(invalid_json_warning(&person));- }- TrimOutcome::CannotFit => {- counter!("personhog_writer_rows_skipped_total").increment(1);- warnings.push(rejected_warning(&person));- }- }- }-- (kept, warnings)- }-- /// Attempt to trim a person's properties to fit under `properties_trim_target`.- /// `trim_properties_to_fit_size` returns `None` when it can't reach the- /// target (e.g. protected-only keys exceed it), so we don't need a- /// second post-trim size check here.- ///- /// Pure computation (no IO); used by both the preflight batch path and- /// the defensive per-row fallback after a PG size-violation error.- fn try_trim_properties(&self, person: &Person) -> TrimOutcome {- let value: serde_json::Value = match serde_json::from_slice(&person.properties) {- Ok(v) => v,- Err(_) => return TrimOutcome::InvalidJson,- };-- let Some(trimmed) = properties::trim_properties_to_fit_size(- &value,- person.team_id,- person.id,- self.properties_trim_target,- ) else {- return TrimOutcome::CannotFit;- };-- let bytes = serde_json::to_vec(&trimmed).unwrap_or_default();- if bytes.is_empty() {- return TrimOutcome::CannotFit;- }- TrimOutcome::Trimmed(bytes)- }-pub async fn upsert_batch(&self, persons: Vec<Person>) -> BatchOutcome {if persons.is_empty() {return BatchOutcome::Success;@@ -218,78 +132,64 @@ impl<D: PersonDb + 'static> PersonWriteStore<D> {outcome}- pub async fn upsert_row(&self, person: &Person) -> RowResult {- match self.db.execute_row(person, None).await {- Ok(()) => return RowResult::Written,- Err(e) if matches!(e.kind, WriteErrorKind::PropertiesSizeViolation) => {- // Fall through to trim logic- }- Err(e) => {- counter!("personhog_writer_rows_skipped_total").increment(1);- warn!(- team_id = person.team_id,- person_id = person.id,- error = %e.message,- "per-row upsert failed, skipping"- );- return RowResult::Skipped(IngestionWarning {- team_id: person.team_id,- person_id: person.id,- message: format!("Person upsert failed: {}", e.message),- });- }- }-- // Size violation: defensive trim-and-retry. The preflight path usually- // catches oversized persons first; this branch fires for the edge case- // where raw bytes fit the threshold but JSONB encoding pushes us over.- //- // `try_trim_properties` may return `CannotFit` for either the "untrimable- // (protected keys already oversized)" case or the rare "raw bytes look- // fine but JSONB is big" case. Either way skipping is correct: the same- // raw bytes already failed at PG, and we have no smaller version to try.- match self.try_trim_properties(person) {- TrimOutcome::Trimmed(bytes) => {- let trimmed_str = from_utf8(&bytes).unwrap_or("{}");- match self.db.execute_row(person, Some(trimmed_str)).await {- Ok(()) => {- counter!("personhog_writer_properties_trimmed_writes_total").increment(1);- RowResult::Trimmed(trimmed_warning(person))- }- Err(_) => {- counter!("personhog_writer_rows_skipped_total").increment(1);- RowResult::Skipped(rejected_warning(person))- }- }- }- TrimOutcome::InvalidJson | TrimOutcome::CannotFit => {- counter!("personhog_writer_rows_skipped_total").increment(1);- RowResult::Skipped(rejected_warning(person))- }- }+ pub async fn upsert_row(&self, person: &Person) -> Result<(), WriteError> {+ self.db.execute_row(person).await}- /// Run per-row upserts for a batch of persons with bounded concurrency.- /// Used by the writer when a batch falls back to the per-row path after- /// chunk-level data failures. pgbouncer handles PG-side backpressure;- /// our bound is to keep sqlx pool turnover reasonable and cap memory of- /// in-flight futures.- pub async fn upsert_rows_parallel(&self, persons: Vec<Person>) -> Vec<RowResult> {+ /// Run per-row upserts for a batch of persons with bounded concurrency,+ /// isolating which rows a data-failed chunk actually cannot apply.+ /// pgbouncer handles PG-side backpressure; our bound is to keep sqlx+ /// pool turnover reasonable and cap memory of in-flight futures.+ ///+ /// Transient failures are returned for retry. Non-transient failures+ /// are invariant violations (the leader admitted an unapplyable+ /// record): logged loudly and returned so the caller halts the flush.+ pub async fn upsert_rows_parallel(&self, persons: Vec<Person>) -> RowFallbackOutcome {let start = Instant::now();let concurrency = self.row_fallback_concurrency;- let results: Vec<RowResult> = stream::iter(persons)+ let results: Vec<(Person, Result<(), WriteError>)> = stream::iter(persons).map(|p| async move {gauge!("personhog_writer_row_fallback_in_flight").increment(1.0);let res = self.upsert_row(&p).await;gauge!("personhog_writer_row_fallback_in_flight").decrement(1.0);- res+ (p, res)}).buffer_unordered(concurrency).collect().await;histogram!("personhog_writer_row_fallback_duration_seconds").record(start.elapsed().as_secs_f64());- results++ let mut outcome = RowFallbackOutcome::default();+ for (person, result) in results {+ match result {+ Ok(()) => {}+ Err(e) if matches!(e.kind, WriteErrorKind::Transient) => {+ outcome.transient.push(person);+ }+ Err(e) => {+ counter!(+ "personhog_writer_unapplyable_rows_total",+ "kind" => kind_label(e.kind)+ )+ .increment(1);+ error!(+ team_id = person.team_id,+ person_id = person.id,+ kind = ?e.kind,+ error = %e.message,+ "PG cannot apply a leader-admitted record; admission \+ has a gap — halting without committing"+ );+ outcome.violations.push(RowViolation {+ team_id: person.team_id,+ person_id: person.id,+ kind: e.kind,+ });+ }+ }+ }+ outcome}async fn run_parallel_chunks(&self, chunks: Vec<Vec<Person>>) -> BatchOutcome {@@ -373,41 +273,12 @@ fn partial_from_failed_chunk(chunk: Vec<Person>, kind: WriteErrorKind) -> BatchO}}-/// Result of attempting to trim a person's properties down to a size that-/// fits the configured threshold. Used by both the preflight batch path-/// and the defensive per-row fallback.-enum TrimOutcome {- /// Trim succeeded; these bytes are guaranteed to be under the threshold.- Trimmed(Vec<u8>),- /// The person's properties weren't valid JSON. Skip.- InvalidJson,- /// Trim ran but the result still exceeds the threshold. Typically means- /// protected properties alone are oversized, or the value wasn't a JSON- /// object. Skip.- CannotFit,-}--fn trimmed_warning(p: &Person) -> IngestionWarning {- IngestionWarning {- team_id: p.team_id,- person_id: p.id,- message: "Person properties exceeded size limit and were trimmed".to_string(),- }-}--fn rejected_warning(p: &Person) -> IngestionWarning {- IngestionWarning {- team_id: p.team_id,- person_id: p.id,- message: "Person properties exceeds size limit and was rejected".to_string(),- }-}--fn invalid_json_warning(p: &Person) -> IngestionWarning {- IngestionWarning {- team_id: p.team_id,- person_id: p.id,- message: "Person properties are invalid JSON and exceed size limit — rejected".to_string(),+/// Stable metric-label form of a non-transient error kind.+fn kind_label(kind: WriteErrorKind) -> &'static str {+ match kind {+ WriteErrorKind::PropertiesSizeViolation => "size",+ WriteErrorKind::Data => "data",+ WriteErrorKind::Transient => "transient",}}@@ -441,8 +312,6 @@ impl StoreConfig {Self {chunk_size: 100,row_fallback_concurrency: 4,- properties_size_threshold: 655_360,- properties_trim_target: 524_288,}}}@@ -546,11 +415,7 @@ mod tests {}}- async fn execute_row(- &self,- _person: &Person,- _override: Option<&str>,- ) -> Result<(), WriteError> {+ async fn execute_row(&self, _person: &Person) -> Result<(), WriteError> {self.row_calls.fetch_add(1, Ordering::SeqCst);match self.lookup_row_response() {ChunkResponse::Ok => Ok(()),@@ -781,155 +646,38 @@ mod tests {}}- // ── upsert_row ─────────────────────────────────────────────+ // ── upsert_rows_parallel ──────────────────────────────────#[tokio::test]- async fn upsert_row_success_returns_written() {+ async fn upsert_rows_parallel_applies_every_row_cleanly() {let store = PersonWriteStore::new(StubDb::new(), StoreConfig::test_default());- assert!(matches!(store.upsert_row(&p(1)).await, RowResult::Written));+ let persons: Vec<Person> = (0..10).map(p).collect();+ let outcome = store.upsert_rows_parallel(persons).await;+ assert!(outcome.transient.is_empty());+ assert!(outcome.violations.is_empty());}#[tokio::test]- async fn upsert_row_transient_returns_skipped() {+ async fn upsert_rows_parallel_returns_transient_failures_for_retry() {let db = StubDb::new().with_row_default(ChunkResponse::Err(WriteErrorKind::Transient));let store = PersonWriteStore::new(db, StoreConfig::test_default());- match store.upsert_row(&p(1)).await {- RowResult::Skipped(warning) => {- assert_eq!(warning.person_id, 1);- assert!(warning.message.contains("Person upsert failed"));- }- other => panic!("expected Skipped, got {other:?}"),- }- }-- #[tokio::test]- async fn upsert_row_data_error_returns_skipped() {- let db = StubDb::new().with_row_default(ChunkResponse::Err(WriteErrorKind::Data));- let store = PersonWriteStore::new(db, StoreConfig::test_default());- assert!(matches!(- store.upsert_row(&p(1)).await,- RowResult::Skipped(_)- ));- }-- // ── upsert_rows_parallel ──────────────────────────────────-- #[tokio::test]- async fn upsert_rows_parallel_returns_a_result_per_person() {- let store = PersonWriteStore::new(StubDb::new(), StoreConfig::test_default());- let persons: Vec<Person> = (0..10).map(p).collect();- let results = store.upsert_rows_parallel(persons).await;- assert_eq!(results.len(), 10);- assert!(results.iter().all(|r| matches!(r, RowResult::Written)));+ let persons: Vec<Person> = (0..5).map(p).collect();+ let outcome = store.upsert_rows_parallel(persons).await;+ assert_eq!(outcome.transient.len(), 5);+ assert!(outcome.violations.is_empty());}#[tokio::test]- async fn upsert_rows_parallel_surfaces_errors_as_skipped() {+ async fn upsert_rows_parallel_surfaces_unapplyable_rows_as_violations() {let db = StubDb::new().with_row_default(ChunkResponse::Err(WriteErrorKind::Data));let store = PersonWriteStore::new(db, StoreConfig::test_default());let persons: Vec<Person> = (0..5).map(p).collect();- let results = store.upsert_rows_parallel(persons).await;- assert_eq!(results.len(), 5);- assert!(results.iter().all(|r| matches!(r, RowResult::Skipped(_))));- }-- // ── preflight_trim_batch ───────────────────────────────────-- #[test]- fn preflight_leaves_normal_persons_untouched() {- let store = PersonWriteStore::new(StubDb::new(), StoreConfig::test_default());- let persons: Vec<Person> = (0..5).map(p).collect();- let (kept, warnings) = store.preflight_trim_batch(persons);- assert_eq!(kept.len(), 5);- assert!(warnings.is_empty());- }-- #[test]- fn preflight_trims_oversized_and_keeps_them_in_batch() {- // Small threshold so we can exercise the path without megabytes of JSON.- let store = PersonWriteStore::new(- StubDb::new(),- StoreConfig {- properties_size_threshold: 1024,- properties_trim_target: 512,- ..StoreConfig::test_default()- },- );- let normal = p(1);- // Oversized person: a single trimmable key with lots of content.- let mut oversized = p(2);- oversized.properties = serde_json::to_vec(&serde_json::json!({- "email": "[email protected]",- "bloat": "x".repeat(2_000),- }))- .unwrap();-- let (kept, warnings) = store.preflight_trim_batch(vec![normal, oversized]);-- assert_eq!(kept.len(), 2, "both persons should remain after trim");- // The trimmed person's properties should now be within threshold.- let trimmed = kept.iter().find(|p| p.id == 2).unwrap();- assert!(trimmed.properties.len() <= 1024);- assert_eq!(warnings.len(), 1);- assert!(warnings[0].message.contains("trimmed"));- }-- #[test]- fn preflight_skips_oversized_when_only_protected_keys_exceed() {- // 1 KiB threshold; protected `email` alone exceeds it.- let store = PersonWriteStore::new(- StubDb::new(),- StoreConfig {- properties_size_threshold: 1024,- properties_trim_target: 512,- ..StoreConfig::test_default()- },- );- let mut untrimable = p(1);- untrimable.properties = serde_json::to_vec(&serde_json::json!({- "email": "x".repeat(2_000),- }))- .unwrap();-- let (kept, warnings) = store.preflight_trim_batch(vec![untrimable]);-- assert!(kept.is_empty());- assert_eq!(warnings.len(), 1);- assert!(warnings[0].message.contains("rejected"));- }-- #[test]- fn preflight_skips_invalid_json() {- let store = PersonWriteStore::new(- StubDb::new(),- StoreConfig {- properties_size_threshold: 16,- properties_trim_target: 8,- ..StoreConfig::test_default()- },- );- let mut bad = p(1);- bad.properties = vec![b'n'; 32]; // "nnnn..." — not valid JSON and > 16 bytes-- let (kept, warnings) = store.preflight_trim_batch(vec![bad]);-- assert!(kept.is_empty());- assert_eq!(warnings.len(), 1);- assert!(warnings[0].message.contains("invalid JSON"));- }-- #[test]- fn preflight_preserves_content_for_untouched_persons() {- let store = PersonWriteStore::new(StubDb::new(), StoreConfig::test_default());- let original: Vec<Person> = (0..3).map(p).collect();-- let (kept, warnings) = store.preflight_trim_batch(original.clone());-- assert_eq!(kept.len(), 3);- assert!(warnings.is_empty());- for (a, b) in original.iter().zip(kept.iter()) {- assert_eq!(a.id, b.id);- assert_eq!(a.properties, b.properties);- }+ let outcome = store.upsert_rows_parallel(persons).await;+ assert!(outcome.transient.is_empty());+ assert_eq!(outcome.violations.len(), 5);+ assert!(outcome+ .violations+ .iter()+ .all(|v| matches!(v.kind, WriteErrorKind::Data)));}}diff --git a/rust/personhog-writer/src/writer.rs b/rust/personhog-writer/src/writer.rsindex 0a147a964c83..4f561319ce76 100644--- a/rust/personhog-writer/src/writer.rs+++ b/rust/personhog-writer/src/writer.rs@@ -1,4 +1,5 @@use std::collections::HashMap;+use std::ops::ControlFlow;use std::sync::Arc;use std::time::Duration;@@ -9,8 +10,8 @@ use tokio::sync::mpsc;use tracing::{debug, error, info, warn};use crate::consumer::FlushBatch;-use crate::kafka::{PersonConsumer, WarningsProducer};-use crate::store::{BatchOutcome, IngestionWarning, PersonDb, PersonWriteStore, RowResult};+use crate::kafka::PersonConsumer;+use crate::store::{BatchOutcome, PersonDb, PersonWriteStore};/// Receives batches from the consumer task, writes to the persistent/// store, and commits Kafka offsets. Runs on its own tokio task so@@ -20,7 +21,6 @@ pub struct WriterTask<D: PersonDb + 'static> {store: PersonWriteStore<D>,flush_rx: mpsc::Receiver<FlushBatch>,handle: Handle,- warnings: Option<WarningsProducer>,consecutive_failures: u32,}@@ -34,14 +34,12 @@ impl<D: PersonDb + 'static> WriterTask<D> {store: PersonWriteStore<D>,flush_rx: mpsc::Receiver<FlushBatch>,handle: Handle,- warnings: Option<WarningsProducer>,) -> Self {Self {consumer,store,flush_rx,handle,- warnings,consecutive_failures: 0,}}@@ -58,7 +56,15 @@ impl<D: PersonDb + 'static> WriterTask<D> {let Some(batch) = batch else {break;};- self.process_batch(batch).await;+ // A failed flush leaves its offsets uncommitted, and+ // Kafka commits are cumulative per partition — if a+ // later batch committed, the failed one would be+ // silently skipped after restart. signal_failure only+ // starts an async shutdown, so the halt has to be+ // structural: stop receiving here and now.+ if self.process_batch(batch).await.is_break() {+ break;+ }}_ = heartbeat.tick() => {@@ -67,13 +73,12 @@ impl<D: PersonDb + 'static> WriterTask<D> {}}- if let Some(producer) = &self.warnings {- producer.flush(Duration::from_secs(5));- }info!("Writer task stopped");}- async fn process_batch(&mut self, batch: FlushBatch) {+ /// Returns `Break` after signaling a failure — the run loop must stop+ /// receiving so no later batch can commit offsets past this one.+ async fn process_batch(&mut self, batch: FlushBatch) -> ControlFlow<()> {let FlushBatch {persons,offsets,@@ -82,94 +87,85 @@ impl<D: PersonDb + 'static> WriterTask<D> {let total_rows = persons.len();counter!("personhog_writer_flushes_total").increment(1);- // Preflight oversized persons out of the batch. Trimmed survivors- // rejoin the main path; untrimable ones produce skip warnings.- let (persons, mut warnings) = self.store.preflight_trim_batch(persons);+ // The leader admits every record against the writer's own rejection+ // surface, so everything here is applyable verbatim. A non-transient+ // failure below is an invariant violation: the flush halts without+ // committing (skipping would permanently diverge PG from the cache+ // and changelog), Kafka redelivers after restart, and the alarm+ // stands until admission's gap is fixed.let mut remaining: Vec<Person> = persons;loop {let to_process = std::mem::take(&mut remaining);match self.store.upsert_batch(to_process).await {BatchOutcome::Success => {- self.finish(total_rows, &offsets, oldest_message_ts_ms, warnings);- return;+ self.finish(total_rows, &offsets, oldest_message_ts_ms);+ return ControlFlow::Continue(());}BatchOutcome::Partial {transient,data_failed,} => {+ let mut retry = transient;if !data_failed.is_empty() {counter!("personhog_writer_batch_fallback_total").increment(1);warn!(rows = data_failed.len(),"batch had data-failed chunks, falling back to per-row");- for r in self.store.upsert_rows_parallel(data_failed).await {- match r {- RowResult::Written => {}- RowResult::Trimmed(w) | RowResult::Skipped(w) => warnings.push(w),- }+ let fallback = self.store.upsert_rows_parallel(data_failed).await;+ if !fallback.violations.is_empty() {+ let first = &fallback.violations[0];+ self.handle.signal_failure(format!(+ "{} unapplyable row(s) despite leader admission (first: \+ team_id={} person_id={} kind={:?}); refusing to commit",+ fallback.violations.len(),+ first.team_id,+ first.person_id,+ first.kind+ ));+ return ControlFlow::Break(());}+ retry.extend(fallback.transient);}- if transient.is_empty() {- self.finish(total_rows, &offsets, oldest_message_ts_ms, warnings);- return;+ if retry.is_empty() {+ self.finish(total_rows, &offsets, oldest_message_ts_ms);+ return ControlFlow::Continue(());}- // Transient chunks remain — retry just those with backoff.+ // Transient failures remain — retry just those with backoff.self.consecutive_failures += 1;let backoff = backoff_duration(self.consecutive_failures);error!(consecutive_failures = self.consecutive_failures,- transient_rows = transient.len(),+ transient_rows = retry.len(),backoff_ms = backoff.as_millis() as u64,- "transient chunk failures, retrying"+ "transient failures, retrying");if self.consecutive_failures >= MAX_CONSECUTIVE_FAILURES {- // Emit warnings for data_failed rows that were already- // written in this iteration before we bail. Offsets- // won't commit, so Kafka replay will re-emit them, but- // losing them when we have them is wrong.- self.emit_warnings(&warnings);self.handle.signal_failure(format!("store flush failed {MAX_CONSECUTIVE_FAILURES} consecutive times"));- return;+ return ControlFlow::Break(());}tokio::time::sleep(backoff).await;- remaining = transient;+ remaining = retry;}BatchOutcome::Fatal(fatal) => {- self.emit_warnings(&warnings);self.handle.signal_failure(format!("upsert_batch fatal: {fatal}"));- return;+ return ControlFlow::Break(());}}}}- fn emit_warnings(&self, warnings: &[IngestionWarning]) {- if let Some(producer) = &self.warnings {- for w in warnings {- producer.emit(w);- }- }- }-- fn finish(- &mut self,- rows: usize,- offsets: &HashMap<i32, i64>,- oldest_ts_ms: Option<i64>,- warnings: Vec<IngestionWarning>,- ) {- self.emit_warnings(&warnings);+ fn finish(&mut self, rows: usize, offsets: &HashMap<i32, i64>, oldest_ts_ms: Option<i64>) {self.consecutive_failures = 0;self.handle.report_healthy();self.commit_and_record(offsets, oldest_ts_ms, rows);diff --git a/rust/personhog-writer/tests/admission_weld.rs b/rust/personhog-writer/tests/admission_weld.rsnew file mode 100644index 000000000000..18cc51541795--- /dev/null+++ b/rust/personhog-writer/tests/admission_weld.rs@@ -0,0 +1,178 @@+//! Welds leader admission to the writer's real apply path: any properties+//! value that passes admission (NUL sanitization + the exact jsonb size+//! measure) must land through the writer's actual upsert statement against+//! a live Postgres. This is the executable form of the changelog contract+//! — nothing admission accepts may be unapplyable — and it must break if+//! either side's rejection surface drifts.+//!+//! Requires local PG (posthog_persons) like the other writer integration+//! tests; the target is `personhog_person_tmp`, which carries the size+//! constraint and the uuid unique index.++mod common;++use common::create_test_pool;+use personhog_common::properties::{+ jsonb_column_size, sanitize_for_jsonb, trim_properties_to_fit_size, TrimResult,+};+use personhog_proto::personhog::types::v1::Person;+use personhog_writer::pg::PgStore;+use personhog_writer::store::PersonDb;+use serde_json::{json, Value};+use uuid::Uuid;++const TARGET_TABLE: &str = "personhog_person_tmp";+const SIZE_THRESHOLD: usize = 655_360;+const TRIM_TARGET: usize = 524_288;+const WELD_TEAM_ID: i64 = 99_400;++/// Hostile property maps: every shape we could think of that has ever made+/// a JSON store or a bind path unhappy. Extend freely — every fixture that+/// admission admits must apply.+fn hostile_fixtures() -> Vec<(&'static str, Value)> {+ let deep = {+ // serde_json's default parse recursion limit is 128, which bounds+ // anything the leader can hold; stay just under it.+ let mut v = json!("bottom");+ for _ in 0..120 {+ v = json!({ "d": v });+ }+ v+ };+ let many_nuls: String = "\u{0000}".repeat(500);+ let big_fitting = "x".repeat(400_000);++ vec![+ ("empty_object", json!({})),+ ("empty_key_and_value", json!({"": ""})),+ ("nul_in_value", json!({"k": "a\u{0000}b"})),+ ("nul_in_key", json!({"a\u{0000}b": "v"})),+ ("nul_only_key", json!({"\u{0000}": "\u{0000}"})),+ ("many_nuls", json!({"k": many_nuls})),+ (+ "nul_nested_in_arrays",+ json!({"k": [["\u{0000}"], {"inner\u{0000}": ["x\u{0000}y"]}]}),+ ),+ (+ "control_characters_besides_nul",+ json!({"k": "\u{0001}\u{0008}\u{000b}\u{001f}\u{007f}"}),+ ),+ (+ "numbers_at_the_edges",+ json!({+ "max_u64": u64::MAX,+ "min_i64": i64::MIN,+ // Sanitization clamps this to 1e307: PG's expanded numeric+ // rendering of anything larger cannot be parsed back by+ // serde_json (the leader's own PG fallback would choke).+ "huge_float": 1.7976931348623157e308,+ "boundary_float": 1e307,+ "tiny_float": 5e-324,+ "neg_zero": -0.0,+ }),+ ),+ (+ "unicode_zoo",+ json!({"emoji": "👩👩👧👧🏳️⚧️", "rtl": "مرحبا", "cjk": "漢字テスト한글", "fffd": "\u{FFFD}", "zwj": "a\u{200d}b"}),+ ),+ ("deeply_nested", json!({"deep": deep})),+ (+ "big_but_fitting",+ json!({"email": "[email protected]", "blob": big_fitting}),+ ),+ (+ "quotes_and_escapes",+ json!({"k": "\"\\\n\r\t/\u{0008}", "\\\"key\"\\": "v"}),+ ),+ (+ "duplicate_after_sanitize",+ json!({"a\u{0000}": "first", "a\u{FFFD}": "second"}),+ ),+ ]+}++/// The leader's admission pipeline, verbatim: sanitize, measure, trim.+/// Returns the properties as they would be produced, or None if admission+/// rejects (protected properties alone cannot fit).+fn admit(mut properties: Value) -> Option<Value> {+ sanitize_for_jsonb(&mut properties);+ if jsonb_column_size(&properties) > SIZE_THRESHOLD {+ match trim_properties_to_fit_size(&properties, TRIM_TARGET) {+ TrimResult::Trimmed(trimmed) => return Some(trimmed),+ TrimResult::Fits => {}+ TrimResult::CannotFit => return None,+ }+ }+ Some(properties)+}++fn person_for(fixture_index: i64, properties: &Value) -> Person {+ Person {+ id: fixture_index,+ team_id: WELD_TEAM_ID,+ uuid: Uuid::new_v4().to_string(),+ properties: serde_json::to_vec(properties).unwrap(),+ created_at: 1_700_000_000,+ version: 1,+ is_identified: false,+ ..Default::default()+ }+}++async fn cleanup(pool: &sqlx::PgPool) {+ sqlx::query("DELETE FROM personhog_person_tmp WHERE team_id = $1")+ .bind(WELD_TEAM_ID)+ .execute(pool)+ .await+ .unwrap();+}++#[tokio::test]+async fn every_admitted_fixture_lands_through_the_writers_real_upsert() {+ let pool = create_test_pool().await;+ cleanup(&pool).await;+ let store = PgStore::new(pool.clone(), TARGET_TABLE.to_string());++ for (index, (name, fixture)) in hostile_fixtures().into_iter().enumerate() {+ let admitted = admit(fixture)+ .unwrap_or_else(|| panic!("fixture {name} must be admissible — none is oversized"));+ let person = person_for(index as i64 + 1, &admitted);+ store+ .execute_row(&person)+ .await+ .unwrap_or_else(|e| panic!("admitted fixture {name} must apply, got: {e}"));++ // The stored jsonb round-trips to exactly the admitted value.+ let (stored,): (Value,) = sqlx::query_as(+ "SELECT properties FROM personhog_person_tmp WHERE team_id = $1 AND id = $2",+ )+ .bind(WELD_TEAM_ID)+ .bind(index as i64 + 1)+ .fetch_one(&pool)+ .await+ .unwrap();+ assert_eq!(stored, admitted, "fixture {name} must round-trip verbatim");+ }++ cleanup(&pool).await;+}++/// Proves the weld can detect what it guards: the raw (unsanitized) NUL+/// fixture is exactly what PG refuses, so skipping sanitization must fail+/// the same statement the admitted fixtures pass.+#[tokio::test]+async fn unsanitized_nul_is_rejected_by_the_same_statement() {+ let pool = create_test_pool().await;+ let store = PgStore::new(pool.clone(), TARGET_TABLE.to_string());++ let person = person_for(9_999, &json!({"k": "a\u{0000}b"}));+ let err = store+ .execute_row(&person)+ .await+ .expect_err("PG must refuse a NUL that bypassed sanitization");+ assert!(+ err.message.contains("0000") || err.message.to_lowercase().contains("unicode"),+ "rejection should be the jsonb NUL refusal, got: {}",+ err.message+ );+}diff --git a/rust/personhog-writer/tests/common/mod.rs b/rust/personhog-writer/tests/common/mod.rsindex 469fa65b2975..e0823d3e56bc 100644--- a/rust/personhog-writer/tests/common/mod.rs+++ b/rust/personhog-writer/tests/common/mod.rs@@ -1,3 +1,8 @@+// Each `tests/*.rs` integration test compiles as its own binary and imports+// `common` via `mod common;`. Helpers used by some test files but not others+// would otherwise fire `dead_code` per-binary; suppress at the module level.+#![allow(dead_code)]+use std::time::Duration;use common_kafka::kafka_producer::KafkaContext;@@ -20,8 +25,6 @@ pub fn test_store_config() -> StoreConfig {StoreConfig {chunk_size: 500,row_fallback_concurrency: 8,- properties_size_threshold: 655_360,- properties_trim_target: 524_288,}}diff --git a/rust/personhog-writer/tests/integration.rs b/rust/personhog-writer/tests/integration.rsindex 9295a4875a14..c58a196476ba 100644--- a/rust/personhog-writer/tests/integration.rs+++ b/rust/personhog-writer/tests/integration.rs@@ -14,7 +14,7 @@ use personhog_writer::consumer::{ConsumerTask, FlushBatch};use personhog_writer::kafka::PersonConsumer;use personhog_writer::pg::PgStore;use personhog_writer::store::{- BatchOutcome, PersonDb, PersonWriteStore, RowResult, WriteError, WriteErrorKind,+ BatchOutcome, PersonDb, PersonWriteStore, WriteError, WriteErrorKind,};use personhog_writer::writer::WriterTask;use prost::Message;@@ -131,7 +131,7 @@ async fn writer_upsert_batch_multiple_persons() {}#[tokio::test]-async fn writer_skips_invalid_uuids_without_failing_batch() {+async fn writer_surfaces_invalid_uuids_as_violations_never_silent_skips() {let pool = create_test_pool().await;let team_id: i32 = 99_004;cleanup_team(&pool, team_id).await;@@ -146,14 +146,27 @@ async fn writer_skips_invalid_uuids_without_failing_batch() {bad_person.uuid = "not-a-valid-uuid".to_string();let another_valid = make_person(team_id as i64, 3, 1);- // Batch contains one invalid UUID -- it should be skipped,- // and the valid persons should still be written.- assert!(matches!(- writer- .upsert_batch(vec![valid_person, bad_person, another_valid])- .await,- BatchOutcome::Success- ));+ // An unbindable row fails its chunk: silently dropping it would+ // permanently diverge PG from the cache and changelog.+ let outcome = writer+ .upsert_batch(vec![valid_person, bad_person, another_valid])+ .await;+ let BatchOutcome::Partial {+ transient,+ data_failed,+ } = outcome+ else {+ panic!("a chunk with an unbindable row must be data-failed");+ };+ assert!(transient.is_empty());+ assert_eq!(data_failed.len(), 3);++ // The per-row pass isolates the poison row as a violation; the valid+ // rows apply.+ let fallback = writer.upsert_rows_parallel(data_failed).await;+ assert!(fallback.transient.is_empty());+ assert_eq!(fallback.violations.len(), 1);+ assert_eq!(fallback.violations[0].person_id, 2);let count: (i64,) =sqlx::query_as("SELECT COUNT(*) FROM personhog_person_tmp WHERE team_id = $1")@@ -161,8 +174,10 @@ async fn writer_skips_invalid_uuids_without_failing_batch() {.fetch_one(&pool).await.unwrap();-- assert_eq!(count.0, 2);+ assert_eq!(+ count.0, 2,+ "valid rows apply; the poison row writes nothing"+ );cleanup_team(&pool, team_id).await;}@@ -207,13 +222,7 @@ async fn consumer_flushes_on_buffer_size_threshold() {PgStore::new(pool.clone(), TARGET_TABLE.to_string()),common::test_store_config(),);- let writer_task = WriterTask::new(- Arc::clone(&kafka_consumer),- writer,- flush_rx,- writer_handle,- None,- );+ let writer_task = WriterTask::new(Arc::clone(&kafka_consumer), writer, flush_rx, writer_handle);tokio::spawn(async move { writer_task.run().await });// Produce 6 messages to mock Kafka (two full batches of 3)@@ -308,13 +317,7 @@ async fn consumer_flushes_on_timer() {PgStore::new(pool.clone(), TARGET_TABLE.to_string()),common::test_store_config(),);- let writer_task = WriterTask::new(- Arc::clone(&kafka_consumer),- writer,- flush_rx,- writer_handle,- None,- );+ let writer_task = WriterTask::new(Arc::clone(&kafka_consumer), writer, flush_rx, writer_handle);tokio::spawn(async move { writer_task.run().await });// Produce 2 messages -- below the size threshold of 1000@@ -409,13 +412,7 @@ async fn consumer_deduplicates_multiple_updates_for_same_person() {PgStore::new(pool.clone(), TARGET_TABLE.to_string()),common::test_store_config(),);- let writer_task = WriterTask::new(- Arc::clone(&kafka_consumer),- writer,- flush_rx,- writer_handle,- None,- );+ let writer_task = WriterTask::new(Arc::clone(&kafka_consumer), writer, flush_rx, writer_handle);tokio::spawn(async move { writer_task.run().await });// Produce 5 updates for the same person (id=1) with increasing versions@@ -513,13 +510,7 @@ async fn writer_processes_batch_from_channel() {PgStore::new(pool.clone(), TARGET_TABLE.to_string()),common::test_store_config(),);- let writer_task = WriterTask::new(- Arc::clone(&kafka_consumer),- writer,- flush_rx,- writer_handle,- None,- );+ let writer_task = WriterTask::new(Arc::clone(&kafka_consumer), writer, flush_rx, writer_handle);tokio::spawn(async move { writer_task.run().await });// Send a batch directly through the channel@@ -562,10 +553,12 @@ async fn writer_processes_batch_from_channel() {// ============================================================/// Mock DB that fails chunks a configurable number of times, then succeeds.-/// Rows always succeed. Exercises the full orchestration layer above it.+/// Rows succeed unless `row_error_kind` is set. Exercises the full+/// orchestration layer above it.struct MockDb {chunk_remaining_failures: std::sync::atomic::AtomicU32,chunk_error_kind: WriteErrorKind,+ row_error_kind: Option<WriteErrorKind>,}#[async_trait::async_trait]@@ -586,12 +579,14 @@ impl PersonDb for MockDb {}}- async fn execute_row(- &self,- _person: &Person,- _override: Option<&str>,- ) -> Result<(), WriteError> {- Ok(())+ async fn execute_row(&self, _person: &Person) -> Result<(), WriteError> {+ match self.row_error_kind {+ Some(kind) => Err(WriteError {+ message: "mock row failure".to_string(),+ kind,+ }),+ None => Ok(()),+ }}}@@ -618,23 +613,17 @@ async fn writer_crashes_after_exhausting_transient_retries() {let mock_db = MockDb {chunk_remaining_failures: std::sync::atomic::AtomicU32::new(100),chunk_error_kind: WriteErrorKind::Transient,+ row_error_kind: None,};let store = PersonWriteStore::new(mock_db,personhog_writer::store::StoreConfig {chunk_size: 10,row_fallback_concurrency: 4,- ..common::test_store_config()},);- let writer_task = WriterTask::new(- Arc::clone(&kafka_consumer),- store,- flush_rx,- writer_handle,- None,- );+ let writer_task = WriterTask::new(Arc::clone(&kafka_consumer), store, flush_rx, writer_handle);tokio::spawn(async move { writer_task.run().await });let batch = FlushBatch {@@ -676,23 +665,17 @@ async fn writer_recovers_on_transient_retry() {let mock_db = MockDb {chunk_remaining_failures: std::sync::atomic::AtomicU32::new(1),chunk_error_kind: WriteErrorKind::Transient,+ row_error_kind: None,};let store = PersonWriteStore::new(mock_db,personhog_writer::store::StoreConfig {chunk_size: 10,row_fallback_concurrency: 4,- ..common::test_store_config()},);- let writer_task = WriterTask::new(- Arc::clone(&kafka_consumer),- store,- flush_rx,- writer_handle,- None,- );+ let writer_task = WriterTask::new(Arc::clone(&kafka_consumer), store, flush_rx, writer_handle);tokio::spawn(async move { writer_task.run().await });let batch = FlushBatch {@@ -738,23 +721,17 @@ async fn writer_falls_back_to_per_row_on_data_error() {let mock_db = MockDb {chunk_remaining_failures: std::sync::atomic::AtomicU32::new(100),chunk_error_kind: WriteErrorKind::Data,+ row_error_kind: None,};let store = PersonWriteStore::new(mock_db,personhog_writer::store::StoreConfig {chunk_size: 10,row_fallback_concurrency: 4,- ..common::test_store_config()},);- let writer_task = WriterTask::new(- Arc::clone(&kafka_consumer),- store,- flush_rx,- writer_handle,- None,- );+ let writer_task = WriterTask::new(Arc::clone(&kafka_consumer), store, flush_rx, writer_handle);tokio::spawn(async move { writer_task.run().await });let batch = FlushBatch {@@ -777,80 +754,90 @@ async fn writer_falls_back_to_per_row_on_data_error() {);}-// ============================================================-// Properties size violation: trim → successful write-// ============================================================-+/// After a batch with unapplyable rows signals failure, the writer must+/// stop receiving entirely: Kafka offset commits are cumulative per+/// partition, so processing a later batch and committing its offsets+/// would silently skip the failed batch's uncommitted rows after restart.+/// The observable halt is the flush channel closing.#[tokio::test]-async fn properties_size_violation_trim_succeeds() {- let pool = create_test_pool().await;- let team_id: i32 = 99_050;- cleanup_team(&pool, team_id).await;-- let store = PersonWriteStore::new(- PgStore::new(pool.clone(), TARGET_TABLE.to_string()),- common::test_store_config(),- );+async fn unapplyable_batch_halts_the_writer_before_any_later_batch() {+ let (flush_tx, flush_rx) = mpsc::channel::<FlushBatch>(4);- // Build properties that exceed 640KB total but fit once custom keys are- // trimmed. Protected "email" is small; two large custom properties push- // the serialized JSON well past the DB constraint.- let mut props = serde_json::Map::new();- props.insert(- "email".to_string(),- serde_json::json!("[email protected]"),- );- let big_value = "x".repeat(400_000);- props.insert("custom_a".to_string(), serde_json::json!(big_value));- props.insert("custom_b".to_string(), serde_json::json!(big_value));+ let (mock_cluster, _) = create_mock_kafka().await;+ let mut client_config = ClientConfig::new();+ client_config+ .set("bootstrap.servers", mock_cluster.bootstrap_servers())+ .set("group.id", "test-writer-halt")+ .set("enable.auto.commit", "false")+ .set("enable.auto.offset.store", "false");+ let kafka_consumer = Arc::new(PersonConsumer::new(&client_config, TOPIC.to_string()).unwrap());- let mut person = make_person(team_id as i64, 1, 1);- person.properties = serde_json::to_vec(&serde_json::Value::Object(props)).unwrap();+ let mut manager = lifecycle::Manager::builder("test")+ .with_trap_signals(false)+ .build();+ let writer_handle = manager.register("writer", lifecycle::ComponentOptions::new());+ let monitor = manager.monitor_background();- let result = store.upsert_row(&person).await;- let RowResult::Trimmed(warning) = result else {- panic!("expected RowResult::Trimmed");+ // The first chunk fails with a data error and its per-row fallback+ // fails too — an unapplyable batch despite leader admission. Later+ // chunks would succeed, so a writer that kept going would commit the+ // buffered batch's offsets past the failed one.+ let mock_db = MockDb {+ chunk_remaining_failures: std::sync::atomic::AtomicU32::new(1),+ chunk_error_kind: WriteErrorKind::Data,+ row_error_kind: Some(WriteErrorKind::PropertiesSizeViolation),};- assert_eq!(warning.team_id, team_id as i64);- assert_eq!(warning.person_id, 1);- assert!(!warning.message.is_empty());+ let store = PersonWriteStore::new(+ mock_db,+ personhog_writer::store::StoreConfig {+ chunk_size: 10,+ row_fallback_concurrency: 4,+ },+ );- // Verify the row landed in PG with trimmed properties- let row: (i64, String) = sqlx::query_as(- "SELECT id, properties::text FROM personhog_person_tmp WHERE team_id = $1 AND id = $2",- )- .bind(team_id)- .bind(1_i64)- .fetch_one(&pool)- .await- .unwrap();+ let writer_task = WriterTask::new(Arc::clone(&kafka_consumer), store, flush_rx, writer_handle);+ tokio::spawn(async move { writer_task.run().await });- assert_eq!(row.0, 1);- let stored_props: serde_json::Value = serde_json::from_str(&row.1).unwrap();- let stored_map = stored_props.as_object().unwrap();- assert!(- stored_map.contains_key("email"),- "protected property 'email' should be preserved"- );- // The trim algorithm removes custom properties in alphabetical order- // until the result fits under the target. "custom_a" is removed first;- // that alone brings the total below 512KB, so "custom_b" survives.- assert!(- !stored_map.contains_key("custom_a"),- "custom property 'custom_a' should have been trimmed"- );+ // A second batch is already buffered behind the poison one — the+ // regression this guards is the writer pulling and committing it.+ let poison = FlushBatch {+ persons: vec![make_person(99_043, 1, 1)],+ offsets: HashMap::new(),+ oldest_message_ts_ms: None,+ };+ let buffered = FlushBatch {+ persons: vec![make_person(99_043, 2, 1)],+ offsets: HashMap::new(),+ oldest_message_ts_ms: None,+ };+ flush_tx.send(poison).await.unwrap();+ flush_tx.send(buffered).await.unwrap();- cleanup_team(&pool, team_id).await;+ // The writer must drop its receiver without consuming the buffered+ // batch, and the lifecycle must report the failure.+ tokio::time::timeout(Duration::from_secs(5), flush_tx.closed())+ .await+ .expect("writer should stop receiving after an unapplyable batch");+ let result = tokio::time::timeout(Duration::from_secs(5), monitor.wait())+ .await+ .expect("lifecycle should shut down");+ assert!(result.is_err(), "lifecycle should report component failure");}// ============================================================-// Properties size violation: untrimable (protected only) → skip+// Properties size violation: invariant violation, never corrected// ============================================================+/// A row violating check_properties_size cannot reach the writer through+/// a correctly-admitting leader, so the writer treats one as an admission+/// bug: a non-transient error that halts the flush without committing and+/// writes nothing. A writer-side trim or skip would make Postgres diverge+/// from the cache and changelog — the exact drift leader admission exists+/// to prevent.#[tokio::test]-async fn properties_size_violation_untrimable_skips() {+async fn properties_size_violation_errors_and_writes_nothing() {let pool = create_test_pool().await;- let team_id: i32 = 99_051;+ let team_id: i32 = 99_050;cleanup_team(&pool, team_id).await;let store = PersonWriteStore::new(@@ -858,23 +845,26 @@ async fn properties_size_violation_untrimable_skips() {common::test_store_config(),);- // Only protected properties, and they exceed 640KB on their own.+ // Would have been trimmable under the old semantics: protected email+ // is small, two large custom properties push past the constraint.let mut props = serde_json::Map::new();- let huge_email = "e".repeat(700_000);- props.insert("email".to_string(), serde_json::json!(huge_email));+ props.insert(+ "email".to_string(),+ serde_json::json!("[email protected]"),+ );+ let big_value = "x".repeat(400_000);+ props.insert("custom_a".to_string(), serde_json::json!(big_value));+ props.insert("custom_b".to_string(), serde_json::json!(big_value));let mut person = make_person(team_id as i64, 1, 1);person.properties = serde_json::to_vec(&serde_json::Value::Object(props)).unwrap();- let result = store.upsert_row(&person).await;- let RowResult::Skipped(warning) = result else {- panic!("expected RowResult::Skipped");- };- assert_eq!(warning.team_id, team_id as i64);- assert_eq!(warning.person_id, 1);- assert!(!warning.message.is_empty());+ let err = store+ .upsert_row(&person)+ .await+ .expect_err("an unapplyable row must error, never be skipped");+ assert!(matches!(err.kind, WriteErrorKind::PropertiesSizeViolation));- // Verify no row was writtenlet count: (i64,) =sqlx::query_as("SELECT COUNT(*) FROM personhog_person_tmp WHERE team_id = $1 AND id = $2").bind(team_id)@@ -882,8 +872,7 @@ async fn properties_size_violation_untrimable_skips() {.fetch_one(&pool).await.unwrap();-- assert_eq!(count.0, 0, "no row should exist for a skipped person");+ assert_eq!(count.0, 0, "an unapplyable person must write nothing");cleanup_team(&pool, team_id).await;}@@ -943,13 +932,7 @@ async fn e2e_produce_to_kafka_and_verify_pg_write() {PgStore::new(pool.clone(), TARGET_TABLE.to_string()),common::test_store_config(),);- let writer_task = WriterTask::new(- Arc::clone(&kafka_consumer),- writer,- flush_rx,- writer_handle,- None,- );+ let writer_task = WriterTask::new(Arc::clone(&kafka_consumer), writer, flush_rx, writer_handle);tokio::spawn(async move { writer_task.run().await });let consumer_task = ConsumerTask::new(