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(capture): redirect heatmap data from events to heatmaps topic (#57253)

Paweł Ledwoń5fa6225ea216
diff --git a/rust/capture/src/ai_endpoint.rs b/rust/capture/src/ai_endpoint.rs
index 8e5f8ddd2663..6edb8a3c8b0e 100644
--- a/rust/capture/src/ai_endpoint.rs
+++ b/rust/capture/src/ai_endpoint.rs
@@ -559,6 +559,7 @@ fn build_kafka_event(
skip_person_processing: restrictions.skip_person_processing(),
redirect_to_dlq: restrictions.redirect_to_dlq(),
redirect_to_topic: restrictions.redirect_to_topic().map(|s| s.to_string()),
+ skip_heatmap_processing: false,
overflow_reason: None,
};
diff --git a/rust/capture/src/events/analytics.rs b/rust/capture/src/events/analytics.rs
index 4eceffa654e6..71554d2dc478 100644
--- a/rust/capture/src/events/analytics.rs
+++ b/rust/capture/src/events/analytics.rs
@@ -3,7 +3,7 @@
//! This module handles processing of regular analytics events (pageviews, custom events,
//! exceptions, etc.) as opposed to recordings (session replay).
-use std::collections::HashSet;
+use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use chrono::DateTime;
@@ -27,6 +27,69 @@ use crate::{
v0_request::{DataType, ProcessedEvent, ProcessedEventMetadata, ProcessingContext},
};
+/// Property keys the heatmap pipeline reads from a redirected event. The
+/// redirect carries only these (plus `distinct_id` and `$cookieless_mode`,
+/// which are needed for the routing key).
+const HEATMAP_PROPERTY_KEYS: &[&str] = &[
+ "$heatmap_data",
+ "$viewport_height",
+ "$viewport_width",
+ "$session_id",
+ "$prev_pageview_pathname",
+ "$prev_pageview_max_scroll",
+ "$current_url",
+];
+
+/// True when this event carries data that the heatmap extraction pipeline
+/// would process — either an explicit `$heatmap_data` payload or the scroll
+/// depth properties that the pipeline derives from a previous pageview.
+fn has_heatmap_data(event: &RawEvent) -> bool {
+ event.properties.contains_key("$heatmap_data")
+ || (event.properties.contains_key("$prev_pageview_pathname")
+ && event.properties.contains_key("$current_url"))
+}
+
+/// Build a stripped-down `$$heatmap` event from a non-`$$heatmap` event that
+/// carries heatmap data. The redirect gets a fresh UUID so it does not
+/// deduplicate against the original. Returns `Ok(None)` if the source event
+/// has no resolvable `distinct_id` — the original event will fail validation
+/// downstream anyway, so no point emitting a redirect that will also fail.
+fn create_heatmap_redirect(
+ event: &RawEvent,
+ historical_cfg: router::HistoricalConfig,
+ context: &ProcessingContext,
+) -> Result<Option<ProcessedEvent>, CaptureError> {
+ let Some(distinct_id) = event.extract_distinct_id() else {
+ return Ok(None);
+ };
+
+ let mut properties = HashMap::new();
+ for key in HEATMAP_PROPERTY_KEYS {
+ if let Some(value) = event.properties.get(*key) {
+ properties.insert((*key).to_string(), value.clone());
+ }
+ }
+ // $cookieless_mode shapes the routing key (token:ip vs token:distinct_id);
+ // extract_is_cookieless_mode reads it from properties.
+ if let Some(value) = event.properties.get("$cookieless_mode") {
+ properties.insert("$cookieless_mode".to_string(), value.clone());
+ }
+
+ let heatmap_event = RawEvent {
+ token: event.token.clone(),
+ distinct_id: Some(serde_json::Value::String(distinct_id)),
+ uuid: Some(uuid_v7()),
+ event: "$$heatmap".to_string(),
+ properties,
+ timestamp: event.timestamp.clone(),
+ offset: event.offset,
+ set: None,
+ set_once: None,
+ };
+
+ process_single_event(&heatmap_event, historical_cfg, context).map(Some)
+}
+
/// Process a single analytics event from RawEvent to ProcessedEvent
#[instrument(skip_all, fields(event_name, request_id))]
pub fn process_single_event(
@@ -88,6 +151,7 @@ pub fn process_single_event(
skip_person_processing: false,
redirect_to_dlq: false,
redirect_to_topic: None,
+ skip_heatmap_processing: false,
overflow_reason: None,
};
@@ -138,25 +202,56 @@ pub fn process_single_event(
/// which topic and key to produce to.
#[instrument(skip_all, fields(events = events.len(), request_id))]
#[allow(clippy::too_many_arguments)]
-pub async fn process_events<'a>(
+pub async fn process_events(
sink: Arc<dyn sinks::Event + Send + Sync>,
dropper: Arc<TokenDropper>,
restriction_service: Option<EventRestrictionService>,
historical_cfg: router::HistoricalConfig,
global_rate_limiter: Option<Arc<GlobalRateLimiter>>,
overflow_limiter: Option<Arc<OverflowLimiter>>,
- events: &'a [RawEvent],
- context: &'a ProcessingContext,
+ events: Vec<RawEvent>,
+ context: &ProcessingContext,
) -> Result<(), CaptureError> {
let chatty_debug_enabled = context.chatty_debug_enabled;
Span::current().record("request_id", &context.request_id);
Span::current().record("is_mirror_deploy", context.is_mirror_deploy);
- let mut events: Vec<ProcessedEvent> = events
- .iter()
- .map(|e| process_single_event(e, historical_cfg.clone(), context))
- .collect::<Result<Vec<ProcessedEvent>, CaptureError>>()?;
+ // Build the processed batch one raw event at a time so we can split a
+ // heatmap-carrying event into a stripped original + a `$$heatmap`
+ // redirect *before* serialization happens inside `process_single_event`.
+ // The original loses `$heatmap_data` and is flagged so the events
+ // pipeline skips re-extracting; other heatmap-related properties
+ // (`$prev_pageview_pathname`, `$current_url`) stay on it because web
+ // analytics queries depend on them. If the redirect fails to construct,
+ // we fall back to processing the original unchanged so the events
+ // pipeline still extracts as before — no silent data loss.
+ let raw_events = events;
+ let mut events: Vec<ProcessedEvent> = Vec::with_capacity(raw_events.len());
+ for mut raw in raw_events {
+ if raw.event == "$$heatmap" || !has_heatmap_data(&raw) {
+ events.push(process_single_event(&raw, historical_cfg, context)?);
+ continue;
+ }
+ let redirect = match create_heatmap_redirect(&raw, historical_cfg, context) {
+ Ok(Some(redirect)) => redirect,
+ Ok(None) => {
+ events.push(process_single_event(&raw, historical_cfg, context)?);
+ continue;
+ }
+ Err(err) => {
+ error!("failed to create heatmap redirect: {err:#}");
+ events.push(process_single_event(&raw, historical_cfg, context)?);
+ continue;
+ }
+ };
+ raw.properties.remove("$heatmap_data");
+ let mut processed = process_single_event(&raw, historical_cfg, context)?;
+ processed.metadata.skip_heatmap_processing = true;
+ events.push(processed);
+ counter!("capture_heatmap_redirects_created").increment(1);
+ events.push(redirect);
+ }
debug_or_info!(chatty_debug_enabled, context=?context, event_count=?events.len(), "created ProcessedEvents batch");
@@ -504,7 +599,7 @@ mod tests {
historical_cfg,
None,
None,
- &events,
+ events,
&context,
)
.await;
@@ -552,7 +647,7 @@ mod tests {
historical_cfg,
None,
None,
- &events,
+ events,
&context,
)
.await;
@@ -601,7 +696,7 @@ mod tests {
historical_cfg,
None,
None,
- &events,
+ events,
&context,
)
.await;
@@ -650,7 +745,7 @@ mod tests {
historical_cfg,
None,
None,
- &events,
+ events,
&context,
)
.await;
@@ -706,7 +801,7 @@ mod tests {
historical_cfg,
None,
None,
- &events,
+ events,
&context,
)
.await;
@@ -742,7 +837,7 @@ mod tests {
historical_cfg,
None,
None,
- &events,
+ events,
&context,
)
.await;
@@ -796,7 +891,7 @@ mod tests {
historical_cfg,
None,
None,
- &events,
+ events,
&context,
)
.await;
@@ -844,7 +939,7 @@ mod tests {
historical_cfg,
None,
None,
- &events,
+ events,
&context,
)
.await;
@@ -902,7 +997,7 @@ mod tests {
historical_cfg,
None,
None,
- &events,
+ events,
&context,
)
.await
@@ -975,7 +1070,7 @@ mod tests {
historical_cfg,
None,
None,
- &events,
+ events,
&context,
)
.await
@@ -1047,7 +1142,7 @@ mod tests {
historical_cfg,
None,
None,
- &events,
+ events,
&context,
)
.await
@@ -1114,7 +1209,7 @@ mod tests {
historical_cfg,
None,
None,
- &events,
+ events,
&context,
)
.await
@@ -1173,7 +1268,7 @@ mod tests {
historical_cfg,
None,
None,
- &events,
+ events,
&context,
)
.await
@@ -1226,7 +1321,7 @@ mod tests {
historical_cfg,
None,
None, // no overflow limiter
- &events,
+ events,
&context,
)
.await
@@ -1262,7 +1357,7 @@ mod tests {
historical_cfg,
None,
Some(limiter),
- &events,
+ events,
&context,
)
.await
@@ -1300,7 +1395,7 @@ mod tests {
historical_cfg,
None,
Some(limiter),
- &events,
+ events,
&context,
)
.await
@@ -1340,7 +1435,7 @@ mod tests {
historical_cfg,
None,
Some(limiter),
- &events,
+ events,
&context,
)
.await
@@ -1397,7 +1492,7 @@ mod tests {
historical_cfg,
None,
Some(limiter),
- &events,
+ events,
&context,
)
.await
@@ -1436,7 +1531,7 @@ mod tests {
historical_cfg,
None,
Some(limiter),
- &events,
+ events,
&context,
)
.await
@@ -1492,7 +1587,7 @@ mod tests {
historical_cfg,
Some(global_limiter),
Some(overflow_limiter),
- &events,
+ events,
&context,
)
.await
@@ -1564,7 +1659,7 @@ mod tests {
historical_cfg,
None,
Some(limiter),
- &events,
+ events,
&context,
)
.await
@@ -1615,7 +1710,7 @@ mod tests {
historical_cfg,
None,
Some(limiter),
- &events,
+ events,
&context,
)
.await
@@ -1669,7 +1764,7 @@ mod tests {
historical_cfg,
None,
Some(limiter),
- &events,
+ events,
&context,
)
.await
@@ -1683,4 +1778,450 @@ mod tests {
"RateLimited{{preserve_locality:false}} must drop partition key"
);
}
+
+ // ============ heatmap redirect tests ============
+
+ /// Two shapes of input event qualify for a heatmap redirect: an event
+ /// carrying `$heatmap_data` directly, or an event carrying the
+ /// scroll-depth pair (`$prev_pageview_pathname` + `$current_url`) which
+ /// the heatmap pipeline turns into a synthetic `scrolldepth` data point.
+ /// The pipeline must handle both identically end-to-end.
+ #[derive(Clone, Copy, Debug)]
+ enum HeatmapShape {
+ HeatmapData,
+ ScrollDepth,
+ }
+
+ fn build_heatmap_carrier_event(shape: HeatmapShape) -> RawEvent {
+ let mut properties = HashMap::new();
+ properties.insert("distinct_id".to_string(), json!("test_user"));
+ properties.insert("$viewport_height".to_string(), json!(900));
+ properties.insert("$viewport_width".to_string(), json!(1440));
+ properties.insert("$session_id".to_string(), json!("session-abc"));
+ properties.insert("$current_url".to_string(), json!("https://example.com"));
+ properties.insert(
+ "other_prop".to_string(),
+ json!("should_not_appear_in_redirect"),
+ );
+
+ match shape {
+ HeatmapShape::HeatmapData => {
+ properties.insert(
+ "$heatmap_data".to_string(),
+ json!({"https://example.com": [{"x": 100, "y": 200, "target_fixed": false, "type": "click"}]}),
+ );
+ }
+ HeatmapShape::ScrollDepth => {
+ properties.insert("$prev_pageview_pathname".to_string(), json!("/old"));
+ properties.insert("$prev_pageview_max_scroll".to_string(), json!(0.42));
+ }
+ }
+
+ RawEvent {
+ uuid: Some(uuid_v7()),
+ distinct_id: None,
+ event: "$pageview".to_string(),
+ properties,
+ timestamp: Some("2023-01-01T11:00:00Z".to_string()),
+ offset: None,
+ set: None,
+ set_once: None,
+ token: Some("test_token".to_string()),
+ }
+ }
+
+ #[rstest]
+ #[case::heatmap_data_present(&["$heatmap_data"], true)]
+ #[case::scroll_depth_pair(&["$prev_pageview_pathname", "$current_url"], true)]
+ #[case::heatmap_data_with_scroll_depth(
+ &["$heatmap_data", "$prev_pageview_pathname", "$current_url"],
+ true,
+ )]
+ #[case::only_prev_pageview_pathname(&["$prev_pageview_pathname"], false)]
+ #[case::only_current_url(&["$current_url"], false)]
+ #[case::no_heatmap_properties(&[], false)]
+ fn test_has_heatmap_data(#[case] property_keys: &[&str], #[case] expected: bool) {
+ let mut properties = HashMap::new();
+ properties.insert("distinct_id".to_string(), json!("test_user"));
+ for key in property_keys {
+ properties.insert((*key).to_string(), json!("anything"));
+ }
+
+ let event = RawEvent {
+ uuid: Some(uuid_v7()),
+ distinct_id: None,
+ event: "$pageview".to_string(),
+ properties,
+ timestamp: None,
+ offset: None,
+ set: None,
+ set_once: None,
+ token: Some("test_token".to_string()),
+ };
+
+ assert_eq!(has_heatmap_data(&event), expected);
+ }
+
+ #[test]
+ fn test_create_heatmap_redirect_properties_and_metadata() {
+ let now = Utc::now();
+ let context = create_test_context(now, None);
+ let event = build_heatmap_carrier_event(HeatmapShape::HeatmapData);
+ let historical_cfg = router::HistoricalConfig::new(false, 1);
+
+ let redirect = create_heatmap_redirect(&event, historical_cfg, &context)
+ .unwrap()
+ .expect("redirect should be created when distinct_id is resolvable");
+
+ assert_eq!(redirect.metadata.data_type, DataType::HeatmapMain);
+ assert_eq!(redirect.metadata.event_name, "$$heatmap");
+ assert!(!redirect.metadata.skip_heatmap_processing);
+ assert_eq!(redirect.event.event, "$$heatmap");
+ assert_ne!(redirect.event.uuid, event.uuid.unwrap());
+
+ let data: RawEvent = serde_json::from_str(&redirect.event.data).unwrap();
+ assert!(data.properties.contains_key("$heatmap_data"));
+ assert!(data.properties.contains_key("$viewport_height"));
+ assert!(data.properties.contains_key("$viewport_width"));
+ assert!(data.properties.contains_key("$session_id"));
+ assert!(data.properties.contains_key("$current_url"));
+ assert_eq!(data.distinct_id, Some(json!("test_user")));
+ assert!(
+ !data.properties.contains_key("distinct_id"),
+ "distinct_id lives on the top-level field, not in properties"
+ );
+ assert!(
+ !data.properties.contains_key("other_prop"),
+ "redirect should only contain heatmap properties"
+ );
+ }
+
+ #[test]
+ fn test_create_heatmap_redirect_returns_none_when_distinct_id_missing() {
+ let now = Utc::now();
+ let context = create_test_context(now, None);
+ let mut event = build_heatmap_carrier_event(HeatmapShape::HeatmapData);
+ event.distinct_id = None;
+ event.properties.remove("distinct_id");
+ let historical_cfg = router::HistoricalConfig::new(false, 1);
+
+ let result = create_heatmap_redirect(&event, historical_cfg, &context).unwrap();
+ assert!(result.is_none());
+ }
+
+ #[test]
+ fn test_create_heatmap_redirect_resolves_distinct_id_from_properties() {
+ let now = Utc::now();
+ let context = create_test_context(now, None);
+ let event = build_heatmap_carrier_event(HeatmapShape::HeatmapData);
+ // Carrier event has distinct_id only in properties (top-level is None).
+ assert!(event.distinct_id.is_none());
+ let historical_cfg = router::HistoricalConfig::new(false, 1);
+
+ let redirect = create_heatmap_redirect(&event, historical_cfg, &context)
+ .unwrap()
+ .expect("redirect should fall back to properties for distinct_id");
+
+ let data: RawEvent = serde_json::from_str(&redirect.event.data).unwrap();
+ assert_eq!(data.distinct_id, Some(json!("test_user")));
+ }
+
+ #[rstest]
+ #[case::heatmap_data(HeatmapShape::HeatmapData)]
+ #[case::scroll_depth(HeatmapShape::ScrollDepth)]
+ #[tokio::test]
+ async fn test_process_events_creates_heatmap_redirect(#[case] shape: HeatmapShape) {
+ let now = Utc::now();
+ let context = create_test_context(now, None);
+ let events = vec![build_heatmap_carrier_event(shape)];
+
+ let sink = Arc::new(MockSink::new());
+ let dropper = Arc::new(limiters::token_dropper::TokenDropper::default());
+ let historical_cfg = router::HistoricalConfig::new(false, 1);
+
+ process_events(
+ sink.clone(),
+ dropper,
+ None,
+ historical_cfg,
+ None,
+ None,
+ events,
+ &context,
+ )
+ .await
+ .unwrap();
+
+ let captured = sink.get_events();
+ assert_eq!(captured.len(), 2, "should produce original + redirect");
+
+ let original = &captured[0];
+ assert_eq!(original.event.event, "$pageview");
+ assert!(original.metadata.skip_heatmap_processing);
+ let orig_data: RawEvent = serde_json::from_str(&original.event.data).unwrap();
+ assert!(
+ !orig_data.properties.contains_key("$heatmap_data"),
+ "$heatmap_data must never be on the original (stripped if present, never added if not)"
+ );
+ assert!(
+ orig_data.properties.contains_key("$current_url"),
+ "non-$heatmap_data properties remain on original"
+ );
+
+ let redirect = &captured[1];
+ assert_eq!(redirect.event.event, "$$heatmap");
+ assert_eq!(redirect.metadata.data_type, DataType::HeatmapMain);
+ assert!(!redirect.metadata.skip_heatmap_processing);
+ }
+
+ #[tokio::test]
+ async fn test_process_events_no_redirect_for_heatmap_event() {
+ let now = Utc::now();
+ let context = create_test_context(now, None);
+
+ let mut event = build_heatmap_carrier_event(HeatmapShape::HeatmapData);
+ event.event = "$$heatmap".to_string();
+ let events = vec![event];
+
+ let sink = Arc::new(MockSink::new());
+ let dropper = Arc::new(limiters::token_dropper::TokenDropper::default());
+ let historical_cfg = router::HistoricalConfig::new(false, 1);
+
+ process_events(
+ sink.clone(),
+ dropper,
+ None,
+ historical_cfg,
+ None,
+ None,
+ events,
+ &context,
+ )
+ .await
+ .unwrap();
+
+ let captured = sink.get_events();
+ assert_eq!(
+ captured.len(),
+ 1,
+ "$$heatmap events should not produce a redirect"
+ );
+ assert_eq!(captured[0].metadata.data_type, DataType::HeatmapMain);
+ assert!(!captured[0].metadata.skip_heatmap_processing);
+ }
+
+ #[tokio::test]
+ async fn test_process_events_no_redirect_without_heatmap_data() {
+ let now = Utc::now();
+ let context = create_test_context(now, None);
+ let events = vec![create_test_event(
+ Some("2023-01-01T11:00:00Z".to_string()),
+ None,
+ None,
+ )];
+
+ let sink = Arc::new(MockSink::new());
+ let dropper = Arc::new(limiters::token_dropper::TokenDropper::default());
+ let historical_cfg = router::HistoricalConfig::new(false, 1);
+
+ process_events(
+ sink.clone(),
+ dropper,
+ None,
+ historical_cfg,
+ None,
+ None,
+ events,
+ &context,
+ )
+ .await
+ .unwrap();
+
+ let captured = sink.get_events();
+ assert_eq!(captured.len(), 1);
+ assert!(!captured[0].metadata.skip_heatmap_processing);
+ }
+
+ /// End-to-end pipeline-to-kafka contract for the heatmap redirect: a
+ /// non-`$$heatmap` event that qualifies as a heatmap carrier produces
+ /// two kafka records — the stripped original on the events topic with
+ /// the `skip_heatmap_processing` header, and a `$$heatmap` redirect on
+ /// the heatmaps topic carrying the heatmap properties. Both qualifying
+ /// shapes (explicit `$heatmap_data`, and the scroll-depth pair) must
+ /// produce identical end-to-end behavior except for which heatmap-
+ /// payload properties end up on the redirect.
+ #[rstest]
+ #[case::heatmap_data(HeatmapShape::HeatmapData)]
+ #[case::scroll_depth(HeatmapShape::ScrollDepth)]
+ #[tokio::test]
+ async fn e2e_heatmap_redirect_strips_original_and_routes_redirect(#[case] shape: HeatmapShape) {
+ let now = Utc::now();
+ let context = create_test_context(now, None);
+ let event = build_heatmap_carrier_event(shape);
+ let original_uuid = event.uuid.unwrap();
+ let events = vec![event];
+
+ let producer = MockKafkaProducer::new();
+ let sink = Arc::new(KafkaSinkBase::with_producer(
+ producer.clone(),
+ test_topics(),
+ ));
+ let dropper = Arc::new(limiters::token_dropper::TokenDropper::default());
+ let historical_cfg = router::HistoricalConfig::new(false, 1);
+
+ process_events(
+ sink,
+ dropper,
+ None,
+ historical_cfg,
+ None,
+ None,
+ events,
+ &context,
+ )
+ .await
+ .unwrap();
+
+ let records = producer.get_records();
+ assert_eq!(
+ records.len(),
+ 2,
+ "should produce original + heatmap redirect"
+ );
+
+ let original = records
+ .iter()
+ .find(|r| r.topic == "events_plugin_ingestion")
+ .expect("original event should land on the main events topic");
+ let redirect = records
+ .iter()
+ .find(|r| r.topic == "heatmaps")
+ .expect("redirect should land on the heatmaps topic");
+
+ // ---- original on events topic ----
+ assert_eq!(
+ original.headers.skip_heatmap_processing,
+ Some(true),
+ "original must carry skip_heatmap_processing=true so the events pipeline skips extraction"
+ );
+ assert_eq!(
+ original.headers.event.as_deref(),
+ Some("$pageview"),
+ "original keeps its event name"
+ );
+ assert_eq!(
+ original.headers.uuid.as_deref(),
+ Some(original_uuid.to_string().as_str()),
+ "original keeps its uuid"
+ );
+
+ let original_captured: CapturedEvent =
+ serde_json::from_str(&original.payload).expect("payload should be a CapturedEvent");
+ let original_raw: RawEvent = serde_json::from_str(&original_captured.data)
+ .expect("data field should be a serialized RawEvent");
+ assert!(
+ !original_raw.properties.contains_key("$heatmap_data"),
+ "$heatmap_data must never be on the original (stripped if present, never added otherwise)"
+ );
+ // Other heatmap-adjacent properties must remain — web analytics queries depend on them.
+ assert!(original_raw.properties.contains_key("$current_url"));
+ assert!(original_raw.properties.contains_key("$viewport_height"));
+ assert!(original_raw.properties.contains_key("$viewport_width"));
+ assert!(original_raw.properties.contains_key("$session_id"));
+ // Unrelated user properties must also remain on the original.
+ assert_eq!(
+ original_raw.properties.get("other_prop"),
+ Some(&json!("should_not_appear_in_redirect")),
+ );
+
+ // ---- redirect on heatmaps topic ----
+ assert_eq!(
+ redirect.headers.skip_heatmap_processing, None,
+ "redirect must NOT set skip_heatmap_processing — the heatmaps pipeline is the consumer"
+ );
+ assert_eq!(
+ redirect.headers.event.as_deref(),
+ Some("$$heatmap"),
+ "redirect must be renamed to $$heatmap"
+ );
+ assert_ne!(
+ redirect.headers.uuid.as_deref(),
+ Some(original_uuid.to_string().as_str()),
+ "redirect must have a fresh uuid so it doesn't dedupe against the original"
+ );
+
+ let redirect_captured: CapturedEvent =
+ serde_json::from_str(&redirect.payload).expect("payload should be a CapturedEvent");
+ assert_eq!(redirect_captured.event, "$$heatmap");
+ let redirect_raw: RawEvent = serde_json::from_str(&redirect_captured.data)
+ .expect("data field should be a serialized RawEvent");
+ assert_eq!(redirect_raw.event, "$$heatmap");
+
+ // Properties carried by every heatmap redirect, regardless of shape.
+ assert_eq!(
+ redirect_raw.properties.get("$viewport_height"),
+ Some(&json!(900)),
+ );
+ assert_eq!(
+ redirect_raw.properties.get("$viewport_width"),
+ Some(&json!(1440)),
+ );
+ assert_eq!(
+ redirect_raw.properties.get("$session_id"),
+ Some(&json!("session-abc")),
+ );
+ assert_eq!(
+ redirect_raw.properties.get("$current_url"),
+ Some(&json!("https://example.com")),
+ );
+ // distinct_id is required for routing-key generation; it's pre-resolved
+ // onto the top-level field rather than left in properties.
+ assert_eq!(redirect_raw.distinct_id, Some(json!("test_user")));
+ assert!(
+ !redirect_raw.properties.contains_key("distinct_id"),
+ "distinct_id is on the top-level field, not in properties"
+ );
+ // The redirect must NOT carry unrelated user properties — only what the heatmap pipeline reads.
+ assert!(
+ !redirect_raw.properties.contains_key("other_prop"),
+ "redirect must only carry heatmap properties"
+ );
+
+ // Shape-specific payload properties.
+ match shape {
+ HeatmapShape::HeatmapData => {
+ assert_eq!(
+ redirect_raw.properties.get("$heatmap_data"),
+ Some(&json!({
+ "https://example.com": [{
+ "x": 100,
+ "y": 200,
+ "target_fixed": false,
+ "type": "click",
+ }]
+ })),
+ );
+ assert!(
+ !redirect_raw
+ .properties
+ .contains_key("$prev_pageview_pathname"),
+ "scroll-depth properties absent on heatmap-data shape"
+ );
+ }
+ HeatmapShape::ScrollDepth => {
+ assert!(
+ !redirect_raw.properties.contains_key("$heatmap_data"),
+ "scroll-depth shape doesn't carry $heatmap_data — the heatmap pipeline derives it from $prev_pageview_*"
+ );
+ assert_eq!(
+ redirect_raw.properties.get("$prev_pageview_pathname"),
+ Some(&json!("/old")),
+ );
+ assert_eq!(
+ redirect_raw.properties.get("$prev_pageview_max_scroll"),
+ Some(&json!(0.42)),
+ );
+ }
+ }
+ }
}
diff --git a/rust/capture/src/events/overflow_stamping.rs b/rust/capture/src/events/overflow_stamping.rs
index 5dc576870b1f..90b5132c83b9 100644
--- a/rust/capture/src/events/overflow_stamping.rs
+++ b/rust/capture/src/events/overflow_stamping.rs
@@ -140,6 +140,7 @@ mod tests {
skip_person_processing: false,
redirect_to_dlq: false,
redirect_to_topic: None,
+ skip_heatmap_processing: false,
overflow_reason: None,
};
diff --git a/rust/capture/src/events/recordings.rs b/rust/capture/src/events/recordings.rs
index b469b6d7eb41..1eb0c1499b8c 100644
--- a/rust/capture/src/events/recordings.rs
+++ b/rust/capture/src/events/recordings.rs
@@ -360,6 +360,7 @@ pub async fn process_replay_events(
skip_person_processing: applied.skip_person_processing(),
redirect_to_dlq: applied.redirect_to_dlq(),
redirect_to_topic: applied.redirect_to_topic().map(|s| s.to_string()),
+ skip_heatmap_processing: false,
overflow_reason,
};
diff --git a/rust/capture/src/otel/filtering.rs b/rust/capture/src/otel/filtering.rs
index a1c5fdc2ae99..5658cc032a14 100644
--- a/rust/capture/src/otel/filtering.rs
+++ b/rust/capture/src/otel/filtering.rs
@@ -124,6 +124,7 @@ pub fn build_events(
skip_person_processing: restrictions.skip_person_processing(),
redirect_to_dlq: restrictions.redirect_to_dlq(),
redirect_to_topic: restrictions.redirect_to_topic().map(|s| s.to_string()),
+ skip_heatmap_processing: false,
overflow_reason: None,
};
diff --git a/rust/capture/src/router.rs b/rust/capture/src/router.rs
index 87d61ab4fb70..e2d1d471ed1b 100644
--- a/rust/capture/src/router.rs
+++ b/rust/capture/src/router.rs
@@ -81,7 +81,7 @@ pub struct State {
pub replay_overflow_limiter: Option<Arc<RedisLimiter>>,
}
-#[derive(Clone)]
+#[derive(Clone, Copy)]
pub struct HistoricalConfig {
pub enable_historical_rerouting: bool,
pub historical_rerouting_threshold_days: i64,
diff --git a/rust/capture/src/sinks/fallback.rs b/rust/capture/src/sinks/fallback.rs
index 911e744d2db1..c2684a3f6a00 100644
--- a/rust/capture/src/sinks/fallback.rs
+++ b/rust/capture/src/sinks/fallback.rs
@@ -160,6 +160,7 @@ mod tests {
skip_person_processing: false,
redirect_to_dlq: false,
redirect_to_topic: None,
+ skip_heatmap_processing: false,
overflow_reason: None,
},
};
@@ -210,6 +211,7 @@ mod tests {
skip_person_processing: false,
redirect_to_dlq: false,
redirect_to_topic: None,
+ skip_heatmap_processing: false,
overflow_reason: None,
},
};
diff --git a/rust/capture/src/sinks/kafka.rs b/rust/capture/src/sinks/kafka.rs
index 5d406b5633f1..9306b71896d7 100644
--- a/rust/capture/src/sinks/kafka.rs
+++ b/rust/capture/src/sinks/kafka.rs
@@ -388,6 +388,7 @@ impl<P: KafkaProducer> KafkaSinkBase<P> {
let skip_person_processing = metadata.skip_person_processing;
let redirect_to_dlq = metadata.redirect_to_dlq;
let redirect_to_topic = metadata.redirect_to_topic;
+ let skip_heatmap_processing = metadata.skip_heatmap_processing;
let overflow_reason = metadata.overflow_reason;
// Use the event's to_headers() method for consistent header serialization
@@ -400,6 +401,10 @@ impl<P: KafkaProducer> KafkaSinkBase<P> {
headers.set_force_disable_person_processing(true);
}
+ if skip_heatmap_processing {
+ headers.set_skip_heatmap_processing(true);
+ }
+
// Check for redirect_to_dlq first - takes priority over all other routing
let (topic, partition_key): (&str, Option<&str>) = if redirect_to_dlq {
counter!(
@@ -867,6 +872,7 @@ mod tests {
skip_person_processing: false,
redirect_to_dlq: false,
redirect_to_topic: None,
+ skip_heatmap_processing: false,
overflow_reason: None,
};
@@ -1015,6 +1021,7 @@ mod tests {
now: Some("2023-01-01T12:00:00Z".to_string()),
force_disable_person_processing: None,
historical_migration: Some(true),
+ skip_heatmap_processing: None,
dlq_reason: None,
dlq_step: None,
dlq_timestamp: None,
@@ -1035,6 +1042,7 @@ mod tests {
now: Some("2023-01-01T12:00:00Z".to_string()),
force_disable_person_processing: None,
historical_migration: Some(false),
+ skip_heatmap_processing: None,
dlq_reason: None,
dlq_step: None,
dlq_timestamp: None,
@@ -1063,6 +1071,7 @@ mod tests {
now: Some(test_now.clone()),
force_disable_person_processing: None,
historical_migration: None,
+ skip_heatmap_processing: None,
dlq_reason: None,
dlq_step: None,
dlq_timestamp: None,
@@ -1096,6 +1105,7 @@ mod tests {
now: Some(test_now.clone()),
force_disable_person_processing: None,
historical_migration: None,
+ skip_heatmap_processing: None,
dlq_reason: Some("test reason".to_string()),
dlq_step: Some("test step".to_string()),
dlq_timestamp: Some(dlq_timestamp.clone()),
@@ -1173,6 +1183,7 @@ mod tests {
skip_person_processing: input.skip_person_processing,
redirect_to_dlq: input.redirect_to_dlq,
redirect_to_topic: input.redirect_to_topic.clone(),
+ skip_heatmap_processing: false,
overflow_reason: input.overflow_reason.clone(),
};
diff --git a/rust/capture/src/sinks/s3.rs b/rust/capture/src/sinks/s3.rs
index 12917ed66869..c18215a9b888 100644
--- a/rust/capture/src/sinks/s3.rs
+++ b/rust/capture/src/sinks/s3.rs
@@ -362,6 +362,7 @@ mod tests {
skip_person_processing: false,
redirect_to_dlq: false,
redirect_to_topic: None,
+ skip_heatmap_processing: false,
overflow_reason: None,
},
}
diff --git a/rust/capture/src/v0_endpoint.rs b/rust/capture/src/v0_endpoint.rs
index d12d9baec84e..55cd9ca93ac5 100644
--- a/rust/capture/src/v0_endpoint.rs
+++ b/rust/capture/src/v0_endpoint.rs
@@ -69,19 +69,20 @@ pub async fn event(
}
Ok((context, events)) => {
+ let event_count = events.len() as u64;
if let Err(err) = process_events(
state.sink.clone(),
state.token_dropper.clone(),
state.event_restriction_service.clone(),
- state.historical_cfg.clone(),
+ state.historical_cfg,
state.global_rate_limiter_token_distinctid.clone(),
state.overflow_limiter.clone(),
- &events,
+ events,
&context,
)
.await
{
- report_dropped_events(err.to_metric_tag(), events.len() as u64);
+ report_dropped_events(err.to_metric_tag(), event_count);
report_internal_error_metrics(err.to_metric_tag(), "processing");
warn!("event: rejected payload: {err:#}");
return Err(err);
diff --git a/rust/capture/src/v0_request.rs b/rust/capture/src/v0_request.rs
index 351ccdbd91c3..754908fc34d5 100644
--- a/rust/capture/src/v0_request.rs
+++ b/rust/capture/src/v0_request.rs
@@ -252,6 +252,9 @@ pub struct ProcessedEventMetadata {
pub redirect_to_dlq: bool,
/// Redirect this event to a custom topic (set by event restrictions)
pub redirect_to_topic: Option<String>,
+ /// Heatmap data on this event was redirected to the heatmaps topic and
+ /// must not be extracted again by the events pipeline.
+ pub skip_heatmap_processing: bool,
/// Overflow routing decision stamped by the pipeline. `None` means the
/// event stays on its default topic for its `data_type`. See
/// [`OverflowReason`] for who sets this and what each variant maps to in
diff --git a/rust/capture/src/v1/analytics/types.rs b/rust/capture/src/v1/analytics/types.rs
index 02b467cb544d..b887923205b0 100644
--- a/rust/capture/src/v1/analytics/types.rs
+++ b/rust/capture/src/v1/analytics/types.rs
@@ -168,6 +168,7 @@ impl SinkEvent for WrappedEvent {
),
force_disable_person_processing,
historical_migration,
+ skip_heatmap_processing: None,
dlq_reason,
dlq_step,
dlq_timestamp,
diff --git a/rust/capture/src/v1/sinks/kafka/sink_tests.rs b/rust/capture/src/v1/sinks/kafka/sink_tests.rs
index 99759c19dba8..a4f8ff4fd77a 100644
--- a/rust/capture/src/v1/sinks/kafka/sink_tests.rs
+++ b/rust/capture/src/v1/sinks/kafka/sink_tests.rs
@@ -33,6 +33,7 @@ fn empty_captured_headers() -> CapturedEventHeaders {
now: None,
force_disable_person_processing: None,
historical_migration: None,
+ skip_heatmap_processing: None,
dlq_reason: None,
dlq_step: None,
dlq_timestamp: None,
diff --git a/rust/capture/src/v1/sinks/router.rs b/rust/capture/src/v1/sinks/router.rs
index fa0b1b43e0cd..b441b6cb3fbb 100644
--- a/rust/capture/src/v1/sinks/router.rs
+++ b/rust/capture/src/v1/sinks/router.rs
@@ -172,6 +172,7 @@ mod tests {
now: None,
force_disable_person_processing: None,
historical_migration: None,
+ skip_heatmap_processing: None,
dlq_reason: None,
dlq_step: None,
dlq_timestamp: None,
diff --git a/rust/capture/tests/common/integration_utils.rs b/rust/capture/tests/common/integration_utils.rs
index 15cf36545a55..eda6ec683581 100644
--- a/rust/capture/tests/common/integration_utils.rs
+++ b/rust/capture/tests/common/integration_utils.rs
@@ -40,6 +40,7 @@ pub const DEFAULT_TEST_TIME: &str = "2025-07-01T11:00:00Z";
pub const SINGLE_EVENT_JSON: &str = "single_event_payload.json";
pub const SINGLE_REPLAY_EVENT_JSON: &str = "single_replay_event_payload.json";
pub const BATCH_EVENTS_JSON: &str = "batch_events_payload.json";
+pub const BATCH_EVENTS_WITH_HEATMAP_JSON: &str = "batch_events_with_heatmap_payload.json";
// the /engage/ endpoint is unique: this only accepts "unnamed" (no event.event attrib)
// events that are structured as "$identify" events
pub const SINGLE_ENGAGE_EVENT_JSON: &str = "single_engage_event_payload.json";
@@ -127,6 +128,9 @@ pub async fn execute_test(unit: &TestCase) {
SINGLE_REPLAY_EVENT_JSON => validate_single_replay_event_payload(&unit.title, got),
SINGLE_ENGAGE_EVENT_JSON => validate_single_engage_event_payload(&unit.title, got),
BATCH_EVENTS_JSON => validate_batch_events_payload(&unit.title, got),
+ BATCH_EVENTS_WITH_HEATMAP_JSON => {
+ validate_batch_events_with_heatmap_payload(&unit.title, got)
+ }
_ => panic!(
"unsupported fixture type {} in TestCase: {}",
unit.fixture, unit.title
@@ -877,7 +881,7 @@ pub fn validate_batch_events_payload(title: &str, got_events: Vec<ProcessedEvent
let props = event["properties"].as_object().expect(&err_msg);
assert_eq!(
- 72_usize,
+ 71_usize,
props.len(),
"mismatched event.properties length on $pageleave in case: {title}",
);
@@ -915,6 +919,92 @@ pub fn validate_batch_events_payload(title: &str, got_events: Vec<ProcessedEvent
);
}
+// utility to validate tests/fixtures/batch_events_with_heatmap_payload.json
+//
+// The $pageleave in this fixture carries `$prev_pageview_pathname` +
+// `$current_url`, which qualifies it as a heatmap-data carrier. Capture must
+// produce a third event — a `$$heatmap` redirect — alongside the original two.
+// The original $pageleave gets `skip_heatmap_processing: true` so the events
+// pipeline does not also extract heatmap data downstream.
+pub fn validate_batch_events_with_heatmap_payload(title: &str, got_events: Vec<ProcessedEvent>) {
+ assert_eq!(
+ 3,
+ got_events.len(),
+ "event count: expected 3 ($pageview + $pageleave + $$heatmap redirect), got {} in case: {title}",
+ got_events.len(),
+ );
+
+ let pageview = &got_events[0];
+ assert_eq!(
+ pageview.event.event, "$pageview",
+ "first event should be $pageview in case: {title}",
+ );
+ assert!(
+ !pageview.metadata.skip_heatmap_processing,
+ "$pageview carries no heatmap data, must not be flagged in case: {title}",
+ );
+
+ let pageleave = &got_events[1];
+ assert_eq!(
+ pageleave.event.event, "$pageleave",
+ "second event should be $pageleave in case: {title}",
+ );
+ assert!(
+ pageleave.metadata.skip_heatmap_processing,
+ "$pageleave carries scroll-depth heatmap data, must be flagged in case: {title}",
+ );
+ let pageleave_data: Value = from_str(&pageleave.event.data)
+ .unwrap_or_else(|_| panic!("failed to hydrate $pageleave event.data in case: {title}"));
+ let pageleave_props = pageleave_data["properties"]
+ .as_object()
+ .unwrap_or_else(|| panic!("missing $pageleave properties in case: {title}"));
+ assert!(
+ pageleave_props.contains_key("$prev_pageview_pathname"),
+ "$prev_pageview_pathname must remain on the original — only $heatmap_data is stripped (case: {title})",
+ );
+ assert!(
+ !pageleave_props.contains_key("$heatmap_data"),
+ "$heatmap_data must never be on the stripped original (case: {title})",
+ );
+
+ let redirect = &got_events[2];
+ assert_eq!(
+ redirect.metadata.data_type,
+ DataType::HeatmapMain,
+ "redirect must be routed to the heatmaps topic in case: {title}",
+ );
+ assert_eq!(
+ redirect.event.event, "$$heatmap",
+ "redirect event name must be $$heatmap in case: {title}",
+ );
+ assert!(
+ !redirect.metadata.skip_heatmap_processing,
+ "redirect must NOT be flagged — the heatmaps pipeline is its consumer in case: {title}",
+ );
+ assert_ne!(
+ redirect.event.uuid, pageleave.event.uuid,
+ "redirect must have a fresh uuid to avoid deduplicating against the original (case: {title})",
+ );
+ assert_eq!(
+ redirect.event.distinct_id, pageleave.event.distinct_id,
+ "redirect must inherit distinct_id from its source event in case: {title}",
+ );
+
+ let redirect_data: Value = from_str(&redirect.event.data)
+ .unwrap_or_else(|_| panic!("failed to hydrate redirect event.data in case: {title}"));
+ let redirect_props = redirect_data["properties"]
+ .as_object()
+ .unwrap_or_else(|| panic!("missing redirect properties in case: {title}"));
+ assert!(
+ redirect_props.contains_key("$prev_pageview_pathname"),
+ "redirect must carry $prev_pageview_pathname in case: {title}",
+ );
+ assert!(
+ redirect_props.contains_key("$current_url"),
+ "redirect must carry $current_url in case: {title}",
+ );
+}
+
//
// Utilities
//
diff --git a/rust/capture/tests/fixtures/batch_events_payload.json b/rust/capture/tests/fixtures/batch_events_payload.json
index 4f1295456560..8b1b7911f479 100644
--- a/rust/capture/tests/fixtures/batch_events_payload.json
+++ b/rust/capture/tests/fixtures/batch_events_payload.json
@@ -216,7 +216,6 @@
"$replay_sample_rate": null,
"$viewport_width": 1366,
"$session_entry_referring_domain": "posthog.example.com",
- "$prev_pageview_pathname": "/testing",
"$feature_flag_payloads": {},
"$sdk_debug_retry_queue_size": 0,
"$is_identified": true,
diff --git a/rust/capture/tests/fixtures/batch_events_with_heatmap_payload.json b/rust/capture/tests/fixtures/batch_events_with_heatmap_payload.json
new file mode 100644
index 000000000000..4f1295456560
--- /dev/null
+++ b/rust/capture/tests/fixtures/batch_events_with_heatmap_payload.json
@@ -0,0 +1,238 @@
+{
+ "api_key": "phc_VXRzc3poSG9GZm1JenRianJ6TTJFZGh4OWY2QXzx9f3",
+ "historical_migration": false,
+ "batch": [
+ {
+ "event": "$pageview",
+ "distinct_id": "[email protected]",
+ "timestamp": "2025-07-01T02:55:00Z",
+ "properties": {
+ "$autocapture_disabled_server_side": true,
+ "$session_recording_network_payload_capture": {
+ "capturePerformance": {
+ "network_timing": true,
+ "web_vitals": false,
+ "web_vitals_allowed_metrics": null
+ },
+ "recordBody": true,
+ "recordHeaders": true
+ },
+ "$host": "posthog.example.com",
+ "$replay_script_config": null,
+ "$exception_capture_enabled_server_side": false,
+ "$referring_domain": "$direct",
+ "$current_url": "https://posthog.example.com/testing",
+ "$session_entry_url": "https://posthog.example.com/testing",
+ "$pathname": "/testing",
+ "$screen_height": 768,
+ "$feature_flag_request_id": "0198393f-1b8a-7c2e-a269-737351f06167",
+ "$is_identified": true,
+ "$viewport_height": 599,
+ "$replay_minimum_duration": 15000,
+ "$browser_language": "es-ES",
+ "$feature_flag_payloads": {},
+ "$os": "Windows",
+ "$timezone_offset": 300,
+ "$sdk_debug_current_session_duration": null,
+ "$timezone": "America/Bogota",
+ "$referrer": "$direct",
+ "$active_feature_flags": [
+ "survey-targeting-c34291e772"
+ ],
+ "$feature/survey-targeting-bb7ab5ac7e-custom": false,
+ "$configured_session_timeout_ms": 3600000,
+ "$pageview_id": "0198395d-cb33-7497-a2c7-d2a54cdea918",
+ "$viewport_width": 1366,
+ "$session_id": "0198395d-f729-7df2-aea7-3456af7343eb",
+ "$device_type": "Desktop",
+ "$session_recording_masking": {
+ "maskAllInputs": false
+ },
+ "$dead_clicks_enabled_server_side": false,
+ "$session_entry_referrer": "$direct",
+ "$feature/survey-targeting-foobar": true,
+ "$recording_status": "buffering",
+ "$os_version": "10",
+ "$sdk_debug_session_start": 1753306906004,
+ "$sdk_debug_retry_queue_size": 0,
+ "$device_id": "0198395e-6a8d-7b5f-aacb-aea40cf448fa",
+ "$web_vitals_enabled_server_side": false,
+ "$web_vitals_allowed_metrics": null,
+ "$session_entry_pathname": "/testing",
+ "$insert_id": "ghi567jkl890",
+ "$lib": "web",
+ "$replay_sample_rate": null,
+ "$sdk_debug_replay_internal_buffer_length": 0,
+ "$window_id": "0198395e-c51f-7389-ab21-c04a88a053c0",
+ "$sdk_debug_replay_internal_buffer_size": 0,
+ "$session_recording_canvas_recording": {
+ "enabled": true,
+ "fps": 3,
+ "quality": "0.4"
+ },
+ "$console_log_recording_enabled_server_side": true,
+ "$lib_custom_api_host": "https://posthog.example.com/testing",
+ "$session_entry_referring_domain": "$direct",
+ "$screen_width": 1366,
+ "title": "CoolApp",
+ "$user_id": "[email protected]",
+ "$session_entry_host": "posthog.example.com",
+ "$lib_version": "1.2.3",
+ "$config_defaults": "unset",
+ "$time": 1753306906.2,
+ "$initialization_time": "2025-07-01T00:00:00Z",
+ "$lib_rate_limit_remaining_tokens": 99,
+ "$browser_language_prefix": "es",
+ "$browser": "Chrome",
+ "$browser_version": 138,
+ "$raw_user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36",
+ "$set_once": {
+ "$initial_ttclid": null,
+ "$host": "posthog.example.com",
+ "fbclid": null,
+ "$initial_gbraid": null,
+ "$initial_wbraid": null,
+ "utm_source": null,
+ "dclid": null,
+ "gclsrc": null,
+ "$initial_gad_source": null,
+ "$initial_mc_cid": null,
+ "$initial_irclid": null,
+ "utm_campaign": null,
+ "$initial_host": "posthog.example.com",
+ "$initial_utm_content": null,
+ "$initial_utm_term": null,
+ "gclid": null,
+ "$pathname": "/testing",
+ "utm_term": null,
+ "_kx": null,
+ "$initial_sccid": null,
+ "igshid": null,
+ "$referring_domain": "$direct",
+ "qclid": null,
+ "$initial_qclid": null,
+ "$initial__kx": null,
+ "$referrer": "$direct",
+ "$initial_dclid": null,
+ "twclid": null,
+ "$initial_fbclid": null,
+ "gbraid": null,
+ "$initial_igshid": null,
+ "utm_content": null,
+ "$initial_utm_campaign": null,
+ "$initial_pathname": "/testing",
+ "$initial_rdt_cid": null,
+ "$initial_epik": null,
+ "ttclid": null,
+ "rdt_cid": null,
+ "wbraid": null,
+ "$initial_msclkid": null,
+ "$initial_current_url": "https://posthog.example.com/testing",
+ "epik": null,
+ "$initial_referrer": "$direct",
+ "utm_medium": null,
+ "$initial_gclid": null,
+ "sccid": null,
+ "mc_cid": null,
+ "msclkid": null,
+ "gad_source": null,
+ "$current_url": "https://posthog.example.com/testing",
+ "$initial_utm_source": null,
+ "irclid": null,
+ "$initial_twclid": null,
+ "$initial_gclsrc": null,
+ "$initial_li_fat_id": null,
+ "$initial_utm_medium": null,
+ "li_fat_id": null,
+ "$initial_referring_domain": "$direct"
+ }
+ }
+ },
+ {
+ "event": "$pageleave",
+ "distinct_id": "[email protected]",
+ "timestamp": "2025-07-01T03:00:00Z",
+ "properties": {
+ "$prev_pageview_id": "01983921-5987-7c35-b1d3-71edaae744be",
+ "$os": "Windows",
+ "$recording_status": "buffering",
+ "$prev_pageview_last_scroll_percentage": 0.6716417910447762,
+ "$lib_rate_limit_remaining_tokens": 99,
+ "$window_id": "01983928-b845-7837-b93a-30057cbfd5ac",
+ "$viewport_height": 599,
+ "$browser_version": 138,
+ "$initialization_time": "2025-07-01T00:00:00Z",
+ "$web_vitals_enabled_server_side": false,
+ "$exception_capture_enabled_server_side": false,
+ "$feature_flag_request_id": "01983928-b845-7837-b93a-30057cbfd5ac",
+ "$console_log_recording_enabled_server_side": true,
+ "$prev_pageview_max_content_percentage": 0.7730789066529139,
+ "$lib_version": "1.2.3",
+ "$prev_pageview_last_scroll": 900,
+ "$device_id": "0198392d-b861-7907-a10e-de85359340c7",
+ "$referring_domain": "$direct",
+ "$sdk_debug_replay_linked_flag_trigger_status": "trigger_disabled",
+ "$browser_language": "es-419",
+ "$dead_clicks_enabled_server_side": false,
+ "$prev_pageview_max_scroll": 900,
+ "$current_url": "https://posthog.example.com/testing",
+ "$session_entry_url": "https://posthog.example.com/testing",
+ "$browser": "Chrome",
+ "$timezone": "America/Denver",
+ "$prev_pageview_last_content": 1499,
+ "$sdk_debug_replay_url_trigger_status": "trigger_pending",
+ "$replay_minimum_duration": 10000,
+ "$active_feature_flags": [],
+ "$pageview_id": "0198392e-c703-7f29-bbe0-16d7775445f9",
+ "$autocapture_disabled_server_side": false,
+ "$session_entry_host": "posthog.example.com",
+ "$prev_pageview_last_content_percentage": 0.7730789066529139,
+ "$raw_user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36",
+ "$time": 1753305291.695,
+ "$browser_language_prefix": "es",
+ "$sdk_debug_replay_remote_trigger_matching_config": null,
+ "$lib": "web",
+ "$session_entry_pathname": "/testing",
+ "$prev_pageview_max_scroll_percentage": 0.6716417910447762,
+ "$replay_script_config": null,
+ "$host": "posthog.example.com",
+ "$session_id": "0198392f-a0b0-771a-ae72-0b892aa6191a",
+ "$pathname": "/testing",
+ "$sdk_debug_current_session_duration": 99702,
+ "$config_defaults": "unset",
+ "$configured_session_timeout_ms": 1800000,
+ "$timezone_offset": 360,
+ "$session_recording_network_payload_capture": {
+ "capturePerformance": {
+ "network_timing": true,
+ "web_vitals": false
+ }
+ },
+ "$session_recording_canvas_recording": {},
+ "$sdk_debug_session_start": 1753305190397,
+ "$sdk_debug_replay_internal_buffer_length": 150,
+ "$device_type": "Desktop",
+ "$referrer": "$direct",
+ "$replay_sample_rate": null,
+ "$viewport_width": 1366,
+ "$session_entry_referring_domain": "posthog.example.com",
+ "$prev_pageview_pathname": "/testing",
+ "$feature_flag_payloads": {},
+ "$sdk_debug_retry_queue_size": 0,
+ "$is_identified": true,
+ "$os_version": "10",
+ "$session_recording_masking": {
+ "maskAllInputs": false
+ },
+ "$screen_height": 768,
+ "$sdk_debug_replay_event_trigger_status": "trigger_disabled",
+ "$session_entry_referrer": "https://posthog.example.com/testing",
+ "$insert_id": "xyz123abc456",
+ "$sdk_debug_replay_internal_buffer_size": 446278,
+ "$screen_width": 1366,
+ "$prev_pageview_max_content": 1499,
+ "$prev_pageview_duration": 10.296
+ }
+ }
+ ]
+}
\ No newline at end of file
diff --git a/rust/capture/tests/integration_new_endpoints.rs b/rust/capture/tests/integration_new_endpoints.rs
index 4f320e2b4118..efee87711e96 100644
--- a/rust/capture/tests/integration_new_endpoints.rs
+++ b/rust/capture/tests/integration_new_endpoints.rs
@@ -3,7 +3,7 @@ mod integration_utils;
use integration_utils::{
base64_payload, execute_test, form_data_base64_payload, form_lz64_urlencoded_payload,
form_urlencoded_payload, gzipped_payload, lz64_payload, plain_json_payload, Method, TestCase,
- BATCH_EVENTS_JSON, DEFAULT_TEST_TIME, SINGLE_EVENT_JSON,
+ BATCH_EVENTS_JSON, BATCH_EVENTS_WITH_HEATMAP_JSON, DEFAULT_TEST_TIME, SINGLE_EVENT_JSON,
};
use axum::http::StatusCode;
@@ -335,6 +335,21 @@ fn post_cases() -> Vec<TestCase> {
StatusCode::OK,
Box::new(form_lz64_urlencoded_payload),
),
+ // batch payload where one event carries heatmap-trigger properties:
+ // capture must produce a $$heatmap redirect alongside the originals.
+ TestCase::new(
+ "new_post-simple-batch-with-heatmap-payload".to_string(),
+ DEFAULT_TEST_TIME,
+ CaptureMode::Events,
+ "",
+ BATCH_EVENTS_WITH_HEATMAP_JSON,
+ Method::Post,
+ None,
+ None,
+ "application/json",
+ StatusCode::OK,
+ Box::new(plain_json_payload),
+ ),
];
units
diff --git a/rust/common/types/src/event.rs b/rust/common/types/src/event.rs
index 6ac4baa25a77..097cff126f96 100644
--- a/rust/common/types/src/event.rs
+++ b/rust/common/types/src/event.rs
@@ -56,7 +56,7 @@ pub trait EventWithLibraryInfo {
fn extract_library_info(&self) -> Option<LibraryInfo>;
}
-#[derive(Default, Debug, Deserialize, Serialize)]
+#[derive(Clone, Default, Debug, Deserialize, Serialize)]
pub struct RawEvent {
#[serde(
alias = "$token",
@@ -119,6 +119,7 @@ pub struct CapturedEventHeaders {
pub now: Option<String>,
pub force_disable_person_processing: Option<bool>,
pub historical_migration: Option<bool>,
+ pub skip_heatmap_processing: Option<bool>,
pub dlq_reason: Option<String>,
pub dlq_step: Option<String>,
pub dlq_timestamp: Option<String>,
@@ -129,6 +130,10 @@ impl CapturedEventHeaders {
self.force_disable_person_processing = Some(value);
}
+ pub fn set_skip_heatmap_processing(&mut self, value: bool) {
+ self.skip_heatmap_processing = Some(value);
+ }
+
pub fn set_dlq_reason(&mut self, value: String) {
self.dlq_reason = Some(value);
}
@@ -186,7 +191,14 @@ impl From<CapturedEventHeaders> for OwnedHeaders {
value: historical_migration_str.as_deref(),
});
- // To prevent adding bloat to the other topic headers, only add add dlq headers when present.
+ // Only add optional headers when present, to avoid bloating every message.
+ if let Some(skip_heatmap_processing) = headers.skip_heatmap_processing {
+ let val = skip_heatmap_processing.to_string();
+ owned = owned.insert(Header {
+ key: "skip_heatmap_processing",
+ value: Some(val.as_str()),
+ });
+ }
if let Some(ref reason) = headers.dlq_reason {
owned = owned.insert(Header {
key: "dlq_reason",
@@ -235,6 +247,9 @@ impl From<OwnedHeaders> for CapturedEventHeaders {
historical_migration: headers_map
.get("historical_migration")
.and_then(|v| v.parse::<bool>().ok()),
+ skip_heatmap_processing: headers_map
+ .get("skip_heatmap_processing")
+ .and_then(|v| v.parse::<bool>().ok()),
dlq_reason: headers_map.get("dlq_reason").cloned(),
dlq_step: headers_map.get("dlq_step").cloned(),
dlq_timestamp: headers_map.get("dlq_timestamp").cloned(),
@@ -294,7 +309,7 @@ impl CapturedEvent {
} else {
None
},
- // DLQ headers should only be explicitly set when needed
+ skip_heatmap_processing: None,
dlq_reason: None,
dlq_step: None,
dlq_timestamp: None,