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(property-vals): compact binary wire format and hashed keys for intermediate topic (#63039)

Andy Zhao01ce9850f280
diff --git a/rust/common/kafka/src/kafka_consumer.rs b/rust/common/kafka/src/kafka_consumer.rs
index 0e632e4c3403..7b327ad66052 100644
--- a/rust/common/kafka/src/kafka_consumer.rs
+++ b/rust/common/kafka/src/kafka_consumer.rs
@@ -139,6 +139,14 @@ impl SingleTopicConsumer {
pub async fn json_recv<T>(&self) -> Result<(T, Offset), RecvErr>
where
T: DeserializeOwned,
+ {
+ self.recv_with(|payload| serde_json::from_slice(payload))
+ .await
+ }
+
+ pub async fn recv_with<T, D>(&self, decode: D) -> Result<(T, Offset), RecvErr>
+ where
+ D: Fn(&[u8]) -> Result<T, serde_json::Error>,
{
let message = self.inner.consumer.recv().await?;
@@ -155,7 +163,8 @@ impl SingleTopicConsumer {
return Err(RecvErr::Empty);
};
- let payload = match deserialize_json_payload(payload, &self.inner.topic) {
+ let payload = maybe_decompress_lz4_payload(payload, &self.inner.topic);
+ let payload = match decode(&payload) {
Ok(p) => p,
Err(e) => {
// We auto-store poison pills, panicking on failure
@@ -206,14 +215,6 @@ impl SingleTopicConsumer {
}
}
-fn deserialize_json_payload<T>(payload: &[u8], topic: &str) -> Result<T, serde_json::Error>
-where
- T: DeserializeOwned,
-{
- let payload = maybe_decompress_lz4_payload(payload, topic);
- serde_json::from_slice(&payload)
-}
-
fn maybe_decompress_lz4_payload<'a>(payload: &'a [u8], topic: &str) -> Cow<'a, [u8]> {
if !payload.starts_with(LZ4_FRAME_MAGIC) {
return Cow::Borrowed(payload);
@@ -348,13 +349,18 @@ mod tests {
use lz4::EncoderBuilder;
use serde_json::{json, Value};
- use super::{decompress_lz4_payload, deserialize_json_payload, Lz4PayloadError};
+ use super::{decompress_lz4_payload, maybe_decompress_lz4_payload, Lz4PayloadError};
+
+ fn decode_json_payload(payload: &[u8], topic: &str) -> Result<Value, serde_json::Error> {
+ let payload = maybe_decompress_lz4_payload(payload, topic);
+ serde_json::from_slice(&payload)
+ }
#[test]
fn deserializes_plain_json_payload() {
let payload = br#"{"event":"$pageview","team_id":1}"#;
- let parsed: Value = deserialize_json_payload(payload, "test-topic").unwrap();
+ let parsed: Value = decode_json_payload(payload, "test-topic").unwrap();
assert_eq!(parsed["event"], "$pageview");
assert_eq!(parsed["team_id"], 1);
@@ -365,7 +371,7 @@ mod tests {
let original = br#"{"event":"$pageview","team_id":1}"#;
let payload = lz4_payload(original);
- let parsed: Value = deserialize_json_payload(&payload, "test-topic").unwrap();
+ let parsed: Value = decode_json_payload(&payload, "test-topic").unwrap();
assert_eq!(parsed["event"], "$pageview");
assert_eq!(parsed["team_id"], 1);
@@ -375,7 +381,7 @@ mod tests {
fn invalid_lz4_payload_falls_back_to_json_error() {
let payload = [0x04, 0x22, 0x4d, 0x18, b'n', b'o', b'p', b'e'];
- assert!(deserialize_json_payload::<Value>(&payload, "test-topic").is_err());
+ assert!(decode_json_payload(&payload, "test-topic").is_err());
}
#[test]
diff --git a/rust/common/kafka/src/kafka_producer.rs b/rust/common/kafka/src/kafka_producer.rs
index d9557ab490e6..81c038b6df6f 100644
--- a/rust/common/kafka/src/kafka_producer.rs
+++ b/rust/common/kafka/src/kafka_producer.rs
@@ -232,6 +232,22 @@ where
.await
}
+pub async fn send_keyed_payloads_to_kafka_with_encoding<C: ClientContext>(
+ kafka_producer: &FutureProducer<C>,
+ topic: &str,
+ encoding: EnvelopeEncoding,
+ iter: impl IntoIterator<Item = (Option<String>, Vec<u8>)>,
+) -> Vec<Result<(), KafkaProduceError>> {
+ send_prepared_payloads_inner(
+ kafka_producer,
+ topic,
+ iter.into_iter()
+ .map(|(key, payload)| (key, None, Ok(payload))),
+ encoding,
+ )
+ .await
+}
+
async fn send_keyed_iter_to_kafka_inner<T, C: ClientContext>(
kafka_producer: &FutureProducer<C>,
topic: &str,
@@ -243,15 +259,33 @@ async fn send_keyed_iter_to_kafka_inner<T, C: ClientContext>(
where
T: Serialize,
{
+ let prepared = iter.into_iter().map(move |item| {
+ let key = key_extractor(&item);
+ let headers = headers_extractor(&item);
+ let payload = serde_json::to_vec(&item)
+ .map_err(|e| KafkaProduceError::SerializationError { error: e });
+ (key, headers, payload)
+ });
+ send_prepared_payloads_inner(kafka_producer, topic, prepared, encoding).await
+}
+
+async fn send_prepared_payloads_inner<C: ClientContext>(
+ kafka_producer: &FutureProducer<C>,
+ topic: &str,
+ iter: impl IntoIterator<
+ Item = (
+ Option<String>,
+ Option<rdkafka::message::OwnedHeaders>,
+ Result<Vec<u8>, KafkaProduceError>,
+ ),
+ >,
+ encoding: EnvelopeEncoding,
+) -> Vec<Result<(), KafkaProduceError>> {
let mut results = Vec::new();
let mut handles = Vec::new();
- for (index, item) in iter.into_iter().enumerate() {
- let key = key_extractor(&item);
- let headers = headers_extractor(&item);
- let json = match serde_json::to_vec(&item)
- .map_err(|e| KafkaProduceError::SerializationError { error: e })
- {
+ for (index, (key, headers, payload)) in iter.into_iter().enumerate() {
+ let json = match payload {
Ok(p) => p,
Err(e) => {
results.push((index, Err(e)));
diff --git a/rust/property-vals-rs/src/config.rs b/rust/property-vals-rs/src/config.rs
index 205c1e5a9809..2c21c8145e0c 100644
--- a/rust/property-vals-rs/src/config.rs
+++ b/rust/property-vals-rs/src/config.rs
@@ -7,6 +7,8 @@ use std::{num::ParseIntError, str::FromStr};
use common_continuous_profiling::ContinuousProfilingConfig;
use common_kafka::config::{ConsumerConfig, KafkaConfig};
use common_kafka::kafka_producer::EnvelopeEncoding;
+
+use crate::producer::WireFormat;
use envconfig::Envconfig;
use siphasher::sip::SipHasher13;
@@ -33,6 +35,9 @@ pub struct Config {
#[envconfig(default = "none")]
pub intermediate_topic_encoding: EnvelopeEncoding,
+ #[envconfig(default = "json")]
+ pub intermediate_topic_format: WireFormat,
+
#[envconfig(default = "clickhouse-property-vals-rs-merger")]
pub merger_consumer_group: String,
diff --git a/rust/property-vals-rs/src/lib.rs b/rust/property-vals-rs/src/lib.rs
index 381b2dfacbd6..615e0db636aa 100644
--- a/rust/property-vals-rs/src/lib.rs
+++ b/rust/property-vals-rs/src/lib.rs
@@ -5,4 +5,5 @@ pub mod metrics_consts;
pub mod producer;
pub mod seen_cache;
pub mod types;
+pub mod wire;
pub mod worker;
diff --git a/rust/property-vals-rs/src/main.rs b/rust/property-vals-rs/src/main.rs
index c38bf9a914d5..d0ec8db02b11 100644
--- a/rust/property-vals-rs/src/main.rs
+++ b/rust/property-vals-rs/src/main.rs
@@ -8,7 +8,7 @@ use lifecycle::{ComponentOptions, Manager};
use property_vals_rs::{
config::Config,
fan_out::{extract_tuple, fan_out, fan_out_group},
- producer::AggregatedProducer,
+ producer::{AggregatedProducer, WireFormat},
types::{Event, GroupIdentify, PropertyValueMessage},
worker::{worker_loop, ReductionConfig},
};
@@ -88,6 +88,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
groups_consumer_group = %config.groups_kafka_consumer_group,
intermediate_topic = %config.intermediate_topic,
intermediate_topic_encoding = ?config.intermediate_topic_encoding,
+ intermediate_topic_format = ?config.intermediate_topic_format,
merger_consumer_group = %config.merger_consumer_group,
output_topic = %config.output_topic,
flush_interval_secs = config.flush_interval_secs,
@@ -103,6 +104,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
config.intermediate_topic.clone(),
produce_timeout,
config.intermediate_topic_encoding,
+ config.intermediate_topic_format,
)
.await?;
@@ -116,6 +118,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
config.intermediate_topic.clone(),
produce_timeout,
config.intermediate_topic_encoding,
+ config.intermediate_topic_format,
)
.await?;
@@ -130,6 +133,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
config.output_topic.clone(),
produce_timeout,
EnvelopeEncoding::None,
+ WireFormat::Json,
)
.await?;
diff --git a/rust/property-vals-rs/src/producer.rs b/rust/property-vals-rs/src/producer.rs
index c4f5459e46c9..3db1ab56f196 100644
--- a/rust/property-vals-rs/src/producer.rs
+++ b/rust/property-vals-rs/src/producer.rs
@@ -1,17 +1,20 @@
+use std::hash::Hasher;
use std::time::Duration;
use async_trait::async_trait;
use common_kafka::config::KafkaConfig;
use common_kafka::kafka_producer::{
- create_kafka_producer, send_keyed_iter_to_kafka_with_encoding, EnvelopeEncoding, KafkaContext,
- KafkaProduceError,
+ create_kafka_producer, send_keyed_payloads_to_kafka_with_encoding, EnvelopeEncoding,
+ KafkaContext, KafkaProduceError,
};
use rdkafka::error::KafkaError;
use rdkafka::producer::FutureProducer;
+use siphasher::sip::SipHasher13;
use thiserror::Error;
use tracing::warn;
use crate::types::{PropertyType, TupleKey};
+use crate::wire;
#[derive(serde::Serialize)]
pub(crate) struct Outgoing<'a> {
@@ -22,6 +25,25 @@ pub(crate) struct Outgoing<'a> {
pub property_count: u64,
}
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
+pub enum WireFormat {
+ #[default]
+ Json,
+ Binary,
+}
+
+impl std::str::FromStr for WireFormat {
+ type Err = String;
+
+ fn from_str(s: &str) -> Result<Self, Self::Err> {
+ match s.trim().to_lowercase().as_ref() {
+ "json" => Ok(WireFormat::Json),
+ "binary" => Ok(WireFormat::Binary),
+ _ => Err(format!("Unknown WireFormat: {s}")),
+ }
+ }
+}
+
#[derive(Debug, Error)]
pub enum ProduceError {
#[error("kafka produce timed out after {0:?}")]
@@ -49,6 +71,7 @@ pub struct AggregatedProducer {
// intermediate topic, which the merger consumes; the output topic is read
// by ClickHouse and must stay `None`.
encoding: EnvelopeEncoding,
+ format: WireFormat,
}
impl AggregatedProducer {
@@ -58,6 +81,7 @@ impl AggregatedProducer {
output_topic: String,
produce_timeout: Duration,
encoding: EnvelopeEncoding,
+ format: WireFormat,
) -> Result<Self, KafkaError>
where
L: common_liveness::SyncLivenessReporter + Clone + 'static,
@@ -68,10 +92,29 @@ impl AggregatedProducer {
output_topic,
produce_timeout,
encoding,
+ format,
})
}
}
+/// Fixed-width partition key: a stable hash of the tuple. The same
+/// (team, type, key, value) tuple from any pod always lands on the same
+/// partition, so the merger can merge the per-pod duplicates that the
+/// events/groups workers emit across replicas. Hashing instead of embedding
+/// the full tuple keeps the key off the wire-bytes bill; collisions only
+/// co-locate unrelated tuples on a partition, which is harmless.
+pub(crate) fn partition_key(m: &Outgoing) -> String {
+ let mut hasher = SipHasher13::new_with_keys(0, 0);
+ hasher.write(m.team_id.to_string().as_bytes());
+ hasher.write(b":");
+ hasher.write(m.property_type.as_kafka_key_segment().as_bytes());
+ hasher.write(b":");
+ hasher.write(m.property_key.as_bytes());
+ hasher.write(b":");
+ hasher.write(m.property_value.as_bytes());
+ format!("{:016x}", hasher.finish())
+}
+
#[async_trait]
impl Producer for AggregatedProducer {
async fn produce(&self, items: Vec<(TupleKey, u64)>) -> Result<(), ProduceError> {
@@ -80,35 +123,39 @@ impl Producer for AggregatedProducer {
}
let total = items.len();
- let messages: Vec<Outgoing> = items
+ let format = self.format;
+ let payloads: Vec<(Option<String>, Vec<u8>)> = items
.iter()
- .map(|(tuple, count)| Outgoing {
- team_id: tuple.team_id,
- property_type: tuple.property_type,
- property_key: &tuple.property_key,
- property_value: &tuple.property_value,
- property_count: *count,
+ .map(|(tuple, count)| {
+ let message = Outgoing {
+ team_id: tuple.team_id,
+ property_type: tuple.property_type,
+ property_key: &tuple.property_key,
+ property_value: &tuple.property_value,
+ property_count: *count,
+ };
+ let key = Some(partition_key(&message));
+ let payload = match format {
+ WireFormat::Json => {
+ serde_json::to_vec(&message).expect("Outgoing serialization is infallible")
+ }
+ WireFormat::Binary => wire::encode(
+ message.team_id,
+ message.property_type,
+ message.property_key,
+ message.property_value,
+ message.property_count,
+ ),
+ };
+ (key, payload)
})
.collect();
- // Full-tuple partition key. The same (team, type, key, value) tuple
- // from any pod always lands on the same partition, so the merger on
- // the consuming side can merge the per-pod duplicates that the
- // events/groups workers emit across replicas.
- let send_fut = send_keyed_iter_to_kafka_with_encoding(
+ let send_fut = send_keyed_payloads_to_kafka_with_encoding(
&self.inner,
&self.output_topic,
- |m| {
- Some(format!(
- "{}:{}:{}:{}",
- m.team_id,
- m.property_type.as_kafka_key_segment(),
- m.property_key,
- m.property_value,
- ))
- },
self.encoding,
- messages,
+ payloads,
);
let results = match tokio::time::timeout(self.produce_timeout, send_fut).await {
@@ -130,3 +177,28 @@ impl Producer for AggregatedProducer {
Ok(())
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn outgoing<'a>(value: &'a str) -> Outgoing<'a> {
+ Outgoing {
+ team_id: 2,
+ property_type: PropertyType::Event,
+ property_key: "$current_url",
+ property_value: value,
+ property_count: 1,
+ }
+ }
+
+ #[test]
+ fn partition_key_is_stable_and_tuple_specific() {
+ let a = partition_key(&outgoing("https://posthog.com/a"));
+ let b = partition_key(&outgoing("https://posthog.com/a"));
+ let c = partition_key(&outgoing("https://posthog.com/b"));
+ assert_eq!(a, b);
+ assert_ne!(a, c);
+ assert_eq!(a.len(), 16);
+ }
+}
diff --git a/rust/property-vals-rs/src/types.rs b/rust/property-vals-rs/src/types.rs
index 7780f9dcf36a..8cace73d5e71 100644
--- a/rust/property-vals-rs/src/types.rs
+++ b/rust/property-vals-rs/src/types.rs
@@ -3,6 +3,10 @@ use serde::ser::{Serialize, Serializer};
pub trait IngestableEvent: serde::de::DeserializeOwned + Send + Sync + 'static {
fn team_id(&self) -> i64;
+
+ fn decode(payload: &[u8]) -> Result<Self, serde_json::Error> {
+ serde_json::from_slice(payload)
+ }
}
#[derive(Debug, Clone, serde::Deserialize)]
@@ -101,4 +105,13 @@ impl IngestableEvent for PropertyValueMessage {
fn team_id(&self) -> i64 {
self.team_id
}
+
+ // Intermediate-topic records may be compact binary (magic-prefixed) or
+ // JSON, depending on the producer's configured wire format.
+ fn decode(payload: &[u8]) -> Result<Self, serde_json::Error> {
+ if payload.starts_with(&crate::wire::MAGIC) {
+ return crate::wire::decode(payload).map_err(de::Error::custom);
+ }
+ serde_json::from_slice(payload)
+ }
}
diff --git a/rust/property-vals-rs/src/wire.rs b/rust/property-vals-rs/src/wire.rs
new file mode 100644
index 000000000000..8c0b10168cd3
--- /dev/null
+++ b/rust/property-vals-rs/src/wire.rs
@@ -0,0 +1,317 @@
+use std::fmt;
+
+use crate::types::{PropertyType, PropertyValueMessage};
+
+/// Compact binary format for intermediate topic records:
+///
+/// - magic + version header
+/// - team_id (varint)
+/// - type tag (0 = event, 1 = person, 2 = group + index byte)
+/// - key (varint length + utf8 bytes)
+/// - value (varint length + utf8 bytes)
+/// - count (varint)
+///
+/// The magic byte distinguishes records from JSON (`{`) and the LZ4 frame
+/// magic, so consumers can sniff which decoder to use.
+pub const MAGIC: [u8; 3] = *b"PV\x01";
+
+const TAG_EVENT: u8 = 0;
+const TAG_PERSON: u8 = 1;
+const TAG_GROUP: u8 = 2;
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct DecodeError(&'static str);
+
+impl fmt::Display for DecodeError {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ write!(f, "wire decode error: {}", self.0)
+ }
+}
+
+impl std::error::Error for DecodeError {}
+
+pub fn encode(
+ team_id: i64,
+ property_type: PropertyType,
+ property_key: &str,
+ property_value: &str,
+ property_count: u64,
+) -> Vec<u8> {
+ let mut buf =
+ Vec::with_capacity(3 + 10 + 2 + 5 + property_key.len() + 5 + property_value.len() + 10);
+ buf.extend_from_slice(&MAGIC);
+ put_varint(&mut buf, team_id as u64);
+ match property_type {
+ PropertyType::Event => buf.push(TAG_EVENT),
+ PropertyType::Person => buf.push(TAG_PERSON),
+ PropertyType::Group(n) => {
+ buf.push(TAG_GROUP);
+ buf.push(n);
+ }
+ }
+ put_str(&mut buf, property_key);
+ put_str(&mut buf, property_value);
+ put_varint(&mut buf, property_count);
+ buf
+}
+
+pub fn decode(buf: &[u8]) -> Result<PropertyValueMessage, DecodeError> {
+ if !buf.starts_with(&MAGIC) {
+ return Err(DecodeError("missing magic header"));
+ }
+ let mut pos = MAGIC.len();
+ let team_id = get_varint(buf, &mut pos)? as i64;
+ let property_type = match get_byte(buf, &mut pos)? {
+ TAG_EVENT => PropertyType::Event,
+ TAG_PERSON => PropertyType::Person,
+ TAG_GROUP => PropertyType::Group(get_byte(buf, &mut pos)?),
+ _ => return Err(DecodeError("unknown property type tag")),
+ };
+ let property_key = get_str(buf, &mut pos)?;
+ let property_value = get_str(buf, &mut pos)?;
+ let property_count = get_varint(buf, &mut pos)?;
+ if pos != buf.len() {
+ return Err(DecodeError("trailing bytes"));
+ }
+ Ok(PropertyValueMessage {
+ team_id,
+ property_type,
+ property_key,
+ property_value,
+ property_count,
+ })
+}
+
+fn put_varint(buf: &mut Vec<u8>, mut v: u64) {
+ loop {
+ let byte = (v & 0x7f) as u8;
+ v >>= 7;
+ if v == 0 {
+ buf.push(byte);
+ return;
+ }
+ buf.push(byte | 0x80);
+ }
+}
+
+fn get_varint(buf: &[u8], pos: &mut usize) -> Result<u64, DecodeError> {
+ let mut out: u64 = 0;
+ let mut shift = 0u32;
+ loop {
+ let byte = get_byte(buf, pos)?;
+ let bits = u64::from(byte & 0x7f);
+ // The round-trip check rejects payload bits that fall outside a u64,
+ // e.g. bits 1-6 of a 10th byte (shift 63), which `<<` drops silently.
+ if shift >= 64 || (bits << shift) >> shift != bits {
+ return Err(DecodeError("varint overflow"));
+ }
+ out |= bits << shift;
+ if byte & 0x80 == 0 {
+ return Ok(out);
+ }
+ shift += 7;
+ }
+}
+
+fn put_str(buf: &mut Vec<u8>, s: &str) {
+ put_varint(buf, s.len() as u64);
+ buf.extend_from_slice(s.as_bytes());
+}
+
+fn get_str(buf: &[u8], pos: &mut usize) -> Result<String, DecodeError> {
+ let len = get_varint(buf, pos)? as usize;
+ let end = pos.checked_add(len).ok_or(DecodeError("length overflow"))?;
+ if end > buf.len() {
+ return Err(DecodeError("string out of bounds"));
+ }
+ let s = std::str::from_utf8(&buf[*pos..end]).map_err(|_| DecodeError("invalid utf8"))?;
+ *pos = end;
+ Ok(s.to_string())
+}
+
+fn get_byte(buf: &[u8], pos: &mut usize) -> Result<u8, DecodeError> {
+ let b = *buf
+ .get(*pos)
+ .ok_or(DecodeError("unexpected end of buffer"))?;
+ *pos += 1;
+ Ok(b)
+}
+
+#[cfg(test)]
+mod tests {
+ use proptest::prelude::*;
+
+ use super::*;
+ use crate::producer::Outgoing;
+ use crate::types::IngestableEvent;
+
+ fn round_trip(team_id: i64, pt: PropertyType, key: &str, value: &str, count: u64) {
+ let buf = encode(team_id, pt, key, value, count);
+ let decoded = decode(&buf).unwrap();
+ assert_eq!(decoded.team_id, team_id);
+ assert_eq!(decoded.property_type, pt);
+ assert_eq!(decoded.property_key, key);
+ assert_eq!(decoded.property_value, value);
+ assert_eq!(decoded.property_count, count);
+ }
+
+ #[test]
+ fn round_trips_all_property_types() {
+ round_trip(
+ 2,
+ PropertyType::Event,
+ "$current_url",
+ "https://posthog.com/",
+ 3,
+ );
+ round_trip(1, PropertyType::Person, "email", "[email protected]", 1);
+ round_trip(i64::MAX, PropertyType::Group(0), "plan", "scale", u64::MAX);
+ round_trip(42, PropertyType::Group(255), "", "", 0);
+ round_trip(7, PropertyType::Event, "ключ", "значение🦔", 12345678901234);
+ }
+
+ #[test]
+ fn rejects_garbage_and_truncation() {
+ assert!(decode(b"not a wire record").is_err());
+ assert!(decode(&[]).is_err());
+ let buf = encode(2, PropertyType::Event, "k", "v", 1);
+ for cut in 0..buf.len() {
+ assert!(
+ decode(&buf[..cut]).is_err(),
+ "truncation at {cut} must error"
+ );
+ }
+ let mut trailing = buf.clone();
+ trailing.push(0);
+ assert!(decode(&trailing).is_err());
+ }
+
+ #[test]
+ fn rejects_varint_overflow() {
+ // count is the last field, so the buffer's final byte is the 10th
+ // byte of the u64::MAX varint (0x01, the only valid value there).
+ let buf = encode(2, PropertyType::Event, "k", "v", u64::MAX);
+ let last = buf.len() - 1;
+ assert_eq!(buf[last], 0x01);
+
+ for tenth_byte in [0x02, 0x7f] {
+ let mut corrupted = buf.clone();
+ corrupted[last] = tenth_byte;
+ assert!(
+ decode(&corrupted).is_err(),
+ "10th byte {tenth_byte:#04x} carries bits past u64 and must error"
+ );
+ }
+
+ let mut eleven_bytes = buf.clone();
+ eleven_bytes[last] = 0x81;
+ eleven_bytes.push(0x00);
+ assert!(decode(&eleven_bytes).is_err(), "11-byte varint must error");
+ }
+
+ #[test]
+ fn binary_is_smaller_than_json() {
+ let key = "$current_url";
+ let value = "https://us.posthog.com/project/2/insights/abc123";
+ let binary = encode(2, PropertyType::Event, key, value, 7).len();
+ let json = serde_json::json!({
+ "team_id": 2,
+ "property_type": "event",
+ "property_key": key,
+ "property_value": value,
+ "property_count": 7,
+ })
+ .to_string()
+ .len();
+ assert!(
+ binary < json / 2,
+ "binary {binary} should be under half of json {json}"
+ );
+ }
+
+ fn arb_property_type() -> impl Strategy<Value = PropertyType> {
+ prop_oneof![
+ Just(PropertyType::Event),
+ Just(PropertyType::Person),
+ any::<u8>().prop_map(PropertyType::Group),
+ ]
+ }
+
+ proptest! {
+ #[test]
+ fn round_trips_any_message(
+ team_id: i64,
+ property_type in arb_property_type(),
+ key in ".*",
+ value in ".*",
+ count: u64,
+ ) {
+ let decoded = decode(&encode(team_id, property_type, &key, &value, count)).unwrap();
+ prop_assert_eq!(decoded.team_id, team_id);
+ prop_assert_eq!(decoded.property_type, property_type);
+ prop_assert_eq!(decoded.property_key, key);
+ prop_assert_eq!(decoded.property_value, value);
+ prop_assert_eq!(decoded.property_count, count);
+ }
+
+ // Flipping the producer's wire format must not change what the
+ // merger sees: both encodings of a message decode identically.
+ #[test]
+ fn binary_and_json_decode_agree(
+ team_id: i64,
+ property_type in arb_property_type(),
+ key in ".*",
+ value in ".*",
+ count: u64,
+ ) {
+ let json = serde_json::to_vec(&Outgoing {
+ team_id,
+ property_type,
+ property_key: &key,
+ property_value: &value,
+ property_count: count,
+ })
+ .unwrap();
+ let binary = encode(team_id, property_type, &key, &value, count);
+
+ let from_json = PropertyValueMessage::decode(&json).unwrap();
+ let from_binary = PropertyValueMessage::decode(&binary).unwrap();
+ prop_assert_eq!(&from_json.team_id, &from_binary.team_id);
+ prop_assert_eq!(&from_json.property_type, &from_binary.property_type);
+ prop_assert_eq!(&from_json.property_key, &from_binary.property_key);
+ prop_assert_eq!(&from_json.property_value, &from_binary.property_value);
+ prop_assert_eq!(&from_json.property_count, &from_binary.property_count);
+ }
+
+ // Random bytes after a valid magic drive the parser deep into the
+ // varint/string paths; it must reject or accept, never panic.
+ #[test]
+ fn decode_never_panics(garbage in proptest::collection::vec(any::<u8>(), 0..256)) {
+ drop(decode(&garbage));
+ let mut with_magic = MAGIC.to_vec();
+ with_magic.extend_from_slice(&garbage);
+ drop(decode(&with_magic));
+ }
+
+ #[test]
+ fn corrupted_encodings_never_panic_and_truncations_error(
+ team_id: i64,
+ property_type in arb_property_type(),
+ key in ".*",
+ value in ".*",
+ count: u64,
+ flipped_byte in any::<prop::sample::Index>(),
+ flipped_bit in 0u8..8,
+ ) {
+ let buf = encode(team_id, property_type, &key, &value, count);
+
+ let mut corrupted = buf.clone();
+ let i = flipped_byte.index(corrupted.len());
+ corrupted[i] ^= 1 << flipped_bit;
+ drop(decode(&corrupted));
+
+ let cut = flipped_byte.index(buf.len());
+ prop_assert!(decode(&buf[..cut]).is_err(), "truncation at {} must error", cut);
+ }
+ }
+}
diff --git a/rust/property-vals-rs/src/worker.rs b/rust/property-vals-rs/src/worker.rs
index 1ad17218614f..51f645a4b687 100644
--- a/rust/property-vals-rs/src/worker.rs
+++ b/rust/property-vals-rs/src/worker.rs
@@ -66,7 +66,7 @@ pub async fn worker_loop<E, P, F>(
handle.report_healthy();
flush(&mut aggregator, &mut pending_offsets, &producer, FLUSH_REASON_TIMER, worker, reduction.max_values_per_key, seen_cache.as_ref()).await;
}
- recv = consumer.json_recv::<E>() => {
+ recv = consumer.recv_with(E::decode) => {
handle.report_healthy();
match recv {
Ok((event, offset)) => {