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.

perf(cohorts): avoid unnecessary str parse (#66714)

Matheus Batista2835f248a799
diff --git a/rust/cohort-event-shuffler/src/consumer.rs b/rust/cohort-event-shuffler/src/consumer.rs
index 90bce0fc2d22..2a21fe7389fd 100644
--- a/rust/cohort-event-shuffler/src/consumer.rs
+++ b/rust/cohort-event-shuffler/src/consumer.rs
@@ -7,10 +7,11 @@ use std::sync::Arc;
use std::time::Duration;
use anyhow::{Context, Result};
-use common_kafka::kafka_consumer::{RecvErr, SingleTopicConsumer};
+use common_kafka::kafka_consumer::{Offset, RecvErr, SingleTopicConsumer};
use common_types::ClickHouseEvent;
use lifecycle::Handle;
use metrics::counter;
+use serde::{de::IgnoredAny, Deserialize};
use tracing::{debug, error, info, warn};
use crate::event::CohortStreamEvent;
@@ -21,24 +22,70 @@ use crate::observability::metrics::{
};
use crate::producer::CohortStreamProducer;
-/// `Forward` carries the moved-out `person_id` so the forward path needs no clone.
-#[derive(Debug, Clone, PartialEq, Eq)]
-pub enum ForwardDecision {
- Forward { person_id: String },
+/// Only the fields the team gate needs. Every undeclared field (notably the large
+/// `properties` / `person_properties` / `groupN_properties` JSON-string blobs) is skipped by
+/// `serde_json` without unescaping or allocating, instead of being materialized.
+#[derive(Deserialize)]
+struct GateFields {
+ team_id: i32,
+ /// `IgnoredAny` detects presence without allocating the value: absent and `null` deserialize to
+ /// `None`, any present non-null value to `Some`.
+ #[serde(default)]
+ person_id: Option<IgnoredAny>,
+}
+
+#[derive(Debug, PartialEq, Eq)]
+enum GateOutcome {
+ Forward,
+ DropNoPersonId,
+ SkipTeamGate,
+}
+
+/// `person_id` is checked first: a missing routing key is attributed to `DropNoPersonId` even when
+/// the team would also be skipped.
+fn classify_gate(gate: &GateFields, team_index: &TeamIndex) -> GateOutcome {
+ if gate.person_id.is_none() {
+ return GateOutcome::DropNoPersonId;
+ }
+ if !team_index.contains(gate.team_id) {
+ return GateOutcome::SkipTeamGate;
+ }
+ GateOutcome::Forward
+}
+
+/// `event` is boxed to keep the enum small: `Forward` is the only large variant and is built only
+/// for survivors, so the drop/skip majority filling the batch `Vec` stays cheap to move.
+#[derive(Debug)]
+enum Decoded {
+ Forward {
+ event: Box<ClickHouseEvent>,
+ person_id: String,
+ },
DropNoPersonId,
SkipTeamGate,
}
-/// Takes `person_id` by `take()` to avoid a clone; `person_id` is checked first because a missing
-/// routing key disqualifies the event regardless of the team gate.
-pub fn classify(event: &mut ClickHouseEvent, team_index: &TeamIndex) -> ForwardDecision {
- let Some(person_id) = event.person_id.take() else {
- return ForwardDecision::DropNoPersonId;
- };
- if !team_index.contains(event.team_id) {
- return ForwardDecision::SkipTeamGate;
+/// Cheap gate parse for every event; a full `ClickHouseEvent` parse only for survivors, over the
+/// same bytes so forwarded envelopes are byte-identical to a single-parse path.
+fn decode_gated(payload: &[u8], team_index: &TeamIndex) -> Result<Decoded, serde_json::Error> {
+ let gate: GateFields = serde_json::from_slice(payload)?;
+ match classify_gate(&gate, team_index) {
+ GateOutcome::DropNoPersonId => Ok(Decoded::DropNoPersonId),
+ GateOutcome::SkipTeamGate => Ok(Decoded::SkipTeamGate),
+ GateOutcome::Forward => {
+ let mut event: ClickHouseEvent = serde_json::from_slice(payload)?;
+ let Some(person_id) = event.person_id.take() else {
+ // Unreachable: the gate saw a present non-null person_id, and a non-string one would
+ // have failed the full parse above. Fail safe instead of panicking.
+ warn!("gate-forwarded event had no person_id after full parse; dropping");
+ return Ok(Decoded::DropNoPersonId);
+ };
+ Ok(Decoded::Forward {
+ event: Box::new(event),
+ person_id,
+ })
+ }
}
- ForwardDecision::Forward { person_id }
}
pub struct EventShuffler {
@@ -102,10 +149,7 @@ impl EventShuffler {
return Ok(0);
}
- let results = self
- .consumer
- .json_recv_batch::<ClickHouseEvent>(self.batch_size, self.batch_timeout)
- .await;
+ let results = self.recv_gated_batch().await;
if results.is_empty() {
return Ok(0);
}
@@ -117,7 +161,7 @@ impl EventShuffler {
let mut offsets = Vec::with_capacity(results.len());
for result in results {
- let (mut event, offset) = match result {
+ let (decoded, offset) = match result {
Ok(pair) => pair,
Err(err) => {
// Poison pills are already offset-stored by the consumer; just log.
@@ -130,17 +174,17 @@ impl EventShuffler {
let source_partition = offset.partition();
let source_offset = offset.get_value();
- match classify(&mut event, &self.team_index) {
- ForwardDecision::Forward { person_id } => {
+ match decoded {
+ Decoded::Forward { event, person_id } => {
forwardable.push(CohortStreamEvent::from_clickhouse(
- event,
+ *event,
person_id,
source_partition,
source_offset,
))
}
- ForwardDecision::DropNoPersonId => dropped += 1,
- ForwardDecision::SkipTeamGate => skipped += 1,
+ Decoded::DropNoPersonId => dropped += 1,
+ Decoded::SkipTeamGate => skipped += 1,
}
offsets.push(offset);
@@ -187,6 +231,32 @@ impl EventShuffler {
Ok(consumed as usize)
}
+
+ /// Local mirror of [`SingleTopicConsumer::json_recv_batch`] that decodes via [`decode_gated`]
+ /// instead of a blanket full parse.
+ async fn recv_gated_batch(&self) -> Vec<Result<(Decoded, Offset), RecvErr>> {
+ let team_index: &TeamIndex = &self.team_index;
+ let mut results = Vec::with_capacity(self.batch_size);
+
+ tokio::select! {
+ _ = tokio::time::sleep(self.batch_timeout) => {}
+ _ = async {
+ while results.len() < self.batch_size {
+ let result = self
+ .consumer
+ .recv_with(|payload| decode_gated(payload, team_index))
+ .await;
+ let was_err = result.is_err();
+ results.push(result);
+ if was_err {
+ break; // an error may be kafka-level, not just a bad payload
+ }
+ }
+ } => {}
+ }
+
+ results
+ }
}
fn log_recv_error(err: &RecvErr) {
@@ -201,64 +271,162 @@ fn log_recv_error(err: &RecvErr) {
mod tests {
use super::*;
use crate::event::sample_clickhouse_event;
+ use serde_json::{json, Value};
fn index_with(teams: &[i32]) -> TeamIndex {
TeamIndex::from_teams(teams.iter().copied())
}
+ fn gate_fields(team_id: i32, person_id: Option<IgnoredAny>) -> GateFields {
+ GateFields { team_id, person_id }
+ }
+
#[test]
- fn classify_covers_every_gate_outcome() {
+ fn classify_gate_covers_every_gate_outcome() {
let cases = [
(
"forward",
- Some("p"),
- 2,
- vec![2],
- ForwardDecision::Forward {
- person_id: "p".to_string(),
- },
- ),
- (
- "no person",
- None,
+ Some(IgnoredAny),
2,
vec![2],
- ForwardDecision::DropNoPersonId,
+ GateOutcome::Forward,
),
+ ("no person", None, 2, vec![2], GateOutcome::DropNoPersonId),
(
"team gate",
- Some("p"),
+ Some(IgnoredAny),
99,
vec![2],
- ForwardDecision::SkipTeamGate,
+ GateOutcome::SkipTeamGate,
),
(
"no person precedence",
None,
99,
vec![2],
- ForwardDecision::DropNoPersonId,
+ GateOutcome::DropNoPersonId,
),
(
"empty index",
- Some("p"),
+ Some(IgnoredAny),
2,
vec![],
- ForwardDecision::SkipTeamGate,
+ GateOutcome::SkipTeamGate,
),
];
for (name, person_id, team_id, teams, expected) in cases {
- let mut event = sample_clickhouse_event(team_id, person_id);
let index = index_with(&teams);
- assert_eq!(classify(&mut event, &index), expected, "case: {name}");
+ assert_eq!(
+ classify_gate(&gate_fields(team_id, person_id), &index),
+ expected,
+ "case: {name}"
+ );
}
}
#[test]
fn unloaded_index_forwards_nothing() {
let index = TeamIndex::new();
- let mut event = sample_clickhouse_event(2, Some("p"));
- assert_eq!(classify(&mut event, &index), ForwardDecision::SkipTeamGate);
+ assert_eq!(
+ classify_gate(&gate_fields(2, Some(IgnoredAny)), &index),
+ GateOutcome::SkipTeamGate
+ );
+ }
+
+ #[test]
+ fn dropped_event_never_materializes_blobs() {
+ // A JSON-object `properties` fails the full parse (the field is a stringified blob): outside
+ // the index the gate ignores the blob and skips; inside it the survivor parse rejects it.
+ let mut value: Value =
+ serde_json::to_value(sample_clickhouse_event(99, Some("p"))).unwrap();
+ value["properties"] = json!({ "a": [1, 2, 3] });
+ let payload = serde_json::to_vec(&value).unwrap();
+
+ assert!(matches!(
+ decode_gated(&payload, &index_with(&[2])).unwrap(),
+ Decoded::SkipTeamGate
+ ));
+ assert!(decode_gated(&payload, &index_with(&[99])).is_err());
+ }
+
+ #[test]
+ fn missing_person_mode_skips_mismatched_team_instead_of_erroring() {
+ // `person_mode` is required by the full parse but ignored by the gate.
+ let mut value: Value =
+ serde_json::to_value(sample_clickhouse_event(99, Some("p"))).unwrap();
+ value.as_object_mut().unwrap().remove("person_mode");
+ let payload = serde_json::to_vec(&value).unwrap();
+
+ assert!(matches!(
+ decode_gated(&payload, &index_with(&[2])).unwrap(),
+ Decoded::SkipTeamGate
+ ));
+ }
+
+ #[test]
+ fn person_id_presence_matches_full_parse_semantics() {
+ let index = index_with(&[2]);
+ let base: Value =
+ serde_json::to_value(sample_clickhouse_event(2, Some("ignored"))).unwrap();
+ let decode =
+ |value: Value| decode_gated(&serde_json::to_vec(&value).unwrap(), &index).unwrap();
+
+ // Absent: drop (person check runs before the team gate).
+ let mut absent = base.clone();
+ absent.as_object_mut().unwrap().remove("person_id");
+ assert!(matches!(decode(absent), Decoded::DropNoPersonId));
+
+ // `null`: drop.
+ let mut null = base.clone();
+ null["person_id"] = Value::Null;
+ assert!(matches!(decode(null), Decoded::DropNoPersonId));
+
+ // Empty string is present: forward.
+ let mut empty = base.clone();
+ empty["person_id"] = json!("");
+ match decode(empty) {
+ Decoded::Forward { event, person_id } => {
+ assert_eq!(person_id, "");
+ assert!(
+ event.person_id.is_none(),
+ "person_id must be taken from the event"
+ );
+ }
+ other => panic!("expected Forward, got {other:?}"),
+ }
+
+ // Valid string: forward.
+ let mut valid = base.clone();
+ valid["person_id"] = json!("p");
+ match decode(valid) {
+ Decoded::Forward { event, person_id } => {
+ assert_eq!(person_id, "p");
+ assert!(event.person_id.is_none());
+ }
+ other => panic!("expected Forward, got {other:?}"),
+ }
+ }
+
+ #[test]
+ fn survivor_fully_materializes_the_forward_envelope() {
+ let payload = serde_json::to_vec(&sample_clickhouse_event(2, Some("p"))).unwrap();
+ match decode_gated(&payload, &index_with(&[2])).unwrap() {
+ Decoded::Forward { event, person_id } => {
+ assert_eq!(person_id, "p");
+ assert_eq!(event.team_id, 2);
+ assert!(event.person_id.is_none(), "person_id should be taken");
+ // Blobs skipped on the drop path are fully parsed for survivors.
+ assert_eq!(
+ event.properties.as_deref(),
+ Some(r#"{"$current_url":"/pricing"}"#)
+ );
+ assert_eq!(
+ event.person_properties.as_deref(),
+ Some(r#"{"email":"[email protected]"}"#)
+ );
+ }
+ other => panic!("expected Forward, got {other:?}"),
+ }
}
}
diff --git a/rust/cohort-event-shuffler/src/event.rs b/rust/cohort-event-shuffler/src/event.rs
index 0ea0135c88b9..8385a1be8143 100644
--- a/rust/cohort-event-shuffler/src/event.rs
+++ b/rust/cohort-event-shuffler/src/event.rs
@@ -33,8 +33,8 @@ pub struct CohortStreamEvent {
}
impl CohortStreamEvent {
- /// Moves every owned field out of `event` rather than cloning; `person_id` is already extracted
- /// by [`crate::consumer::classify`].
+ /// Moves every owned field out of `event` rather than cloning; `person_id` is extracted
+ /// upstream and passed in separately.
pub fn from_clickhouse(
event: ClickHouseEvent,
person_id: String,
diff --git a/rust/cohort-event-shuffler/src/observability/metrics.rs b/rust/cohort-event-shuffler/src/observability/metrics.rs
index 113aaa54a1f3..db6c1ce5473a 100644
--- a/rust/cohort-event-shuffler/src/observability/metrics.rs
+++ b/rust/cohort-event-shuffler/src/observability/metrics.rs
@@ -2,7 +2,8 @@
use metrics_exporter_prometheus::{PrometheusBuilder, PrometheusHandle};
-/// Every consumed message, forwarded or not.
+/// Every message that passed the gate parse, forwarded or not. The gate ignores most fields, so a
+/// skipped event that is invalid only on an ignored field (e.g. missing `person_mode`) still counts.
pub const EVENTS_CONSUMED: &str = "shuffler_events_consumed_total";
pub const EVENTS_FORWARDED: &str = "shuffler_events_forwarded_total";
pub const EVENTS_DROPPED_NO_PERSON_ID: &str = "shuffler_events_dropped_no_person_id_total";