Skip to content

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

feat(propvals): part 3: add fan-out, aggregator, and tuple types (#59429)

Andy Zhaoa5f22ce36b74
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index 46d03afee678..d38c09c6d723 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -7326,6 +7326,8 @@ dependencies = [
"envconfig",
"lifecycle",
"proptest",
+ "serde",
+ "serde_json",
"serve-metrics",
"siphasher 1.0.2",
"tokio",
diff --git a/rust/property-vals-rs/Cargo.toml b/rust/property-vals-rs/Cargo.toml
index 28e83e4cfc67..2afaa669b492 100644
--- a/rust/property-vals-rs/Cargo.toml
+++ b/rust/property-vals-rs/Cargo.toml
@@ -11,6 +11,8 @@ common-continuous-profiling = { path = "../common/continuous_profiling" }
common-kafka = { path = "../common/kafka" }
envconfig = { workspace = true }
lifecycle = { path = "../common/lifecycle" }
+serde = { workspace = true }
+serde_json = { workspace = true }
serve-metrics = { path = "../common/serve_metrics" }
siphasher = { workspace = true }
tokio = { workspace = true }
diff --git a/rust/property-vals-rs/src/aggregator.rs b/rust/property-vals-rs/src/aggregator.rs
new file mode 100644
index 000000000000..e3e55569f976
--- /dev/null
+++ b/rust/property-vals-rs/src/aggregator.rs
@@ -0,0 +1,102 @@
+use std::collections::HashMap;
+
+use crate::types::TupleKey;
+
+pub struct Aggregator {
+ counts: HashMap<TupleKey, u64>,
+}
+
+impl Aggregator {
+ pub fn new() -> Self {
+ Self {
+ counts: HashMap::new(),
+ }
+ }
+
+ pub fn add(&mut self, tuple: TupleKey, count: u64) {
+ *self.counts.entry(tuple).or_insert(0) += count;
+ }
+
+ pub fn len(&self) -> usize {
+ self.counts.len()
+ }
+
+ pub fn is_empty(&self) -> bool {
+ self.counts.is_empty()
+ }
+
+ pub fn drain(&mut self) -> HashMap<TupleKey, u64> {
+ std::mem::take(&mut self.counts)
+ }
+}
+
+impl Default for Aggregator {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::types::PropertyType;
+ use proptest::prelude::*;
+
+ fn tuple(team: i64, key: &str, value: &str) -> TupleKey {
+ TupleKey {
+ team_id: team,
+ property_type: PropertyType::Event,
+ property_key: key.to_string(),
+ property_value: value.to_string(),
+ }
+ }
+
+ fn arb_property_type() -> impl Strategy<Value = PropertyType> {
+ prop_oneof![
+ Just(PropertyType::Event),
+ Just(PropertyType::Person),
+ (0u8..=10).prop_map(PropertyType::Group),
+ ]
+ }
+
+ prop_compose! {
+ fn arb_tuple()(
+ team_id in -5i64..=5,
+ property_type in arb_property_type(),
+ property_key in "[a-c]{1,3}",
+ property_value in "[x-z]{1,3}",
+ ) -> TupleKey {
+ TupleKey { team_id, property_type, property_key, property_value }
+ }
+ }
+
+ proptest! {
+ #[test]
+ fn drained_counts_equal_per_tuple_sum(
+ ops in prop::collection::vec((arb_tuple(), 1u64..1_000), 0..200),
+ ) {
+ let mut agg = Aggregator::new();
+ let mut expected: HashMap<TupleKey, u64> = HashMap::new();
+
+ for (t, n) in &ops {
+ agg.add(t.clone(), *n);
+ *expected.entry(t.clone()).or_insert(0) += *n;
+ }
+
+ prop_assert_eq!(agg.drain(), expected);
+ }
+ }
+
+ #[test]
+ fn drain_clears_state() {
+ let mut agg = Aggregator::new();
+ agg.add(tuple(2, "$browser", "Chrome"), 1);
+
+ let first = agg.drain();
+ assert_eq!(first.len(), 1);
+ assert!(agg.is_empty());
+
+ let second = agg.drain();
+ assert!(second.is_empty());
+ }
+}
diff --git a/rust/property-vals-rs/src/fan_out.rs b/rust/property-vals-rs/src/fan_out.rs
new file mode 100644
index 000000000000..05888fd8261f
--- /dev/null
+++ b/rust/property-vals-rs/src/fan_out.rs
@@ -0,0 +1,279 @@
+use serde_json::Value;
+
+use crate::types::{Event, GroupIdentify, PropertyType, TupleKey};
+
+pub const MAX_PROPERTY_KEY_LEN: usize = 400;
+pub const MAX_PROPERTY_VALUE_LEN: usize = 255;
+
+pub fn fan_out(event: &Event) -> Vec<TupleKey> {
+ let mut out = Vec::new();
+
+ if let Some(raw) = &event.properties {
+ emit_from_blob(event.team_id, PropertyType::Event, raw, &mut out);
+ }
+ if let Some(raw) = &event.person_properties {
+ emit_from_blob(event.team_id, PropertyType::Person, raw, &mut out);
+ }
+
+ out
+}
+
+pub fn fan_out_group(event: &GroupIdentify) -> Vec<TupleKey> {
+ let mut out = Vec::new();
+ if let Some(raw) = &event.group_properties {
+ emit_from_blob(
+ event.team_id,
+ PropertyType::Group(event.group_type_index),
+ raw,
+ &mut out,
+ );
+ }
+ out
+}
+
+fn emit_from_blob(team_id: i64, property_type: PropertyType, raw: &str, out: &mut Vec<TupleKey>) {
+ let parsed: Value = match serde_json::from_str(raw) {
+ Ok(v) => v,
+ Err(_) => return,
+ };
+
+ let obj = match parsed.as_object() {
+ Some(o) => o,
+ None => return,
+ };
+
+ for (key, value) in obj {
+ if value.is_null() {
+ continue;
+ }
+
+ let property_value = coerce_to_string(value);
+
+ if key.is_empty() || key.chars().count() > MAX_PROPERTY_KEY_LEN {
+ continue;
+ }
+ if property_value.is_empty() || property_value.chars().count() > MAX_PROPERTY_VALUE_LEN {
+ continue;
+ }
+
+ out.push(TupleKey {
+ team_id,
+ property_type,
+ property_key: key.clone(),
+ property_value,
+ });
+ }
+}
+
+fn coerce_to_string(v: &Value) -> String {
+ match v {
+ Value::String(s) => s.clone(),
+ _ => v.to_string(),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use proptest::prelude::*;
+ use serde_json::{Map, Value};
+
+ fn event(properties: &str) -> Event {
+ Event {
+ team_id: 2,
+ properties: Some(properties.to_string()),
+ person_properties: None,
+ }
+ }
+
+ fn group_identify(group_type_index: u8, properties: &str) -> GroupIdentify {
+ GroupIdentify {
+ team_id: 2,
+ group_type_index,
+ group_properties: Some(properties.to_string()),
+ }
+ }
+
+ fn arb_property_string() -> impl Strategy<Value = String> {
+ prop_oneof!["[a-zA-Z0-9_$ -]{0,450}", r#"[\x{3042}\x{1F600}]{0,500}"#,]
+ }
+
+ fn arb_value() -> impl Strategy<Value = Value> {
+ prop_oneof![
+ arb_property_string().prop_map(Value::String),
+ any::<bool>().prop_map(Value::Bool),
+ any::<i64>().prop_map(|n| Value::Number(n.into())),
+ Just(Value::Null),
+ ]
+ }
+
+ prop_compose! {
+ fn arb_blob()(
+ pairs in prop::collection::vec((arb_property_string(), arb_value()), 0..20),
+ ) -> String {
+ let map: Map<String, Value> = pairs.into_iter().collect();
+ serde_json::to_string(&map).unwrap()
+ }
+ }
+
+ prop_compose! {
+ fn arb_event()(
+ team_id: i64,
+ properties in prop::option::of(arb_blob()),
+ person_properties in prop::option::of(arb_blob()),
+ ) -> Event {
+ Event { team_id, properties, person_properties }
+ }
+ }
+
+ prop_compose! {
+ fn arb_group_identify()(
+ team_id: i64,
+ group_type_index: u8,
+ group_properties in prop::option::of(arb_blob()),
+ ) -> GroupIdentify {
+ GroupIdentify { team_id, group_type_index, group_properties }
+ }
+ }
+
+ fn check_tuple_invariants(t: &TupleKey, expected_team: i64) {
+ assert_eq!(t.team_id, expected_team);
+ assert!(!t.property_key.is_empty());
+ assert!(!t.property_value.is_empty());
+ assert!(t.property_key.chars().count() <= MAX_PROPERTY_KEY_LEN);
+ assert!(t.property_value.chars().count() <= MAX_PROPERTY_VALUE_LEN);
+ }
+
+ proptest! {
+ #[test]
+ fn fan_out_outputs_obey_caps_and_team(e in arb_event()) {
+ for t in fan_out(&e) {
+ check_tuple_invariants(&t, e.team_id);
+ }
+ }
+
+ #[test]
+ fn fan_out_group_outputs_obey_caps_and_team(g in arb_group_identify()) {
+ for t in fan_out_group(&g) {
+ check_tuple_invariants(&t, g.team_id);
+ }
+ }
+
+ #[test]
+ fn fan_out_is_pure(e in arb_event()) {
+ prop_assert_eq!(fan_out(&e), fan_out(&e));
+ }
+
+ #[test]
+ fn fan_out_group_is_pure(g in arb_group_identify()) {
+ prop_assert_eq!(fan_out_group(&g), fan_out_group(&g));
+ }
+
+ #[test]
+ fn fan_out_group_property_type_matches_index(g in arb_group_identify()) {
+ for t in fan_out_group(&g) {
+ prop_assert_eq!(t.property_type, PropertyType::Group(g.group_type_index));
+ }
+ }
+ }
+
+ #[test]
+ fn event_property_produces_event_type_tuple() {
+ let tuples = fan_out(&event(r#"{"$browser":"Chrome"}"#));
+ assert_eq!(tuples.len(), 1);
+ assert_eq!(tuples[0].property_type, PropertyType::Event);
+ assert_eq!(tuples[0].property_key, "$browser");
+ assert_eq!(tuples[0].property_value, "Chrome");
+ }
+
+ #[test]
+ fn json_null_value_is_dropped() {
+ let tuples = fan_out(&event(r#"{"nullable_field":null}"#));
+ assert!(tuples.is_empty());
+ }
+
+ #[test]
+ fn empty_string_value_is_dropped() {
+ let tuples = fan_out(&event(r#"{"blank":""}"#));
+ assert!(tuples.is_empty());
+ }
+
+ #[test]
+ fn person_properties_emit_person_type() {
+ let ev = Event {
+ team_id: 2,
+ properties: None,
+ person_properties: Some(r#"{"email":"[email protected]"}"#.to_string()),
+ };
+ let tuples = fan_out(&ev);
+ assert_eq!(tuples.len(), 1);
+ assert_eq!(tuples[0].property_type, PropertyType::Person);
+ assert_eq!(tuples[0].property_key, "email");
+ assert_eq!(tuples[0].property_value, "[email protected]");
+ }
+
+ #[test]
+ fn bool_value_coerces_to_string() {
+ let tuples = fan_out(&event(r#"{"a_bool":true}"#));
+ assert_eq!(tuples.len(), 1);
+ assert_eq!(tuples[0].property_value, "true");
+ }
+
+ #[test]
+ fn number_value_coerces_to_string() {
+ let tuples = fan_out(&event(r#"{"a_number":42}"#));
+ assert_eq!(tuples.len(), 1);
+ assert_eq!(tuples[0].property_value, "42");
+ }
+
+ #[test]
+ fn unparseable_blob_emits_nothing() {
+ let tuples = fan_out(&event(r#"not valid json"#));
+ assert!(tuples.is_empty());
+ }
+
+ #[test]
+ fn empty_object_emits_nothing() {
+ let tuples = fan_out(&event("{}"));
+ assert!(tuples.is_empty());
+ }
+
+ #[test]
+ fn group_identify_index_0_emits_group_type() {
+ let tuples = fan_out_group(&group_identify(0, r#"{"plan":"enterprise"}"#));
+ assert_eq!(tuples.len(), 1);
+ assert_eq!(tuples[0].property_type, PropertyType::Group(0));
+ assert_eq!(tuples[0].property_key, "plan");
+ assert_eq!(tuples[0].property_value, "enterprise");
+ }
+
+ #[test]
+ fn group_identify_index_4_emits_group_4_type() {
+ let tuples = fan_out_group(&group_identify(4, r#"{"region":"us-east"}"#));
+ assert_eq!(tuples.len(), 1);
+ assert_eq!(tuples[0].property_type, PropertyType::Group(4));
+ }
+
+ #[test]
+ fn group_identify_high_index_still_emits() {
+ let tuples = fan_out_group(&group_identify(7, r#"{"plan":"enterprise"}"#));
+ assert_eq!(tuples.len(), 1);
+ assert_eq!(tuples[0].property_type, PropertyType::Group(7));
+ }
+
+ #[test]
+ fn group_identify_missing_properties_drops() {
+ let g = GroupIdentify {
+ team_id: 2,
+ group_type_index: 0,
+ group_properties: None,
+ };
+ assert!(fan_out_group(&g).is_empty());
+ }
+
+ #[test]
+ fn group_identify_unparseable_drops() {
+ let tuples = fan_out_group(&group_identify(0, "not valid json"));
+ assert!(tuples.is_empty());
+ }
+}
diff --git a/rust/property-vals-rs/src/lib.rs b/rust/property-vals-rs/src/lib.rs
index ef68c36943d4..385521254ef6 100644
--- a/rust/property-vals-rs/src/lib.rs
+++ b/rust/property-vals-rs/src/lib.rs
@@ -1 +1,4 @@
+pub mod aggregator;
pub mod config;
+pub mod fan_out;
+pub mod types;
diff --git a/rust/property-vals-rs/src/types.rs b/rust/property-vals-rs/src/types.rs
new file mode 100644
index 000000000000..020c19db6ab3
--- /dev/null
+++ b/rust/property-vals-rs/src/types.rs
@@ -0,0 +1,60 @@
+use serde::ser::{Serialize, Serializer};
+
+pub trait IngestableEvent: serde::de::DeserializeOwned + Send + Sync + 'static {
+ fn team_id(&self) -> i64;
+}
+
+#[derive(Debug, Clone, serde::Deserialize)]
+pub struct Event {
+ pub team_id: i64,
+
+ #[serde(default)]
+ pub properties: Option<String>,
+ #[serde(default)]
+ pub person_properties: Option<String>,
+}
+
+impl IngestableEvent for Event {
+ fn team_id(&self) -> i64 {
+ self.team_id
+ }
+}
+
+#[derive(Debug, Clone, serde::Deserialize)]
+pub struct GroupIdentify {
+ pub team_id: i64,
+ pub group_type_index: u8,
+ #[serde(default)]
+ pub group_properties: Option<String>,
+}
+
+impl IngestableEvent for GroupIdentify {
+ fn team_id(&self) -> i64 {
+ self.team_id
+ }
+}
+
+#[derive(Debug, Clone, Hash, Eq, PartialEq)]
+pub struct TupleKey {
+ pub team_id: i64,
+ pub property_type: PropertyType,
+ pub property_key: String,
+ pub property_value: String,
+}
+
+#[derive(Debug, Clone, Copy, Hash, Eq, PartialEq)]
+pub enum PropertyType {
+ Event,
+ Person,
+ Group(u8),
+}
+
+impl Serialize for PropertyType {
+ fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
+ match self {
+ PropertyType::Event => serializer.serialize_str("event"),
+ PropertyType::Person => serializer.serialize_str("person"),
+ PropertyType::Group(n) => serializer.serialize_str(&format!("group_{n}")),
+ }
+ }
+}