: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(capture): event routing full parity for capture v1 (#57900)
Eli Reisman13d6f58f85b7
diff --git a/rust/capture/src/v1/analytics/process.rs b/rust/capture/src/v1/analytics/process.rsindex 70eb66122122..792e45e03312 100644--- a/rust/capture/src/v1/analytics/process.rs+++ b/rust/capture/src/v1/analytics/process.rs@@ -20,6 +20,16 @@ use crate::v1::context::Context;use crate::v1::sinks::Destination;use crate::v1::Error;+/// Maps event name to its Kafka destination, mirroring legacy DataType assignment.+fn destination_for_event_name(name: &str) -> Destination {+ match name {+ "$exception" => Destination::ExceptionErrorTracking,+ "$$heatmap" => Destination::HeatmapMain,+ "$$client_ingestion_warning" => Destination::ClientIngestionWarning,+ _ => Destination::AnalyticsMain,+ }+}+pub async fn process_batch(state: &router::State,context: &mut Context,@@ -84,6 +94,8 @@ fn validate_events(context: &Context, batch: Batch) -> Result<Vec<WrappedEvent>,return Err(Error::DuplicateEventUuid(event.uuid().to_owned()));}+ let destination = destination_for_event_name(&event.event);+match validate_event(&event) {Ok(raw_ts) => {metrics::counter!(CAPTURE_V1_PARSED_EVENTS, "result" => "valid").increment(1);@@ -94,7 +106,7 @@ fn validate_events(context: &Context, batch: Batch) -> Result<Vec<WrappedEvent>,adjusted_timestamp: Some(adjusted),result: EventResult::Ok,details: None,- destination: Destination::default(),+ destination,force_disable_person_processing: false,});}@@ -105,7 +117,7 @@ fn validate_events(context: &Context, batch: Batch) -> Result<Vec<WrappedEvent>,adjusted_timestamp: None,result: EventResult::Drop,details: Some(err.tag()),- destination: Destination::default(),+ destination,force_disable_person_processing: false,});}@@ -248,7 +260,7 @@ async fn apply_restrictions(events: &mut [WrappedEvent],) {for event in events.iter_mut() {- if event.result != EventResult::Ok {+ if event.result != EventResult::Ok || !event.destination.is_analytics_pipeline() {continue;}@@ -1032,6 +1044,82 @@ mod tests {assert_eq!(ev.destination, Destination::AnalyticsMain);}+ // --- destination_for_event_name ---++ #[rstest::rstest]+ #[case("$exception", Destination::ExceptionErrorTracking)]+ #[case("$$heatmap", Destination::HeatmapMain)]+ #[case("$$client_ingestion_warning", Destination::ClientIngestionWarning)]+ #[case("$pageview", Destination::AnalyticsMain)]+ #[case("custom_event", Destination::AnalyticsMain)]+ #[case("$autocapture", Destination::AnalyticsMain)]+ fn destination_for_event_name_mapping(#[case] event_name: &str, #[case] expected: Destination) {+ assert_eq!(destination_for_event_name(event_name), expected);+ }++ // --- restrictions bypass non-analytics events ---++ #[rstest::rstest]+ #[case("$exception", Destination::ExceptionErrorTracking)]+ #[case("$$heatmap", Destination::HeatmapMain)]+ #[case("$$client_ingestion_warning", Destination::ClientIngestionWarning)]+ #[tokio::test]+ async fn restrictions_skip_non_analytics_events(+ #[case] event_name: &str,+ #[case] expected_dest: Destination,+ ) {+ let service = restriction_service(+ "phc_token",+ vec![Restriction {+ restriction_type: RestrictionType::DropEvent,+ scope: RestrictionScope::AllEvents,+ args: None,+ }],+ )+ .await;++ let mut ev = wrapped_event(event_name, "user-1");+ ev.destination = expected_dest.clone();+ let mut events = vec![ev];+ let now_ts = Utc::now().timestamp();++ apply_restrictions(&service, "phc_token", now_ts, &mut events).await;++ // Non-analytics events are untouched by restrictions+ assert_eq!(events[0].result, EventResult::Ok);+ assert_eq!(events[0].destination, expected_dest);+ }++ #[tokio::test]+ async fn restrictions_still_apply_to_analytics_events() {+ let service = restriction_service(+ "phc_token",+ vec![Restriction {+ restriction_type: RestrictionType::DropEvent,+ scope: RestrictionScope::AllEvents,+ args: None,+ }],+ )+ .await;++ let mut events = vec![+ wrapped_event("$pageview", "user-1"),+ wrapped_event("$exception", "user-2"),+ ];+ // Simulate what validate_events does+ events[1].destination = Destination::ExceptionErrorTracking;+ let now_ts = Utc::now().timestamp();++ apply_restrictions(&service, "phc_token", now_ts, &mut events).await;++ // Analytics event gets dropped by restriction+ assert_eq!(events[0].result, EventResult::Drop);+ assert_eq!(events[0].destination, Destination::Drop);+ // Non-analytics event bypasses restriction+ assert_eq!(events[1].result, EventResult::Ok);+ assert_eq!(events[1].destination, Destination::ExceptionErrorTracking);+ }+// --- apply_token_distinct_id_limits ---use async_trait::async_trait;diff --git a/rust/capture/src/v1/sinks/kafka/config.rs b/rust/capture/src/v1/sinks/kafka/config.rsindex 817f74386de5..853bdc9f36cd 100644--- a/rust/capture/src/v1/sinks/kafka/config.rs+++ b/rust/capture/src/v1/sinks/kafka/config.rs@@ -109,6 +109,11 @@ pub struct Config {pub topic_historical: String,pub topic_overflow: String,pub topic_dlq: String,++ // -- Non-analytics topics (also required) --+ pub topic_exception: String,+ pub topic_heatmap: String,+ pub topic_client_ingestion_warning: String,}const VALID_ACKS: &[&str] = &["0", "1", "-1", "all"];@@ -160,6 +165,9 @@ impl Config {Destination::AnalyticsHistorical => Some(&self.topic_historical),Destination::Overflow => Some(&self.topic_overflow),Destination::Dlq => Some(&self.topic_dlq),+ Destination::ExceptionErrorTracking => Some(&self.topic_exception),+ Destination::HeatmapMain => Some(&self.topic_heatmap),+ Destination::ClientIngestionWarning => Some(&self.topic_client_ingestion_warning),Destination::Custom(t) => Some(t.as_str()),Destination::Drop => None,}@@ -171,8 +179,10 @@ mod tests {use std::collections::HashMap;use envconfig::Envconfig;+ use rstest::rstest;use super::Config;+ use crate::v1::sinks::Destination;fn required_kafka_env() -> HashMap<String, String> {[@@ -181,6 +191,9 @@ mod tests {("TOPIC_HISTORICAL", "events_hist"),("TOPIC_OVERFLOW", "events_overflow"),("TOPIC_DLQ", "events_dlq"),+ ("TOPIC_EXCEPTION", "error_tracking_events"),+ ("TOPIC_HEATMAP", "heatmaps_ingestion"),+ ("TOPIC_CLIENT_INGESTION_WARNING", "events_plugin_ingestion"),].into_iter().map(|(k, v)| (k.to_string(), v.to_string()))@@ -283,18 +296,22 @@ mod tests {assert_eq!(cfg.socket_receive_buffer_bytes, 0);}- #[test]- fn missing_required_hosts() {+ #[rstest]+ #[case("HOSTS")]+ #[case("TOPIC_MAIN")]+ #[case("TOPIC_HISTORICAL")]+ #[case("TOPIC_OVERFLOW")]+ #[case("TOPIC_DLQ")]+ #[case("TOPIC_EXCEPTION")]+ #[case("TOPIC_HEATMAP")]+ #[case("TOPIC_CLIENT_INGESTION_WARNING")]+ fn missing_required_field_errors(#[case] key: &str) {let mut env = required_kafka_env();- env.remove("HOSTS");- assert!(Config::init_from_hashmap(&env).is_err());- }-- #[test]- fn missing_required_topic() {- let mut env = required_kafka_env();- env.remove("TOPIC_MAIN");- assert!(Config::init_from_hashmap(&env).is_err());+ env.remove(key);+ assert!(+ Config::init_from_hashmap(&env).is_err(),+ "{key} should be required"+ );}#[test]@@ -372,4 +389,18 @@ mod tests {cfg.metadata_max_age_ms = 15000;assert!(cfg.validate().is_ok(), "exactly 3x should pass");}++ #[rstest]+ #[case(Destination::AnalyticsMain, Some("events_main"))]+ #[case(Destination::AnalyticsHistorical, Some("events_hist"))]+ #[case(Destination::Overflow, Some("events_overflow"))]+ #[case(Destination::Dlq, Some("events_dlq"))]+ #[case(Destination::ExceptionErrorTracking, Some("error_tracking_events"))]+ #[case(Destination::HeatmapMain, Some("heatmaps_ingestion"))]+ #[case(Destination::ClientIngestionWarning, Some("events_plugin_ingestion"))]+ #[case(Destination::Drop, None)]+ fn topic_for_resolves_destination(#[case] dest: Destination, #[case] expected: Option<&str>) {+ let cfg = Config::init_from_hashmap(&required_kafka_env()).unwrap();+ assert_eq!(cfg.topic_for(&dest), expected);+ }}diff --git a/rust/capture/src/v1/sinks/kafka/sink_tests.rs b/rust/capture/src/v1/sinks/kafka/sink_tests.rsindex 971947cc63a9..b22da54a66e5 100644--- a/rust/capture/src/v1/sinks/kafka/sink_tests.rs+++ b/rust/capture/src/v1/sinks/kafka/sink_tests.rs@@ -689,6 +689,9 @@ fn sink_name_returns_configured_name() {#[case::overflow(Destination::Overflow, "events_overflow")]#[case::dlq(Destination::Dlq, "events_dlq")]#[case::custom(Destination::Custom("my_topic".into()), "my_topic")]+#[case::exception(Destination::ExceptionErrorTracking, "error_tracking_events")]+#[case::heatmap(Destination::HeatmapMain, "heatmaps_ingestion")]+#[case::client_ingestion_warning(Destination::ClientIngestionWarning, "events_plugin_ingestion")]#[tokio::test]async fn destination_routes_to_correct_topic(#[case] destination: Destination,diff --git a/rust/capture/src/v1/sinks/mod.rs b/rust/capture/src/v1/sinks/mod.rsindex 2690ea1960db..c9d71de92702 100644--- a/rust/capture/src/v1/sinks/mod.rs+++ b/rust/capture/src/v1/sinks/mod.rs@@ -229,6 +229,18 @@ mod tests {"events_overflow".into(),),(format!("{prefix}KAFKA_TOPIC_DLQ"), "events_dlq".into()),+ (+ format!("{prefix}KAFKA_TOPIC_EXCEPTION"),+ "error_tracking_events".into(),+ ),+ (+ format!("{prefix}KAFKA_TOPIC_HEATMAP"),+ "heatmaps_ingestion".into(),+ ),+ (+ format!("{prefix}KAFKA_TOPIC_CLIENT_INGESTION_WARNING"),+ "events_plugin_ingestion".into(),+ ),].into_iter().collect()diff --git a/rust/capture/src/v1/sinks/types.rs b/rust/capture/src/v1/sinks/types.rsindex 5185633b55c4..17a23086f07f 100644--- a/rust/capture/src/v1/sinks/types.rs+++ b/rust/capture/src/v1/sinks/types.rs@@ -15,6 +15,40 @@ pub enum Destination {Dlq,Custom(String),Drop,+ ExceptionErrorTracking,+ HeatmapMain,+ ClientIngestionWarning,+}++impl Destination {+ /// Returns true for destinations that flow through the analytics ingestion+ /// pipeline (and are therefore subject to analytics-scoped restrictions,+ /// overflow routing, etc). Mirrors legacy `DataType::is_analytics_pipeline`.+ pub fn is_analytics_pipeline(&self) -> bool {+ matches!(self, Self::AnalyticsMain | Self::AnalyticsHistorical)+ }+}++#[cfg(test)]+mod destination_tests {+ use super::Destination;++ #[test]+ fn is_analytics_pipeline_true_for_main_and_historical() {+ assert!(Destination::AnalyticsMain.is_analytics_pipeline());+ assert!(Destination::AnalyticsHistorical.is_analytics_pipeline());+ }++ #[test]+ fn is_analytics_pipeline_false_for_non_analytics() {+ assert!(!Destination::ExceptionErrorTracking.is_analytics_pipeline());+ assert!(!Destination::HeatmapMain.is_analytics_pipeline());+ assert!(!Destination::ClientIngestionWarning.is_analytics_pipeline());+ assert!(!Destination::Overflow.is_analytics_pipeline());+ assert!(!Destination::Dlq.is_analytics_pipeline());+ assert!(!Destination::Drop.is_analytics_pipeline());+ assert!(!Destination::Custom("foo".into()).is_analytics_pipeline());+ }}// ---------------------------------------------------------------------------diff --git a/rust/capture/src/v1/test_utils.rs b/rust/capture/src/v1/test_utils.rsindex 718d09427313..7673281171c4 100644--- a/rust/capture/src/v1/test_utils.rs+++ b/rust/capture/src/v1/test_utils.rs@@ -143,6 +143,9 @@ pub fn test_kafka_config() -> crate::v1::sinks::kafka::config::Config {("TOPIC_HISTORICAL", "events_hist"),("TOPIC_OVERFLOW", "events_overflow"),("TOPIC_DLQ", "events_dlq"),+ ("TOPIC_EXCEPTION", "error_tracking_events"),+ ("TOPIC_HEATMAP", "heatmaps_ingestion"),+ ("TOPIC_CLIENT_INGESTION_WARNING", "events_plugin_ingestion"),].into_iter().map(|(k, v)| (k.to_string(), v.to_string()))diff --git a/rust/capture/tests/v1_sink_integration.rs b/rust/capture/tests/v1_sink_integration.rsindex 7d02c24a61d4..c381159841ff 100644--- a/rust/capture/tests/v1_sink_integration.rs+++ b/rust/capture/tests/v1_sink_integration.rs@@ -36,6 +36,9 @@ fn v1_kafka_config(topic: &str) -> capture::v1::sinks::kafka::config::Config {("TOPIC_HISTORICAL", topic),("TOPIC_OVERFLOW", topic),("TOPIC_DLQ", topic),+ ("TOPIC_EXCEPTION", topic),+ ("TOPIC_HEATMAP", topic),+ ("TOPIC_CLIENT_INGESTION_WARNING", topic),("LINGER_MS", "0"),("COMPRESSION_CODEC", "none"),("MESSAGE_TIMEOUT_MS", "10000"),