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): emit ingestion warnings from the session replay endpoint (#77014)

Eli Reisman2649f6aeb288
diff --git a/nodejs/src/ingestion/common/ingestion-warning-types.ts b/nodejs/src/ingestion/common/ingestion-warning-types.ts
index d9d1b957a3e7..57ef018f884c 100644
--- a/nodejs/src/ingestion/common/ingestion-warning-types.ts
+++ b/nodejs/src/ingestion/common/ingestion-warning-types.ts
@@ -111,6 +111,13 @@ export const INGESTION_WARNING_TYPES = {
replay_lib_version_too_old: { category: 'replay', severity: 'info' },
message_contained_no_valid_rrweb_events: { category: 'replay', severity: 'warning' },
message_timestamp_diff_too_large: { category: 'replay', severity: 'warning' },
+ // Capture's replay endpoint (/s), which validates the $snapshot envelope before
+ // the batch is collapsed into one $snapshot_items message. Distinguished from the
+ // three above by `source: capture` and `path: replay` — those describe conditions
+ // found after ingestion, these reject at the edge.
+ missing_session_id: { category: 'replay', severity: 'error', captureProduced: true },
+ invalid_session_id: { category: 'replay', severity: 'error', captureProduced: true },
+ missing_snapshot_data: { category: 'replay', severity: 'error', captureProduced: true },
} as const satisfies Record<
string,
{
diff --git a/rust/capture/src/config.rs b/rust/capture/src/config.rs
index 0e2d62332553..62ceff25cbe6 100644
--- a/rust/capture/src/config.rs
+++ b/rust/capture/src/config.rs
@@ -456,9 +456,10 @@ pub struct Config {
#[envconfig(default = "1048576")]
pub capture_ingestion_warnings_kafka_message_max_bytes: u32,
- // The warnings emitter's own destination. It runs in the v1 analytics
- // handler but is independent of the v0 `KAFKA_*` block: it reads only these
- // three vars, never `kafka_hosts` / `kafka_tls` /
+ // The warnings emitter's own destination. It serves every pipeline that
+ // emits (v1 and legacy analytics, both AI endpoints, and replay) but is
+ // independent of the v0 `KAFKA_*` block: it reads only these three vars,
+ // never `kafka_hosts` / `kafka_tls` /
// `kafka_client_ingestion_warning_topic`. charts sets all three per env,
// pointed at the MSK cluster the clientwarnings consumer reads from.
//
diff --git a/rust/capture/src/events/analytics.rs b/rust/capture/src/events/analytics.rs
index 5f8298fb5307..39e5972fd002 100644
--- a/rust/capture/src/events/analytics.rs
+++ b/rust/capture/src/events/analytics.rs
@@ -7,7 +7,9 @@ use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use chrono::DateTime;
-use common_ingestion_warnings::{WarningEmitter, CAPTURE_LEGACY_RATE_LIMIT};
+use common_ingestion_warnings::{
+ WarningEmitter, CAPTURE_LEGACY_ANALYTICS, CAPTURE_LEGACY_RATE_LIMIT,
+};
use common_types::{CapturedEvent, RawEvent};
use limiters::token_dropper::TokenDropper;
use metrics::counter;
@@ -25,10 +27,8 @@ use crate::{
events::overflow_stamping::stamp_overflow_reason,
global_rate_limiter::{GlobalRateLimitKey, GlobalRateLimiter},
ingestion_warnings::{
- emit_rate_limit_warning,
- legacy::{
- emit_distinct_id_truncated_warning, emit_processing_abort_warning, request_context,
- },
+ emit_distinct_id_truncated_warning, emit_rate_limit_warning,
+ legacy::{emit_processing_abort_warning, request_context},
},
prometheus::{report_clock_skew, report_dropped_events},
router, sinks,
@@ -593,6 +593,7 @@ async fn process_events_inner(
emit_distinct_id_truncated_warning(
ingestion_warning_emitter.as_deref(),
&request_context(context),
+ CAPTURE_LEGACY_ANALYTICS,
truncated_sample.filter(|_| truncated_count == 1),
truncated_count,
);
diff --git a/rust/capture/src/events/recordings.rs b/rust/capture/src/events/recordings.rs
index 32ba7e4f4f5f..6ed154c2b494 100644
--- a/rust/capture/src/events/recordings.rs
+++ b/rust/capture/src/events/recordings.rs
@@ -13,7 +13,8 @@
use std::sync::Arc;
use chrono::DateTime;
-use common_types::{CapturedEvent, HasEventName};
+use common_ingestion_warnings::{WarningEmitter, CAPTURE_REPLAY};
+use common_types::{CapturedEvent, ExtractedDistinctId, HasEventName};
use limiters::redis::RedisLimiter;
use metrics::{counter, histogram};
use serde::{Deserialize, Deserializer, Serialize};
@@ -30,6 +31,13 @@ use crate::{
AppliedRestrictions, EventContext as RestrictionEventContext, EventRestrictionService,
Pipeline,
},
+ ingestion_warnings::{
+ emit_distinct_id_truncated_warning,
+ replay::{
+ emit_replay_abort_warning, request_context, ReplayRejectionReason, SessionIdRejection,
+ SnapshotDataRejection,
+ },
+ },
prometheus::report_dropped_events,
sinks,
utils::uuid_v7_from_datetime,
@@ -115,6 +123,11 @@ pub struct RecordingProperties {
#[serde(rename = "$lib", skip_serializing_if = "Option::is_none")]
pub lib: Option<String>,
+ /// Read only for ingestion-warning attribution, unlike `$lib`, which also
+ /// lands in the serialized snapshot as the recording's library.
+ #[serde(rename = "$lib_version", skip_serializing_if = "Option::is_none")]
+ pub lib_version: Option<String>,
+
#[serde(rename = "$cookieless_mode", skip_serializing_if = "Option::is_none")]
pub cookieless_mode: Option<bool>,
@@ -147,8 +160,22 @@ impl RawRecording {
.and_then(|value| OffsetDateTime::parse(value, &Iso8601::DEFAULT).ok())
}
- /// Extract the distinct_id, checking both root field and properties
- pub fn extract_distinct_id(&self) -> Option<String> {
+ /// Extract the distinct_id, checking both root field and properties, and
+ /// report whether it was cut down to the 200-char cap so the caller can tell
+ /// the sender their id was modified.
+ ///
+ /// Truncation is reported only when the value was actually cut. An id over
+ /// 200 bytes but within 200 chars survives `chars().take(200)` intact, so
+ /// reporting it would warn a customer about a modification that never
+ /// happened. This matches [`common_types::ExtractedDistinctId`]'s contract on
+ /// the analytics path, which is what lets one warning type mean the same
+ /// thing on both.
+ ///
+ /// Deliberately not shared with `RawEvent::extract_distinct_id_checked`: that
+ /// one also trims whitespace, rejects ids that are empty after trimming, and
+ /// counts a whitespace metric. Adopting those here would change which replay
+ /// payloads capture accepts.
+ pub fn extract_distinct_id(&self) -> Option<ExtractedDistinctId> {
let value = match &self.distinct_id {
None | Some(Value::Null) => match &self.properties.distinct_id {
None | Some(Value::Null) => return None,
@@ -164,11 +191,31 @@ impl RawRecording {
let distinct_id = distinct_id.replace('\0', "\u{FFFD}");
- match distinct_id.len() {
- 0 => None,
- 1..=200 => Some(distinct_id),
- _ => Some(distinct_id.chars().take(200).collect()),
+ if distinct_id.is_empty() {
+ return None;
+ }
+
+ // Byte length bounds char count, so ids within 200 bytes skip the
+ // char-count pass entirely on the hot path.
+ if distinct_id.len() <= 200 {
+ return Some(ExtractedDistinctId {
+ value: distinct_id,
+ truncated_from_chars: None,
+ });
+ }
+
+ let char_count = distinct_id.chars().count();
+ if char_count <= 200 {
+ return Some(ExtractedDistinctId {
+ value: distinct_id,
+ truncated_from_chars: None,
+ });
}
+
+ Some(ExtractedDistinctId {
+ value: distinct_id.chars().take(200).collect(),
+ truncated_from_chars: Some(char_count),
+ })
}
/// Extract token from root field or properties
@@ -210,9 +257,104 @@ pub async fn process_replay_events(
sink: Arc<dyn sinks::Event + Send + Sync>,
restriction_service: Option<EventRestrictionService>,
replay_overflow_limiter: Option<Arc<RedisLimiter>>,
+ ingestion_warning_emitter: Option<Arc<dyn WarningEmitter>>,
events: Vec<RawRecording>,
context: &ProcessingContext,
) -> Result<(), CaptureError> {
+ let event_count = events.len() as u64;
+
+ let abort = match process_replay_events_inner(
+ sink,
+ restriction_service,
+ replay_overflow_limiter,
+ events,
+ context,
+ )
+ .await
+ {
+ // The batch collapses into one message carrying one distinct_id, so a
+ // truncation is always exactly one modified id: `count` is 1 and the
+ // sample is never an arbitrary pick among several.
+ Ok(truncated_sample) => {
+ if truncated_sample.is_some() {
+ emit_distinct_id_truncated_warning(
+ ingestion_warning_emitter.as_deref(),
+ &request_context(context),
+ CAPTURE_REPLAY,
+ truncated_sample,
+ 1,
+ );
+ }
+ return Ok(());
+ }
+ Err(abort) => abort,
+ };
+
+ emit_replay_abort_warning(
+ ingestion_warning_emitter.as_deref(),
+ context,
+ &abort.error,
+ abort.reason,
+ abort.session_id_bytes,
+ event_count,
+ );
+
+ Err(abort.error)
+}
+
+/// A replay abort, carrying the warning detail that names the specific condition
+/// behind a `CaptureError` variant that covers several.
+///
+/// The `From<CaptureError>` impl is what lets the pipeline keep using `?` for the
+/// aborts that need no extra detail.
+struct ReplayAbort {
+ error: CaptureError,
+ reason: Option<ReplayRejectionReason>,
+ /// Byte length of the offending `$session_id`, matching the limit that
+ /// rejected it. Session ids are constrained to ASCII, so for any id that
+ /// fails only on length this is also its character count.
+ session_id_bytes: Option<usize>,
+}
+
+impl From<CaptureError> for ReplayAbort {
+ fn from(error: CaptureError) -> Self {
+ Self {
+ error,
+ reason: None,
+ session_id_bytes: None,
+ }
+ }
+}
+
+impl ReplayAbort {
+ fn invalid_session_id(reason: SessionIdRejection, bytes: Option<usize>) -> Self {
+ Self {
+ error: CaptureError::InvalidSessionId,
+ reason: Some(ReplayRejectionReason::InvalidSessionId(reason)),
+ session_id_bytes: bytes,
+ }
+ }
+
+ fn missing_snapshot_data(reason: SnapshotDataRejection) -> Self {
+ Self {
+ error: CaptureError::MissingSnapshotData,
+ reason: Some(ReplayRejectionReason::MissingSnapshotData(reason)),
+ session_id_bytes: None,
+ }
+ }
+}
+
+/// Returns the truncated-distinct_id sample when the ingested id was cut down to
+/// the 200-char cap, for the caller to warn about. `None` means nothing was
+/// modified, including when the request was dropped by an event restriction and
+/// so ingested nothing to warn about.
+async fn process_replay_events_inner(
+ sink: Arc<dyn sinks::Event + Send + Sync>,
+ restriction_service: Option<EventRestrictionService>,
+ replay_overflow_limiter: Option<Arc<RedisLimiter>>,
+ events: Vec<RawRecording>,
+ context: &ProcessingContext,
+) -> Result<Option<(String, usize, Uuid)>, ReplayAbort> {
let chatty_debug_enabled = context.chatty_debug_enabled;
Span::current().record("request_id", &context.request_id);
@@ -240,9 +382,14 @@ pub async fn process_replay_events(
let uuid = first_event
.uuid
.unwrap_or_else(|| uuid_v7_from_datetime(computed_timestamp));
- let distinct_id = first_event
+ let extracted_distinct_id = first_event
.extract_distinct_id()
.ok_or(CaptureError::MissingDistinctId)?;
+ let distinct_id = extracted_distinct_id.value;
+ // Only clones on the rare truncated path; the id is moved into the event below.
+ let truncated_sample = extracted_distinct_id
+ .truncated_from_chars
+ .map(|chars| (distinct_id.clone(), chars, uuid));
let is_cookieless_mode = first_event
.extract_is_cookieless_mode()
.ok_or(CaptureError::InvalidCookielessMode)?;
@@ -254,14 +401,26 @@ pub async fn process_replay_events(
.take()
.ok_or(CaptureError::MissingSessionId)?;
- // Validate session_id
- let session_id_str = session_id.as_str().ok_or(CaptureError::InvalidSessionId)?;
- if session_id_str.len() > 70
- || !session_id_str
- .chars()
- .all(|c| c.is_ascii_alphanumeric() || c == '-')
+ // Validate session_id. Split into two checks so the ingestion warning can
+ // name which rule the id broke; the accept/reject outcome is unchanged, and
+ // length is still evaluated first so an id that breaks both reports length.
+ let session_id_str = session_id
+ .as_str()
+ .ok_or_else(|| ReplayAbort::invalid_session_id(SessionIdRejection::NotAString, None))?;
+ if session_id_str.len() > 70 {
+ return Err(ReplayAbort::invalid_session_id(
+ SessionIdRejection::TooLong,
+ Some(session_id_str.len()),
+ ));
+ }
+ if !session_id_str
+ .chars()
+ .all(|c| c.is_ascii_alphanumeric() || c == '-')
{
- return Err(CaptureError::InvalidSessionId);
+ return Err(ReplayAbort::invalid_session_id(
+ SessionIdRejection::InvalidCharset,
+ Some(session_id_str.len()),
+ ));
}
Span::current().record("session_id", session_id_str);
@@ -282,7 +441,7 @@ pub async fn process_replay_events(
if applied.should_drop() {
report_dropped_events("event_restriction_drop", 1);
- return Ok(());
+ return Ok(None);
}
applied
@@ -313,7 +472,7 @@ pub async fn process_replay_events(
.properties
.lib
.take()
- .or_else(|| snapshot_library_fallback_from(context.user_agent.as_ref()))
+ .or_else(|| snapshot_library_fallback_from(context.user_agent.as_deref()))
.unwrap_or_else(|| String::from("unknown"));
// Collect snapshot items from all events by taking ownership (no clone!)
@@ -322,7 +481,9 @@ pub async fn process_replay_events(
// Process first event's snapshot_data
let Some(snapshot_data) = first_event.properties.snapshot_data.take() else {
- return Err(CaptureError::MissingSnapshotData);
+ return Err(ReplayAbort::missing_snapshot_data(
+ SnapshotDataRejection::Absent,
+ ));
};
match snapshot_data {
Value::Array(mut arr) => {
@@ -332,14 +493,18 @@ pub async fn process_replay_events(
snapshot_items.push(Value::Object(obj));
}
_ => {
- return Err(CaptureError::MissingSnapshotData);
+ return Err(ReplayAbort::missing_snapshot_data(
+ SnapshotDataRejection::WrongJsonType,
+ ));
}
}
// Process remaining events' snapshot_data
for mut event in events_iter {
let Some(snapshot_data) = event.properties.snapshot_data.take() else {
- return Err(CaptureError::MissingSnapshotData);
+ return Err(ReplayAbort::missing_snapshot_data(
+ SnapshotDataRejection::Absent,
+ ));
};
match snapshot_data {
Value::Array(mut arr) => {
@@ -349,7 +514,9 @@ pub async fn process_replay_events(
snapshot_items.push(Value::Object(obj));
}
_ => {
- return Err(CaptureError::MissingSnapshotData);
+ return Err(ReplayAbort::missing_snapshot_data(
+ SnapshotDataRejection::WrongJsonType,
+ ));
}
}
}
@@ -398,7 +565,7 @@ pub async fn process_replay_events(
redirect_to_topic: applied.redirect_to_topic().map(|s| s.to_string()),
skip_heatmap_processing: false,
overflow_reason,
- distinct_id_truncated_from: None,
+ distinct_id_truncated_from: extracted_distinct_id.truncated_from_chars,
};
// Serialize snapshot data synchronously
@@ -437,7 +604,7 @@ pub async fn process_replay_events(
debug_or_info!(chatty_debug_enabled, context=?context, "sent recordings CapturedEvent");
- Ok(())
+ Ok(truncated_sample)
}
/// Asynchronously serialize snapshot data by offloading to blocking thread pool
@@ -497,7 +664,11 @@ pub fn serialize_snapshot_data_sync(
data.to_string()
}
-fn snapshot_library_fallback_from(user_agent: Option<&String>) -> Option<String> {
+/// Derive the recording's library from the user agent when the payload carried no
+/// `$lib`. Shared with the ingestion-warning attribution in
+/// [`crate::ingestion_warnings::replay`] so a warning names the same library as
+/// the event it is about.
+pub(crate) fn snapshot_library_fallback_from(user_agent: Option<&str>) -> Option<String> {
user_agent?
.split('/')
.next()
@@ -510,6 +681,9 @@ fn snapshot_library_fallback_from(user_agent: Option<&String>) -> Option<String>
mod tests {
use super::*;
use crate::event_restrictions::RestrictionType;
+ use common_ingestion_warnings::test_support::CollectingEmitter;
+ use common_ingestion_warnings::WarningType;
+ use rstest::rstest;
use serde_json::json;
#[test]
@@ -532,7 +706,10 @@ mod tests {
recording.sent_at(),
Some(OffsetDateTime::from_unix_timestamp_nanos(1_704_164_645_678_000_000).unwrap())
);
- assert_eq!(recording.extract_distinct_id(), Some("user123".to_string()));
+ assert_eq!(
+ recording.extract_distinct_id().map(|e| e.value),
+ Some("user123".to_string())
+ );
assert_eq!(
recording.properties.session_id,
Some(Value::String("session-abc".to_string()))
@@ -558,7 +735,64 @@ mod tests {
});
let recording: RawRecording = serde_json::from_value(json).unwrap();
- assert_eq!(recording.extract_distinct_id(), Some("user456".to_string()));
+ assert_eq!(
+ recording.extract_distinct_id().map(|e| e.value),
+ Some("user456".to_string())
+ );
+ }
+
+ // Truncation drives a customer-facing `distinct_id_truncated` warning, so
+ // reporting it for an id that was ingested intact is a false alarm. The
+ // multi-byte cases are the trap: matching on byte length (which this
+ // extractor used to do) flags ids that `chars().take(200)` never cuts.
+ //
+ // Each case also asserts the replay extractor agrees with the analytics one,
+ // so the single warning type keeps meaning the same thing on both paths.
+ // Parity holds for these inputs because none has surrounding whitespace,
+ // which `RawEvent` trims and this extractor deliberately does not.
+ #[rstest]
+ #[case::short("abc", 3, None)]
+ #[case::ascii_at_the_cap(&"a".repeat(200), 200, None)]
+ #[case::ascii_over_the_cap(&"a".repeat(201), 200, Some(201))]
+ #[case::multibyte_over_200_bytes_within_200_chars(&"é".repeat(150), 150, None)]
+ #[case::multibyte_over_200_chars(&"é".repeat(201), 200, Some(201))]
+ fn distinct_id_truncation_is_reported_only_when_the_value_was_cut(
+ #[case] distinct_id: &str,
+ #[case] expected_chars: usize,
+ #[case] expected_truncated_from: Option<usize>,
+ ) {
+ let recording: RawRecording = serde_json::from_value(json!({
+ "event": "$snapshot",
+ "distinct_id": distinct_id,
+ "properties": {"$session_id": "s", "$snapshot_data": [{"type": 1}]}
+ }))
+ .unwrap();
+
+ let extracted = recording
+ .extract_distinct_id()
+ .expect("a non-empty distinct_id must extract");
+ assert_eq!(extracted.value.chars().count(), expected_chars);
+ assert_eq!(extracted.truncated_from_chars, expected_truncated_from);
+
+ let analytics = common_types::RawEvent {
+ distinct_id: Some(json!(distinct_id)),
+ ..Default::default()
+ }
+ .extract_distinct_id_checked()
+ .expect("a non-empty distinct_id must extract");
+ assert_eq!(
+ extracted, analytics,
+ "replay and analytics extraction must agree so one warning type means one thing"
+ );
+ }
+
+ #[rstest]
+ #[case::absent(json!({"event": "$snapshot", "properties": {}}))]
+ #[case::null(json!({"event": "$snapshot", "distinct_id": null, "properties": {}}))]
+ #[case::empty_string(json!({"event": "$snapshot", "distinct_id": "", "properties": {}}))]
+ fn unusable_distinct_ids_extract_to_none(#[case] payload: Value) {
+ let recording: RawRecording = serde_json::from_value(payload).unwrap();
+ assert!(recording.extract_distinct_id().is_none());
}
#[test]
@@ -658,7 +892,7 @@ mod tests {
let context = create_test_context();
let result =
- process_replay_events(sink, Some(service), None, vec![recording], &context).await;
+ process_replay_events(sink, Some(service), None, None, vec![recording], &context).await;
assert!(result.is_ok());
assert!(events_captured.lock().unwrap().is_empty());
@@ -692,7 +926,7 @@ mod tests {
let context = create_test_context();
let result =
- process_replay_events(sink, Some(service), None, vec![recording], &context).await;
+ process_replay_events(sink, Some(service), None, None, vec![recording], &context).await;
assert!(result.is_ok());
let captured = events_captured.lock().unwrap();
@@ -728,7 +962,7 @@ mod tests {
let context = create_test_context();
let result =
- process_replay_events(sink, Some(service), None, vec![recording], &context).await;
+ process_replay_events(sink, Some(service), None, None, vec![recording], &context).await;
assert!(result.is_ok());
let captured = events_captured.lock().unwrap();
@@ -764,7 +998,7 @@ mod tests {
let context = create_test_context();
let result =
- process_replay_events(sink, Some(service), None, vec![recording], &context).await;
+ process_replay_events(sink, Some(service), None, None, vec![recording], &context).await;
assert!(result.is_ok());
let captured = events_captured.lock().unwrap();
@@ -782,7 +1016,7 @@ mod tests {
let recording = create_test_recording();
let context = create_test_context();
- let result = process_replay_events(sink, None, None, vec![recording], &context).await;
+ let result = process_replay_events(sink, None, None, None, vec![recording], &context).await;
assert!(result.is_ok());
let captured = events_captured.lock().unwrap();
@@ -811,7 +1045,7 @@ mod tests {
recording.properties.snapshot_host = stamp.clone();
let context = create_test_context();
- process_replay_events(sink, None, None, vec![recording], &context)
+ process_replay_events(sink, None, None, None, vec![recording], &context)
.await
.unwrap();
@@ -856,7 +1090,7 @@ mod tests {
let context = create_test_context();
let result =
- process_replay_events(sink, Some(service), None, vec![recording], &context).await;
+ process_replay_events(sink, Some(service), None, None, vec![recording], &context).await;
// Should NOT be dropped because session_id doesn't match filter
assert!(result.is_ok());
@@ -900,7 +1134,7 @@ mod tests {
let recording = create_test_recording();
let context = create_test_context();
- let result = process_replay_events(sink, None, None, vec![recording], &context).await;
+ let result = process_replay_events(sink, None, None, None, vec![recording], &context).await;
assert!(result.is_ok());
let captured = events_captured.lock().unwrap();
@@ -920,7 +1154,7 @@ mod tests {
let context = create_test_context();
let result =
- process_replay_events(sink, None, Some(limiter), vec![recording], &context).await;
+ process_replay_events(sink, None, Some(limiter), None, vec![recording], &context).await;
assert!(result.is_ok());
let captured = events_captured.lock().unwrap();
@@ -943,7 +1177,7 @@ mod tests {
let context = create_test_context();
let result =
- process_replay_events(sink, None, Some(limiter), vec![recording], &context).await;
+ process_replay_events(sink, None, Some(limiter), None, vec![recording], &context).await;
assert!(result.is_ok());
let captured = events_captured.lock().unwrap();
@@ -986,6 +1220,7 @@ mod tests {
sink,
Some(service),
Some(limiter),
+ None,
vec![recording],
&context,
)
@@ -1013,7 +1248,8 @@ mod tests {
let recordings = vec![create_test_recording(), create_test_recording()];
let context = create_test_context();
- let result = process_replay_events(sink, None, Some(limiter), recordings, &context).await;
+ let result =
+ process_replay_events(sink, None, Some(limiter), None, recordings, &context).await;
assert!(result.is_ok());
let captured = events_captured.lock().unwrap();
@@ -1076,7 +1312,7 @@ mod tests {
let limiter = build_replay_limiter(vec!["test-session-123".to_string()]).await;
let recording = create_test_recording();
let context = create_test_context();
- process_replay_events(sink, None, Some(limiter), vec![recording], &context)
+ process_replay_events(sink, None, Some(limiter), None, vec![recording], &context)
.await
.unwrap();
})
@@ -1102,7 +1338,7 @@ mod tests {
let limiter = build_replay_limiter(vec!["some-other-session".to_string()]).await;
let recording = create_test_recording();
let context = create_test_context();
- process_replay_events(sink, None, Some(limiter), vec![recording], &context)
+ process_replay_events(sink, None, Some(limiter), None, vec![recording], &context)
.await
.unwrap();
})
@@ -1149,6 +1385,7 @@ mod tests {
sink,
Some(service),
Some(limiter),
+ None,
vec![recording],
&context,
)
@@ -1174,7 +1411,7 @@ mod tests {
});
let recording = create_test_recording();
let context = create_test_context();
- process_replay_events(sink, None, None, vec![recording], &context)
+ process_replay_events(sink, None, None, None, vec![recording], &context)
.await
.unwrap();
})
@@ -1209,7 +1446,7 @@ mod tests {
let recording = create_test_recording(); // session_id = "test-session-123"
let context = create_test_context();
- process_replay_events(sink, None, Some(limiter), vec![recording], &context)
+ process_replay_events(sink, None, Some(limiter), None, vec![recording], &context)
.await
.unwrap();
@@ -1225,4 +1462,157 @@ mod tests {
"replay overflow keeps session_id partition key"
);
}
+
+ fn recording_with_properties(properties: Value) -> RawRecording {
+ serde_json::from_value(json!({
+ "event": "$snapshot",
+ "distinct_id": "test_user",
+ "properties": properties,
+ }))
+ .unwrap()
+ }
+
+ async fn warnings_from_replay(
+ events: Vec<RawRecording>,
+ ) -> Vec<common_ingestion_warnings::test_support::EmittedWarning> {
+ let sink: Arc<dyn Event + Send + Sync> = Arc::new(MockSink {
+ events: Arc::new(Mutex::new(Vec::new())),
+ });
+ let emitter = Arc::new(CollectingEmitter::default());
+
+ // The outcome is asserted by each caller through the warnings; a failing
+ // result is the point in most of these cases.
+ drop(
+ process_replay_events(
+ sink,
+ None,
+ None,
+ Some(emitter.clone()),
+ events,
+ &create_test_context(),
+ )
+ .await,
+ );
+
+ emitter.emitted()
+ }
+
+ // The mapper and details are unit-tested in `ingestion_warnings::replay`; what
+ // no helper test can catch is the pipeline failing to call it, or calling it
+ // with the wrong reason for the branch that rejected. Each case here pins one
+ // emit site to the condition that reaches it.
+ #[rstest]
+ #[case::missing_session_id(
+ json!({"$snapshot_data": [{"type": 1}]}),
+ WarningType::MissingSessionId,
+ None
+ )]
+ #[case::session_id_not_a_string(
+ json!({"$session_id": 42, "$snapshot_data": [{"type": 1}]}),
+ WarningType::InvalidSessionId,
+ Some("not_a_string")
+ )]
+ #[case::session_id_too_long(
+ json!({"$session_id": "a".repeat(71), "$snapshot_data": [{"type": 1}]}),
+ WarningType::InvalidSessionId,
+ Some("too_long")
+ )]
+ #[case::session_id_bad_charset(
+ json!({"$session_id": "not a valid id", "$snapshot_data": [{"type": 1}]}),
+ WarningType::InvalidSessionId,
+ Some("invalid_charset")
+ )]
+ #[case::snapshot_data_absent(
+ json!({"$session_id": "s"}),
+ WarningType::MissingSnapshotData,
+ Some("absent")
+ )]
+ #[case::snapshot_data_wrong_type(
+ json!({"$session_id": "s", "$snapshot_data": "not-an-array"}),
+ WarningType::MissingSnapshotData,
+ Some("wrong_json_type")
+ )]
+ #[tokio::test]
+ async fn replay_validation_failures_emit_their_warning(
+ #[case] properties: Value,
+ #[case] expected: WarningType,
+ #[case] expected_reason: Option<&str>,
+ ) {
+ let emitted = warnings_from_replay(vec![recording_with_properties(properties)]).await;
+
+ assert_eq!(emitted.len(), 1);
+ assert_eq!(emitted[0].warning, expected);
+ assert_eq!(emitted[0].source, CAPTURE_REPLAY);
+ assert_eq!(
+ emitted[0]
+ .extra_details
+ .get("reason")
+ .and_then(|r| r.as_str()),
+ expected_reason
+ );
+ }
+
+ #[tokio::test]
+ async fn missing_distinct_id_emits_its_warning() {
+ let recording: RawRecording = serde_json::from_value(json!({
+ "event": "$snapshot",
+ "properties": {"$session_id": "s", "$snapshot_data": [{"type": 1}]},
+ }))
+ .unwrap();
+
+ let emitted = warnings_from_replay(vec![recording]).await;
+
+ assert_eq!(emitted.len(), 1);
+ assert_eq!(emitted[0].warning, WarningType::MissingDistinctId);
+ }
+
+ // A later event's missing snapshot data aborts the whole request, so the
+ // warning must charge every event in it, not just the offending one.
+ #[tokio::test]
+ async fn a_later_events_bad_snapshot_data_charges_the_whole_batch() {
+ let good = recording_with_properties(json!({
+ "$session_id": "s", "$snapshot_data": [{"type": 1}]
+ }));
+ let bad = recording_with_properties(json!({"$session_id": "s"}));
+
+ let emitted = warnings_from_replay(vec![good, bad]).await;
+
+ assert_eq!(emitted.len(), 1);
+ assert_eq!(emitted[0].warning, WarningType::MissingSnapshotData);
+ assert_eq!(emitted[0].count, 2);
+ }
+
+ #[tokio::test]
+ async fn a_valid_batch_emits_nothing() {
+ let emitted = warnings_from_replay(vec![create_test_recording()]).await;
+ assert!(emitted.is_empty());
+ }
+
+ // The id is ingested after being cut, so this rides the success path. Nothing
+ // else proves the pipeline reads the truncation outcome it now computes.
+ #[tokio::test]
+ async fn a_truncated_distinct_id_warns_on_the_success_path() {
+ let long_id = "a".repeat(201);
+ let recording: RawRecording = serde_json::from_value(json!({
+ "event": "$snapshot",
+ "distinct_id": long_id,
+ "properties": {"$session_id": "s", "$snapshot_data": [{"type": 1}]},
+ }))
+ .unwrap();
+
+ let emitted = warnings_from_replay(vec![recording]).await;
+
+ assert_eq!(emitted.len(), 1);
+ assert_eq!(emitted[0].warning, WarningType::DistinctIdTruncated);
+ assert_eq!(emitted[0].source, CAPTURE_REPLAY);
+ assert_eq!(emitted[0].count, 1);
+ assert_eq!(emitted[0].extra_details["distinctIdLength"], json!(201));
+ assert_eq!(
+ emitted[0].extra_details["distinctId"]
+ .as_str()
+ .map(|s| s.chars().count()),
+ Some(200),
+ "the reported id is the truncated one that was actually ingested"
+ );
+ }
}
diff --git a/rust/capture/src/ingestion_warnings/legacy.rs b/rust/capture/src/ingestion_warnings/legacy.rs
index 2291d094f681..1b162eef5e4c 100644
--- a/rust/capture/src/ingestion_warnings/legacy.rs
+++ b/rust/capture/src/ingestion_warnings/legacy.rs
@@ -13,8 +13,7 @@ use common_ingestion_warnings::{
emit_request_warning, WarningEmitter, WarningRequestContext, WarningType,
CAPTURE_LEGACY_ANALYTICS,
};
-use serde_json::{json, Map};
-use uuid::Uuid;
+use serde_json::Map;
use super::unknown_if_missing;
use crate::api::CaptureError;
@@ -34,39 +33,6 @@ pub fn request_context(context: &ProcessingContext) -> WarningRequestContext {
}
}
-/// Emit the `distinct_id_truncated` warning for one legacy batch's events
-/// whose distinct_id was cut down to the 200-char cap at extraction. The
-/// events were ingested (modified, not dropped), so this is legacy-only: v1
-/// rejects oversized ids outright as `distinct_id_too_large`.
-///
-/// Identifier details are included only when the batch had exactly one
-/// truncated event; with several they would be an arbitrary pick, and `count`
-/// already carries the volume. The truncated value is at most 200 chars, so
-/// it needs no bounding of its own; `distinctIdLength` is the original char
-/// count, telling the customer how far over the cap they were.
-pub fn emit_distinct_id_truncated_warning(
- emitter: Option<&dyn WarningEmitter>,
- request: &WarningRequestContext,
- sample: Option<(String, usize, Uuid)>,
- count: u64,
-) {
- let mut details = Map::new();
- if let Some((distinct_id, original_chars, event_uuid)) = sample {
- details.insert("distinctId".to_string(), json!(distinct_id));
- details.insert("distinctIdLength".to_string(), json!(original_chars));
- details.insert("eventUuid".to_string(), json!(event_uuid));
- }
-
- emit_request_warning(
- emitter,
- request,
- CAPTURE_LEGACY_ANALYTICS,
- WarningType::DistinctIdTruncated,
- details,
- count,
- );
-}
-
/// Map a legacy-path request abort to the ingestion warning customers should
/// see, or `None` for failures customers can't act on.
///
@@ -173,6 +139,7 @@ mod tests {
use crate::ingestion_warnings::{raw_event, SdkAttribution, MAX_SDK_ATTRIBUTION_LEN};
use common_ingestion_warnings::test_support::CollectingEmitter;
use common_ingestion_warnings::UNKNOWN_ATTRIBUTION;
+ use serde_json::json;
fn legacy_context(attribution: SdkAttribution) -> ProcessingContext {
ProcessingContext {
diff --git a/rust/capture/src/ingestion_warnings/mod.rs b/rust/capture/src/ingestion_warnings/mod.rs
index 0ab78fb8ea2b..b10fda9bf744 100644
--- a/rust/capture/src/ingestion_warnings/mod.rs
+++ b/rust/capture/src/ingestion_warnings/mod.rs
@@ -25,6 +25,7 @@
pub mod ai;
pub mod legacy;
pub mod otel;
+pub mod replay;
use std::collections::HashSet;
@@ -34,6 +35,7 @@ use common_ingestion_warnings::{
};
use common_types::{EventWithLibraryInfo, RawEvent};
use serde_json::{json, Map};
+use uuid::Uuid;
/// Max accepted length of a client-supplied `$lib` or `$lib_version`, matching
/// the bound v1 puts on the `PostHog-Sdk-Info` header (real values are ~20
@@ -141,6 +143,42 @@ pub fn emit_rate_limit_warning(
);
}
+/// Emit the `distinct_id_truncated` warning for one batch's events whose
+/// distinct_id was cut down to the 200-char cap at extraction. The events were
+/// ingested (modified, not dropped), which is why v1 has no counterpart: it
+/// rejects oversized ids outright as `distinct_id_too_large`. Shared by the
+/// legacy analytics and replay pipelines, which differ only in their
+/// [`WarningSource`], so that the payload cannot drift between them.
+///
+/// Identifier details are included only when the batch had exactly one
+/// truncated event; with several they would be an arbitrary pick, and `count`
+/// already carries the volume. The truncated value is at most 200 chars, so
+/// it needs no bounding of its own; `distinctIdLength` is the original char
+/// count, telling the customer how far over the cap they were.
+pub fn emit_distinct_id_truncated_warning(
+ emitter: Option<&dyn WarningEmitter>,
+ request: &WarningRequestContext,
+ source: WarningSource,
+ sample: Option<(String, usize, Uuid)>,
+ count: u64,
+) {
+ let mut details = Map::new();
+ if let Some((distinct_id, original_chars, event_uuid)) = sample {
+ details.insert("distinctId".to_string(), json!(distinct_id));
+ details.insert("distinctIdLength".to_string(), json!(original_chars));
+ details.insert("eventUuid".to_string(), json!(event_uuid));
+ }
+
+ emit_request_warning(
+ emitter,
+ request,
+ source,
+ WarningType::DistinctIdTruncated,
+ details,
+ count,
+ );
+}
+
/// A `RawEvent` carrying only `properties`, for the attribution tests in this
/// module and its children.
#[cfg(test)]
diff --git a/rust/capture/src/ingestion_warnings/replay.rs b/rust/capture/src/ingestion_warnings/replay.rs
new file mode 100644
index 000000000000..ee5d655e7cf8
--- /dev/null
+++ b/rust/capture/src/ingestion_warnings/replay.rs
@@ -0,0 +1,563 @@
+//! Ingestion warnings for the session replay path (`/s`).
+//!
+//! Replay's context projection lives here for the same reason legacy's does: the
+//! path has no subtree of its own, spanning `v0_endpoint`, `payload/recordings`,
+//! and `events/recordings`.
+//!
+//! Two things make replay's payloads read differently from the other pipelines'.
+//! A batch of `$snapshot` events becomes one `$snapshot_items` message, so a
+//! validation failure drops the whole request and `count` charges the batch. And
+//! the token is only known after the body has been read, decompressed and parsed
+//! (`crate::payload::recordings::handle_recording_payload`), so every transport
+//! and parse failure is unattributable here exactly as it is for legacy.
+
+use common_ingestion_warnings::{
+ emit_request_warning, WarningEmitter, WarningRequestContext, WarningType, CAPTURE_REPLAY,
+};
+use serde_json::{json, Map};
+
+use super::{unknown_if_missing, within_bound, SdkAttribution};
+use crate::api::CaptureError;
+use crate::events::recordings::{snapshot_library_fallback_from, RawRecording};
+use crate::v0_request::ProcessingContext;
+
+/// Why a `$session_id` was rejected.
+///
+/// Each value points at a different fix: a missing id means the SDK never set
+/// one, a non-string means a custom integration is passing the wrong JSON type,
+/// and the two shape failures mean the id itself has to change. The offending
+/// value is deliberately not reported (see [`emit_replay_abort_warning`]), so
+/// this is what makes the warning actionable.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum SessionIdRejection {
+ NotAString,
+ TooLong,
+ InvalidCharset,
+}
+
+impl SessionIdRejection {
+ fn as_str(self) -> &'static str {
+ match self {
+ Self::NotAString => "not_a_string",
+ Self::TooLong => "too_long",
+ Self::InvalidCharset => "invalid_charset",
+ }
+ }
+}
+
+/// Why a `$snapshot_data` property was rejected.
+///
+/// `Absent` means the property is missing entirely, which is usually an SDK too
+/// old to send it. `WrongJsonType` means it is present but neither an array of
+/// rrweb events nor a single event object, which is usually a payload built by
+/// hand.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum SnapshotDataRejection {
+ Absent,
+ WrongJsonType,
+}
+
+impl SnapshotDataRejection {
+ fn as_str(self) -> &'static str {
+ match self {
+ Self::Absent => "absent",
+ Self::WrongJsonType => "wrong_json_type",
+ }
+ }
+}
+
+/// The `reason` detail to ship with a replay abort, when the error has one.
+///
+/// `CaptureError` collapses distinguishable conditions into single variants
+/// (`CaptureError::InvalidSessionId` covers three, `CaptureError::MissingSnapshotData`
+/// two), and the HTTP status and metric tags depend on that collapsing, so the
+/// pipeline reports the specific reason alongside the error instead of splitting
+/// the variants. Each variant here is named for the error it accompanies.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum ReplayRejectionReason {
+ InvalidSessionId(SessionIdRejection),
+ MissingSnapshotData(SnapshotDataRejection),
+}
+
+impl ReplayRejectionReason {
+ fn as_str(self) -> &'static str {
+ match self {
+ Self::InvalidSessionId(reason) => reason.as_str(),
+ Self::MissingSnapshotData(reason) => reason.as_str(),
+ }
+ }
+}
+
+/// Read SDK attribution off one snapshot event, falling back to the request's
+/// user agent.
+///
+/// Callers pass the batch's first event, which is sound because one batch is one
+/// SDK in every real client (the reasoning behind
+/// [`super::SdkAttribution::from_first_event`], which takes the whole batch) and
+/// because replay reads all its other metadata from the first event too.
+///
+/// `lib` falls back to the user agent through the same helper the pipeline uses
+/// to label the ingested recording, so a warning names the library the customer
+/// will see on their events rather than a second, differently-derived guess.
+/// There is no such fallback for `lib_version`: nothing else in the request
+/// carries it, so an absent one stays absent and projects to
+/// `UNKNOWN_ATTRIBUTION`.
+pub fn attribution_from_event(event: &RawRecording, user_agent: &str) -> SdkAttribution {
+ let lib = event
+ .properties
+ .lib
+ .clone()
+ .or_else(|| snapshot_library_fallback_from(Some(user_agent)));
+
+ SdkAttribution {
+ lib: lib.and_then(within_bound),
+ lib_version: event.properties.lib_version.clone().and_then(within_bound),
+ }
+}
+
+/// Warning attribution for a replay batch.
+///
+/// Snapshot events carry `$lib`/`$lib_version` in their own envelope shape, so
+/// the payload handler projects them onto [`ProcessingContext`] while the events
+/// are still typed, the same way the legacy batch handler does.
+pub fn request_context(context: &ProcessingContext) -> WarningRequestContext {
+ WarningRequestContext {
+ token: context.token.clone(),
+ lib: unknown_if_missing(context.sdk_attribution.lib.as_deref()),
+ lib_version: unknown_if_missing(context.sdk_attribution.lib_version.as_deref()),
+ path: context.path.clone(),
+ }
+}
+
+/// Map a replay-path request abort to the ingestion warning customers should
+/// see, or `None` for failures customers can't act on.
+///
+/// This is the replay pipeline's counterpart to v1's `Error::tag()` →
+/// [`WarningType::from_tag`] route. Like legacy's, it matches enum variants
+/// rather than `to_metric_tag()` strings so renames are compile-checked, and the
+/// types it returns take the `DIRECT_EMIT` route because no `v1::Error` ever
+/// produces a tag naming a replay condition.
+///
+/// `None` arms are deliberate and exhaustive, mirroring the exclusions v1 pins
+/// in `from_tag_rejects_unregistered_tags`. There is no catch-all: a new
+/// `CaptureError` variant fails to compile here until someone decides whether
+/// customers should see a warning for it.
+pub fn warning_for_capture_error(err: &CaptureError) -> Option<WarningType> {
+ match err {
+ CaptureError::MissingDistinctId => Some(WarningType::MissingDistinctId),
+ CaptureError::MissingSessionId => Some(WarningType::MissingSessionId),
+ CaptureError::InvalidSessionId => Some(WarningType::InvalidSessionId),
+ CaptureError::MissingSnapshotData => Some(WarningType::MissingSnapshotData),
+ // Only the Kafka sink raises EventTooBig once processing has started. The
+ // transport-level size limits raise it too, but they fire while
+ // decompressing the body, before a verified token exists, so they never
+ // reach the abort path. `setup.rs` caps the decompressed payload at the
+ // producer's own message limit for this capture mode, which keeps the
+ // sink raise rare: it needs the re-serialized envelope to outgrow the
+ // payload it came from, or a broker limit below the producer's.
+ CaptureError::EventTooBig(_) => Some(WarningType::MessageSizeTooLarge),
+
+ // Transport and parse failures surface before a verified token exists,
+ // so there is no team to attribute a warning to.
+ CaptureError::RequestDecodingError(_)
+ | CaptureError::RequestParsingError(_)
+ | CaptureError::RequestHydrationError(_)
+ | CaptureError::EmptyBatch
+ | CaptureError::EmptyPayload
+ | CaptureError::EmptyPayloadFiltered => None,
+
+ // Auth failures: the token is missing, ambiguous, or invalid, so any
+ // attribution would be untrustworthy.
+ CaptureError::NoTokenError
+ | CaptureError::MultipleTokensError
+ | CaptureError::TokenValidationError(_) => None,
+
+ // Unreachable on this path rather than excluded by policy.
+ // `extract_is_cookieless_mode` defaults to `Some(false)` instead of
+ // returning `None`, `$window_id` falls back to the session id so
+ // `MissingWindowId` is never constructed, and replay's timestamp parse
+ // reports no failure to map. The analytics-only variants below this
+ // pipeline never sees round out the exhaustive match.
+ CaptureError::InvalidCookielessMode
+ | CaptureError::InvalidTimestamp
+ | CaptureError::MissingWindowId
+ | CaptureError::MissingEventName => None,
+
+ // Quota, rate, and ops-imposed drops are surfaced through billing and
+ // ops channels, not the warnings UI.
+ CaptureError::BillingLimit
+ | CaptureError::RateLimited
+ | CaptureError::GlobalRateLimitExceeded() => None,
+
+ // Sink and server failures are ours to fix, not the customer's.
+ CaptureError::RetryableSinkError
+ | CaptureError::NonRetryableSinkError
+ | CaptureError::ServiceUnavailable(_)
+ | CaptureError::BodyReadTimeout
+ | CaptureError::InternalError(_) => None,
+ }
+}
+
+/// Emit the ingestion warning for a replay-path `process_replay_events` abort,
+/// if the error maps to one.
+///
+/// The pipeline rejects the whole request on the first invalid event and would
+/// have produced a single message for the batch, so `count` charges the full
+/// batch, matching what `report_dropped_events` records for the same failure;
+/// it's floored at 1 because a zero would read as "nothing happened" in the v2
+/// table. `EventTooBig` is the exception: the sink raises it for the one message
+/// it tried to produce, so charging the batch would overstate a single failure.
+///
+/// `reason` carries the specific condition behind a variant that covers several.
+/// The offending `$session_id` itself is deliberately left out: it is
+/// unvalidated client input landing in a customer-visible column, and the reason
+/// plus `sessionIdLength` already say what has to change.
+pub fn emit_replay_abort_warning(
+ emitter: Option<&dyn WarningEmitter>,
+ context: &ProcessingContext,
+ err: &CaptureError,
+ reason: Option<ReplayRejectionReason>,
+ session_id_chars: Option<usize>,
+ event_count: u64,
+) {
+ let Some(warning) = warning_for_capture_error(err) else {
+ return;
+ };
+
+ let mut details = Map::new();
+ if let Some(reason) = reason {
+ details.insert("reason".to_string(), json!(reason.as_str()));
+ }
+ if let Some(chars) = session_id_chars {
+ details.insert("sessionIdLength".to_string(), json!(chars));
+ }
+ details.insert("eventCount".to_string(), json!(event_count));
+
+ let count = match err {
+ CaptureError::EventTooBig(_) => 1,
+ _ => event_count.max(1),
+ };
+
+ emit_request_warning(
+ emitter,
+ &request_context(context),
+ CAPTURE_REPLAY,
+ warning,
+ details,
+ count,
+ );
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::config::CaptureMode;
+ use crate::ingestion_warnings::{SdkAttribution, MAX_SDK_ATTRIBUTION_LEN};
+ use common_ingestion_warnings::test_support::CollectingEmitter;
+ use common_ingestion_warnings::UNKNOWN_ATTRIBUTION;
+ use rstest::rstest;
+
+ fn replay_context(attribution: SdkAttribution) -> ProcessingContext {
+ ProcessingContext {
+ user_agent: None,
+ sent_at: None,
+ token: "tok".to_string(),
+ now: chrono::Utc::now(),
+ client_ip: "127.0.0.1".to_string(),
+ request_id: "req".to_string(),
+ path: "/s".to_string(),
+ is_mirror_deploy: false,
+ historical_migration: false,
+ chatty_debug_enabled: false,
+ capture_mode: CaptureMode::Recordings,
+ sdk_attribution: attribution,
+ }
+ }
+
+ // Pins which conditions are the customer's to fix versus ours. The match is
+ // exhaustive with no catch-all, so a new variant won't compile until someone
+ // decides; this table is what pins the decision itself.
+ #[rstest]
+ #[case::missing_distinct_id(
+ CaptureError::MissingDistinctId,
+ Some(WarningType::MissingDistinctId)
+ )]
+ #[case::missing_session_id(CaptureError::MissingSessionId, Some(WarningType::MissingSessionId))]
+ #[case::invalid_session_id(CaptureError::InvalidSessionId, Some(WarningType::InvalidSessionId))]
+ #[case::missing_snapshot_data(
+ CaptureError::MissingSnapshotData,
+ Some(WarningType::MissingSnapshotData)
+ )]
+ #[case::oversize(
+ CaptureError::EventTooBig("too big".to_string()),
+ Some(WarningType::MessageSizeTooLarge)
+ )]
+ #[case::parse(CaptureError::RequestParsingError("bad json".to_string()), None)]
+ #[case::decode(CaptureError::RequestDecodingError("bad gzip".to_string()), None)]
+ #[case::empty_batch(CaptureError::EmptyBatch, None)]
+ #[case::empty_payload(CaptureError::EmptyPayload, None)]
+ #[case::no_token(CaptureError::NoTokenError, None)]
+ #[case::billing(CaptureError::BillingLimit, None)]
+ #[case::rate_limited(CaptureError::RateLimited, None)]
+ #[case::unreachable_cookieless(CaptureError::InvalidCookielessMode, None)]
+ #[case::unreachable_window_id(CaptureError::MissingWindowId, None)]
+ #[case::unreachable_timestamp(CaptureError::InvalidTimestamp, None)]
+ #[case::retryable_sink(CaptureError::RetryableSinkError, None)]
+ #[case::non_retryable_sink(CaptureError::NonRetryableSinkError, None)]
+ #[case::body_timeout(CaptureError::BodyReadTimeout, None)]
+ #[case::internal(CaptureError::InternalError("boom".to_string()), None)]
+ fn abort_warnings_map_only_customer_actionable_errors(
+ #[case] err: CaptureError,
+ #[case] expected: Option<WarningType>,
+ ) {
+ assert_eq!(warning_for_capture_error(&err), expected);
+ }
+
+ // Guards the trust chain end to end. A type this mapper emits that is not
+ // capture-produced would be demoted to a generic client warning by the nodejs
+ // consumer, and one also reachable via `from_tag` would violate the common
+ // crate's one-route invariant. Both fail silently in production.
+ #[test]
+ fn emitted_warnings_are_trusted_and_single_routed() {
+ let mapping_errors = [
+ CaptureError::MissingDistinctId,
+ CaptureError::MissingSessionId,
+ CaptureError::InvalidSessionId,
+ CaptureError::MissingSnapshotData,
+ CaptureError::EventTooBig("too big".to_string()),
+ ];
+ let mapped = mapping_errors.iter().filter_map(warning_for_capture_error);
+
+ for warning in mapped {
+ assert!(
+ warning.capture_produced(),
+ "{warning:?} is not on the consumer trust allowlist"
+ );
+ }
+
+ // The replay-only types must stay off the tag route; the two shared with
+ // analytics stay on it. Either way, exactly one route per type.
+ for warning in [
+ WarningType::MissingSessionId,
+ WarningType::InvalidSessionId,
+ WarningType::MissingSnapshotData,
+ ] {
+ assert!(
+ WarningType::DIRECT_EMIT.contains(&warning),
+ "{warning:?} must be direct-emit"
+ );
+ assert_eq!(
+ WarningType::from_tag(warning.as_str()),
+ None,
+ "{warning:?} must not also be tag-routed"
+ );
+ }
+ }
+
+ #[rstest]
+ #[case::not_a_string(SessionIdRejection::NotAString, "not_a_string")]
+ #[case::too_long(SessionIdRejection::TooLong, "too_long")]
+ #[case::invalid_charset(SessionIdRejection::InvalidCharset, "invalid_charset")]
+ fn session_id_rejection_reasons_are_a_closed_vocabulary(
+ #[case] reason: SessionIdRejection,
+ #[case] expected: &str,
+ ) {
+ assert_eq!(reason.as_str(), expected);
+ }
+
+ #[rstest]
+ #[case::absent(SnapshotDataRejection::Absent, "absent")]
+ #[case::wrong_json_type(SnapshotDataRejection::WrongJsonType, "wrong_json_type")]
+ fn snapshot_data_rejection_reasons_are_a_closed_vocabulary(
+ #[case] reason: SnapshotDataRejection,
+ #[case] expected: &str,
+ ) {
+ assert_eq!(reason.as_str(), expected);
+ }
+
+ // The details are the customer-visible payload, and the offending session id
+ // must never be among them.
+ #[test]
+ fn invalid_session_id_reports_the_reason_and_length_but_not_the_value() {
+ let emitter = CollectingEmitter::default();
+ let context = replay_context(SdkAttribution {
+ lib: Some("web".to_string()),
+ lib_version: Some("1.2.3".to_string()),
+ });
+
+ emit_replay_abort_warning(
+ Some(&emitter),
+ &context,
+ &CaptureError::InvalidSessionId,
+ Some(ReplayRejectionReason::InvalidSessionId(
+ SessionIdRejection::InvalidCharset,
+ )),
+ Some(71),
+ 4,
+ );
+
+ let emitted = emitter.emitted();
+ assert_eq!(emitted.len(), 1);
+ let warning = &emitted[0];
+ assert_eq!(warning.warning, WarningType::InvalidSessionId);
+ assert_eq!(warning.count, 4);
+ assert_eq!(warning.extra_details["reason"], json!("invalid_charset"));
+ assert_eq!(warning.extra_details["sessionIdLength"], json!(71));
+ assert_eq!(warning.extra_details["eventCount"], json!(4));
+ assert_eq!(warning.extra_details["lib"], json!("web"));
+ assert_eq!(warning.extra_details["libVersion"], json!("1.2.3"));
+ assert_eq!(warning.extra_details["path"], json!("/s"));
+ assert!(
+ !warning.extra_details.contains_key("sessionId"),
+ "the offending session id must not ride into a customer-visible column"
+ );
+ }
+
+ // A validation abort drops every event in the batch; the sink's oversize
+ // rejection is one message. Charging the batch for the latter would report a
+ // single failure as many.
+ #[rstest]
+ #[case::validation_charges_the_batch(CaptureError::MissingSessionId, 7, 7)]
+ #[case::validation_floors_at_one(CaptureError::MissingSnapshotData, 0, 1)]
+ #[case::oversize_charges_one(CaptureError::EventTooBig("too big".to_string()), 7, 1)]
+ fn abort_counts_match_what_was_dropped(
+ #[case] err: CaptureError,
+ #[case] event_count: u64,
+ #[case] expected_count: u64,
+ ) {
+ let emitter = CollectingEmitter::default();
+
+ emit_replay_abort_warning(
+ Some(&emitter),
+ &replay_context(SdkAttribution::default()),
+ &err,
+ None,
+ None,
+ event_count,
+ );
+
+ let emitted = emitter.emitted();
+ assert_eq!(emitted.len(), 1);
+ assert_eq!(emitted[0].count, expected_count);
+ }
+
+ #[test]
+ fn unmapped_errors_emit_nothing() {
+ let emitter = CollectingEmitter::default();
+
+ emit_replay_abort_warning(
+ Some(&emitter),
+ &replay_context(SdkAttribution::default()),
+ &CaptureError::RetryableSinkError,
+ None,
+ None,
+ 3,
+ );
+
+ assert!(emitter.emitted().is_empty());
+ }
+
+ #[test]
+ fn no_emitter_is_a_silent_no_op() {
+ emit_replay_abort_warning(
+ None,
+ &replay_context(SdkAttribution::default()),
+ &CaptureError::MissingSessionId,
+ None,
+ None,
+ 3,
+ );
+ }
+
+ // Each of these is a payload capture accepts today, so each must produce a
+ // stampable context rather than a missing key.
+ #[rstest]
+ #[case::nothing_reported(None, None, UNKNOWN_ATTRIBUTION, UNKNOWN_ATTRIBUTION)]
+ #[case::lib_without_version(Some("web"), None, "web", UNKNOWN_ATTRIBUTION)]
+ #[case::both(Some("posthog-ios"), Some("3.1.0"), "posthog-ios", "3.1.0")]
+ #[case::empty_lib(Some(""), Some(""), UNKNOWN_ATTRIBUTION, UNKNOWN_ATTRIBUTION)]
+ fn attribution_falls_back_to_unknown_when_unusable(
+ #[case] lib: Option<&str>,
+ #[case] lib_version: Option<&str>,
+ #[case] expected_lib: &str,
+ #[case] expected_lib_version: &str,
+ ) {
+ let context = replay_context(SdkAttribution {
+ lib: lib.map(str::to_string),
+ lib_version: lib_version.map(str::to_string),
+ });
+
+ let projected = request_context(&context);
+ assert_eq!(projected.lib, expected_lib);
+ assert_eq!(projected.lib_version, expected_lib_version);
+ assert_eq!(projected.token, "tok");
+ assert_eq!(projected.path, "/s");
+ }
+
+ // Oversized values are dropped rather than truncated, so they land on the
+ // unknown fallback instead of riding into every warning for the request.
+ #[test]
+ fn oversized_attribution_is_dropped_at_projection() {
+ let over_bound = "w".repeat(MAX_SDK_ATTRIBUTION_LEN + 1);
+ let at_bound = "w".repeat(MAX_SDK_ATTRIBUTION_LEN);
+
+ let projected = request_context(&replay_context(SdkAttribution {
+ lib: within_bound(over_bound),
+ lib_version: within_bound(at_bound.clone()),
+ }));
+
+ assert_eq!(projected.lib, UNKNOWN_ATTRIBUTION);
+ assert_eq!(projected.lib_version, at_bound);
+ }
+
+ fn recording(properties: serde_json::Value) -> RawRecording {
+ serde_json::from_value(json!({"event": "$snapshot", "properties": properties})).unwrap()
+ }
+
+ // Each case is a payload real SDKs send. The `$lib`-absent rows are the ones
+ // that matter: replay has no `PostHog-Sdk-Info` header, so the user agent is
+ // the only remaining signal, and it must resolve the same way the ingested
+ // recording's own `$lib` does.
+ #[rstest]
+ #[case::lib_and_version(
+ json!({"$lib": "web", "$lib_version": "1.2.3"}),
+ "posthog-js/1.2.3",
+ Some("web"),
+ Some("1.2.3")
+ )]
+ #[case::lib_without_version(json!({"$lib": "posthog-ios"}), "whatever", Some("posthog-ios"), None)]
+ #[case::posthog_user_agent_fallback(json!({}), "posthog-python/3.0.1", Some("posthog-python"), None)]
+ #[case::browser_user_agent_falls_back_to_web(json!({}), "Mozilla/5.0", Some("web"), None)]
+ #[case::version_without_lib_still_reports_version(
+ json!({"$lib_version": "9.9.9"}),
+ "posthog-node/9.9.9",
+ Some("posthog-node"),
+ Some("9.9.9")
+ )]
+ fn attribution_reads_the_snapshot_envelope_then_the_user_agent(
+ #[case] properties: serde_json::Value,
+ #[case] user_agent: &str,
+ #[case] expected_lib: Option<&str>,
+ #[case] expected_version: Option<&str>,
+ ) {
+ let attribution = attribution_from_event(&recording(properties), user_agent);
+
+ assert_eq!(attribution.lib.as_deref(), expected_lib);
+ assert_eq!(attribution.lib_version.as_deref(), expected_version);
+ }
+
+ // Oversized client input is dropped at extraction so it never reaches the
+ // context, matching what the analytics path does with the same values.
+ #[test]
+ fn oversized_snapshot_attribution_is_dropped_at_extraction() {
+ let over_bound = "w".repeat(MAX_SDK_ATTRIBUTION_LEN + 1);
+
+ let attribution = attribution_from_event(
+ &recording(json!({"$lib": over_bound, "$lib_version": over_bound})),
+ "posthog-js/1.0.0",
+ );
+
+ assert_eq!(attribution.lib, None);
+ assert_eq!(attribution.lib_version, None);
+ }
+}
diff --git a/rust/capture/src/payload/recordings.rs b/rust/capture/src/payload/recordings.rs
index b1b8d7cdf8e6..3457a5617332 100644
--- a/rust/capture/src/payload/recordings.rs
+++ b/rust/capture/src/payload/recordings.rs
@@ -16,7 +16,7 @@ use crate::{
debug_or_info,
events::recordings::RawRecording,
extractors::extract_body_with_timeout,
- ingestion_warnings::SdkAttribution,
+ ingestion_warnings::replay::attribution_from_event,
payload::{decompress_payload, extract_and_record_metadata, extract_payload_bytes, EventQuery},
router,
token::validate_token,
@@ -128,10 +128,7 @@ pub async fn handle_recording_payload(
user_agent: Some(metadata.user_agent.to_string()),
chatty_debug_enabled,
capture_mode: state.capture_mode,
- // Replay emits no ingestion warnings yet. Snapshot events report `$lib`
- // in their own envelope shape, so wiring this up is a real conversion,
- // not a field copy — left for whoever adds replay warnings.
- sdk_attribution: SdkAttribution::default(),
+ sdk_attribution: attribution_from_event(&events[0], metadata.user_agent),
};
// Apply all billing limit quotas and drop partial or whole
diff --git a/rust/capture/src/v0_endpoint.rs b/rust/capture/src/v0_endpoint.rs
index 5d0b09643a98..e7252ec145bf 100644
--- a/rust/capture/src/v0_endpoint.rs
+++ b/rust/capture/src/v0_endpoint.rs
@@ -133,6 +133,7 @@ pub async fn recording(
state.sink.clone(),
state.event_restriction_service.clone(),
state.replay_overflow_limiter.clone(),
+ state.ingestion_warning_emitter.clone(),
events,
&context,
)
diff --git a/rust/capture/tests/common/utils.rs b/rust/capture/tests/common/utils.rs
index 73d63b6269f5..0e1000be618d 100644
--- a/rust/capture/tests/common/utils.rs
+++ b/rust/capture/tests/common/utils.rs
@@ -254,6 +254,24 @@ impl ServerHandle {
Self::for_config(config).await
}
+ /// Like `for_recordings`, with the synthetic ingestion warnings emitter
+ /// enabled and pointed at its own topic via the emitter's dedicated config,
+ /// so replay warning envelopes are readable independently of the events that
+ /// triggered them.
+ pub async fn for_recordings_with_warnings(
+ main: &EphemeralTopic,
+ warnings_topic: &EphemeralTopic,
+ ) -> Self {
+ let mut config = DEFAULT_CONFIG.clone();
+ config.kafka.kafka_topic = main.topic_name().to_string();
+ config.capture_mode = CaptureMode::Recordings;
+ config.capture_ingestion_warnings_enabled = true;
+ config.capture_ingestion_warnings_kafka_hosts = config.kafka.kafka_hosts.clone();
+ config.capture_ingestion_warnings_kafka_tls = config.kafka.kafka_tls;
+ config.capture_ingestion_warnings_kafka_topic = warnings_topic.topic_name().to_string();
+ Self::for_config(config).await
+ }
+
/// Boots a server with the v1 analytics pipeline enabled: a single `msk`
/// sink whose topics all point at `topic`, injected via a deterministic env
/// snapshot (no global `std::env` mutation, so parallel tests don't race on
diff --git a/rust/capture/tests/ingestion_warnings_integration.rs b/rust/capture/tests/ingestion_warnings_integration.rs
index 2ab80cf61494..feedee52294d 100644
--- a/rust/capture/tests/ingestion_warnings_integration.rs
+++ b/rust/capture/tests/ingestion_warnings_integration.rs
@@ -82,6 +82,71 @@ async fn v1_validation_drop_emits_warning_envelope_to_kafka() -> Result<()> {
Ok(())
}
+/// The replay path's own leg. Beyond the emitter wiring the tests above cover,
+/// this is the only thing that exercises two replay-specific pieces end to end:
+/// `v0_endpoint::recording` handing the emitter to the pipeline, and
+/// `handle_recording_payload` projecting `$lib`/`$lib_version` out of the
+/// snapshot envelope. A regression in either leaves the warning correct in unit
+/// tests but absent, or attributed to `unknown`, in production.
+#[tokio::test]
+async fn replay_validation_abort_emits_warning_envelope_to_kafka() -> Result<()> {
+ setup_tracing();
+ let token = random_string("phc_replay_warn", 16);
+ let events_topic = EphemeralTopic::new().await;
+ let warnings_topic = EphemeralTopic::new().await;
+ let server = ServerHandle::for_recordings_with_warnings(&events_topic, &warnings_topic).await;
+
+ // Two events so the batch count is distinguishable from a per-event charge,
+ // and a `$session_id` that trips the charset rule rather than the length one.
+ let properties = json!({
+ "$session_id": "not a valid session id",
+ "$snapshot_data": [{"type": 1}],
+ "$lib": "web",
+ "$lib_version": "1.200.0",
+ });
+ let payload = json!([
+ {"event": "$snapshot", "api_key": token, "distinct_id": "u1", "properties": properties},
+ {"event": "$snapshot", "api_key": token, "distinct_id": "u1", "properties": properties},
+ ]);
+ let res = server.capture_recording(payload.to_string(), None).await;
+ assert_eq!(
+ res.status(),
+ reqwest::StatusCode::BAD_REQUEST,
+ "an invalid session id rejects the whole replay request"
+ );
+
+ let envelope: CapturedEvent = serde_json::from_value(warnings_topic.next_event()?)?;
+ assert_eq!(envelope.event, "$$client_ingestion_warning");
+ assert_eq!(envelope.token, token);
+ assert_eq!(
+ envelope.distinct_id, token,
+ "distinct_id must be the token, never a caller-supplied value"
+ );
+
+ let inner: Value = serde_json::from_str(&envelope.data)?;
+ assert_eq!(
+ inner["properties"],
+ json!({
+ "$$client_ingestion_warning_type": "invalid_session_id",
+ "$$client_ingestion_warning_source": "capture",
+ "$$client_ingestion_warning_details": {
+ "count": 2,
+ "eventCount": 2,
+ "reason": "invalid_charset",
+ "sessionIdLength": 22,
+ "lib": "web",
+ "libVersion": "1.200.0",
+ "path": "/s/",
+ "pipelineStep": "capture_validation",
+ },
+ })
+ );
+
+ events_topic.assert_empty();
+ warnings_topic.assert_empty();
+ Ok(())
+}
+
#[tokio::test]
async fn legacy_processing_abort_emits_warning_envelope_to_kafka() -> Result<()> {
setup_tracing();
diff --git a/rust/common/ingestion_warnings/src/lib.rs b/rust/common/ingestion_warnings/src/lib.rs
index 3d6642390514..9ea8f499e9c5 100644
--- a/rust/common/ingestion_warnings/src/lib.rs
+++ b/rust/common/ingestion_warnings/src/lib.rs
@@ -184,6 +184,19 @@ pub const CAPTURE_AI_OTEL: WarningSource = WarningSource {
pipeline_step: "capture_validation",
};
+/// Capture's session replay endpoint (`rust/capture/src/events/recordings.rs`,
+/// `/s`). Like `CAPTURE_LEGACY_ANALYTICS`, a validation failure aborts the whole
+/// request, so warnings charge the batch's event count; unlike it, the batch was
+/// on its way to becoming a single `$snapshot_items` message, so "the batch" and
+/// "the message" are the same thing here. One source rather than a validation /
+/// rate-limit pair because `CaptureMode::Recordings` registers no other route and
+/// runs no per-distinct_id limiter.
+pub const CAPTURE_REPLAY: WarningSource = WarningSource {
+ service: serializer::SOURCE_CAPTURE,
+ path: "replay",
+ pipeline_step: "capture_validation",
+};
+
/// Sink-agnostic emitter seam. The Kafka implementation is
/// [`KafkaWarningEmitter`]; tests use
/// [`test_support::CollectingEmitter`].
diff --git a/rust/common/ingestion_warnings/src/registry.rs b/rust/common/ingestion_warnings/src/registry.rs
index 6afd5e060779..023df533336b 100644
--- a/rust/common/ingestion_warnings/src/registry.rs
+++ b/rust/common/ingestion_warnings/src/registry.rs
@@ -35,19 +35,24 @@ impl WarningType {
/// would mean inventing an error that never gets returned.
/// * Ones from a pipeline that has no tag vocabulary. The AI endpoints
/// reject via their own typed conditions, not `v1::Error`, so their tags
- /// would be strings no `Error` ever produces.
+ /// would be strings no `Error` ever produces. The replay endpoint is the
+ /// same case from the other direction: its conditions are `CaptureError`
+ /// variants v1 analytics never returns, so no `Error::tag()` names them.
///
/// Emit sites for these name the variant directly.
///
/// This list exists so the trust-allowlist invariant below can still be
/// airtight: `captureProduced` must equal "reachable by one of capture's two
/// emit routes", and without this the direct route would be invisible to it.
- pub const DIRECT_EMIT: [Self; 5] = [
+ pub const DIRECT_EMIT: [Self; 8] = [
Self::HighVolumeDistinctId,
Self::DistinctIdTruncated,
Self::InvalidAiEvent,
Self::InvalidAiPayload,
Self::NoAiSpansIngested,
+ Self::MissingSessionId,
+ Self::InvalidSessionId,
+ Self::MissingSnapshotData,
];
/// Map a capture error tag (`v1::Error::tag()` / per-event drop detail) to a
diff --git a/rust/common/ingestion_warnings/warning_types.generated.json b/rust/common/ingestion_warnings/warning_types.generated.json
index 9c9497f18627..ce5482ad312b 100644
--- a/rust/common/ingestion_warnings/warning_types.generated.json
+++ b/rust/common/ingestion_warnings/warning_types.generated.json
@@ -187,6 +187,12 @@
"severity": "warning",
"captureProduced": false
},
+ {
+ "type": "invalid_session_id",
+ "category": "replay",
+ "severity": "error",
+ "captureProduced": true
+ },
{
"type": "malformed_event_properties",
"category": "event",
@@ -235,6 +241,18 @@
"severity": "error",
"captureProduced": true
},
+ {
+ "type": "missing_session_id",
+ "category": "replay",
+ "severity": "error",
+ "captureProduced": true
+ },
+ {
+ "type": "missing_snapshot_data",
+ "category": "replay",
+ "severity": "error",
+ "captureProduced": true
+ },
{
"type": "no_ai_spans_ingested",
"category": "event",