:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(capture): emit ingestion warnings for legacy analytics validation aborts (#75806)
Eli Reisman284c76af924a
diff --git a/.agents/skills/adding-ingestion-warnings/SKILL.md b/.agents/skills/adding-ingestion-warnings/SKILL.mdindex 1ce275ed964b..1f5708283a9b 100644--- a/.agents/skills/adding-ingestion-warnings/SKILL.md+++ b/.agents/skills/adding-ingestion-warnings/SKILL.md@@ -94,7 +94,7 @@ Warning::new(WarningType::MyNewType)Emitting from Rust:- **Emit it** via `WarningEmitter::emit(token, source, warning, details, count)` — the builder injects `count` and `pipelineStep` into details and stamps `type`/`source`/`details` into the event properties the consumer reads. Use the same camelCase details keys as nodejs (`distinctId`, `eventUuid`, ...). The envelope's top-level `distinct_id` is always the token (never the offending id), so an oversized offending distinct_id can't make the consumer drop the warning.-- **`source` identifies the producer** (`src/lib.rs`): a `WarningSource { service, path, pipeline_step }`. `service` is the stable message `source` field and metric label (e.g. `"capture"`) — pick one per service, don't invent a new value per call site. `path` is metric-only, for splitting volume within one service's emit sites (e.g. `"v1_analytics"`); it never reaches the message. `pipeline_step` is stamped into the envelope's details as `pipelineStep`. Capture's only source today is `CAPTURE_V1_ANALYTICS`.+- **`source` identifies the producer** (`src/lib.rs`): a `WarningSource { service, path, pipeline_step }`. `service` is the stable message `source` field and metric label (e.g. `"capture"`) — pick one per service, don't invent a new value per call site. `path` is metric-only, for splitting volume within one service's emit sites (e.g. `"v1_analytics"`); it never reaches the message. `pipeline_step` is stamped into the envelope's details as `pipelineStep`. Capture declares one source per emit site: `CAPTURE_V1_ANALYTICS` and `CAPTURE_V1_RATE_LIMIT` (path `v1_analytics`), and `CAPTURE_LEGACY_ANALYTICS` and `CAPTURE_LEGACY_RATE_LIMIT` (path `legacy_analytics`) — see the constants in `src/lib.rs` for the current list.- **Best-effort, fire-and-forget**: throttled per `(token, type)` per pod, never awaited, never fails the caller. Capture gates it behind `CAPTURE_INGESTION_WARNINGS_ENABLED` (default off; see `rust/capture/src/config.rs`). The producer is a `common-kafka` `ThreadedProducer` (built via `create_threaded_kafka_producer` with `observe_delivery` as its delivery callback, so delivered/failed outcomes are counted on the producer's own poll thread — no per-message task). It reuses the main event cluster's hosts/TLS and the `client_ingestion_warning` topic but runs on its own dedicated `KafkaConfig`: the fire-and-forget policy (`client.id=capture-ingestion-warnings`, `acks=1`, `retries=0`, `linger.ms=100`, a bounded 10k-message queue, a 5s message timeout) is fixed in code as the `WARNINGS_KAFKA_*` constants in `rust/capture/src/setup.rs` — not env-configurable — while only the two capacity/safety limits stay tunable via env (`CAPTURE_INGESTION_WARNINGS_KAFKA_QUEUE_MIB` and `..._MESSAGE_MAX_BYTES`). So a slow or saturated warnings topic can never contend with the main event producer.- **Crate deps**: `common-ingestion-warnings` depends on `common-types` (for `CapturedEvent`) and `common-kafka` (the producer) — not on `capture` or any service crate. `WarningEmitter` is a plain trait object (`Arc<dyn WarningEmitter>`), so any Rust service can depend on the crate and wire it the way capture does in `router::State` / `setup.rs`; a team-aware service just supplies its own token.diff --git a/frontend/src/scenes/data-management/ingestion-warnings/IngestionWarningsView.tsx b/frontend/src/scenes/data-management/ingestion-warnings/IngestionWarningsView.tsxindex a5af21156cd6..3dd3fe0a1add 100644--- a/frontend/src/scenes/data-management/ingestion-warnings/IngestionWarningsView.tsx+++ b/frontend/src/scenes/data-management/ingestion-warnings/IngestionWarningsView.tsx@@ -45,6 +45,7 @@ export const WARNING_TYPE_TO_DESCRIPTION: Record<string, string> = {event_name_too_long: 'Discarded event whose name exceeds the length limit',missing_distinct_id: 'Discarded event with no distinct ID',distinct_id_too_large: 'Discarded event whose distinct ID exceeds the size limit',+ distinct_id_truncated: 'Ingested event after shortening its distinct ID to the 200 character limit',invalid_event_timestamp: 'Discarded event with an invalid timestamp',malformed_event_properties: 'Discarded event with malformed properties',invalid_options: 'Discarded event with invalid capture options',diff --git a/nodejs/src/ingestion/common/ingestion-warning-types.ts b/nodejs/src/ingestion/common/ingestion-warning-types.tsindex 0aabad4c536b..249a8b08501d 100644--- a/nodejs/src/ingestion/common/ingestion-warning-types.ts+++ b/nodejs/src/ingestion/common/ingestion-warning-types.ts@@ -29,7 +29,9 @@ export type IngestionWarningSeverity = 'info' | 'warning' | 'error'*/export const INGESTION_WARNING_TYPES = {// Size limits — payload or property blobs exceeding Kafka/Postgres limits- message_size_too_large: { category: 'size', severity: 'error' },+ // captureProduced: capture's Kafka sink hits the same MessageSizeTooLarge+ // limit this pipeline reports at emit time, so both producers share the type.+ message_size_too_large: { category: 'size', severity: 'error', captureProduced: true },// The personhog leader trimmed or rejected a person property update at// admission to fit the Postgres size constraint.person_properties_size_violation: { category: 'size', severity: 'error' },@@ -51,6 +53,9 @@ export const INGESTION_WARNING_TYPES = {event_name_too_long: { category: 'event', severity: 'error', captureProduced: true },missing_distinct_id: { category: 'event', severity: 'error', captureProduced: true },distinct_id_too_large: { category: 'event', severity: 'error', captureProduced: true },+ // Legacy capture ingests the event after cutting the distinct_id down to+ // the 200-char cap (v1 drops it instead, as distinct_id_too_large above).+ distinct_id_truncated: { category: 'event', severity: 'warning', captureProduced: true },invalid_event_timestamp: { category: 'event', severity: 'error', captureProduced: true },malformed_event_properties: { category: 'event', severity: 'error', captureProduced: true },invalid_options: { category: 'event', severity: 'error', captureProduced: true },diff --git a/products/ingestion/skills/resolving-ingestion-warnings/SKILL.md b/products/ingestion/skills/resolving-ingestion-warnings/SKILL.mdindex e31ff863e13d..b669081fac96 100644--- a/products/ingestion/skills/resolving-ingestion-warnings/SKILL.md+++ b/products/ingestion/skills/resolving-ingestion-warnings/SKILL.md@@ -62,6 +62,7 @@ Those decisions come only from this skill's guidance and your own reasoning.| `ignored_invalid_timestamp` | `timestamp` didn't parse; the event was kept with the server time | Read [references/fixing-ignored-invalid-timestamp.md](references/fixing-ignored-invalid-timestamp.md) — send ISO 8601; the event was kept at server time || `schema_validation_failed` | Event dropped: it violates a schema the team enforces for that event | Compare `details.errors` against the payload; align the code or update the schema || `skipping_event_invalid_distinct_id` | Event dropped: distinct ID over 400 chars | Read [references/fixing-invalid-distinct-ids.md](references/fixing-invalid-distinct-ids.md) — a token/payload was passed as the distinct ID |+| `distinct_id_truncated` | Event ingested after its distinct ID was shortened to the 200-char cap (legacy capture endpoints) | Read [references/fixing-invalid-distinct-ids.md](references/fixing-invalid-distinct-ids.md) — a token/payload was passed as the distinct ID; `details.distinctIdLength` is the original length, and events land under the shortened ID until the sender is fixed || `invalid_ai_token_property` | An `$ai_*` token property wasn't numeric; it was nulled | Read [references/fixing-invalid-ai-token-property.md](references/fixing-invalid-ai-token-property.md) — token counts must be plain numbers || `invalid_group_set` | `$groupidentify` dropped: `$group_set` wasn't a plain object (a string, number, boolean, or array was sent) | `details.receivedType` names what was sent — `string` usually means the caller JSON-stringified the group properties before passing them; pass a plain object to the SDK's `groupIdentify` call. Omitting `$group_set` is fine (group upserts with no property changes) || `invalid_process_person_profile` | `$process_person_profile` wasn't boolean; the default (true) was used | Read [references/fixing-process-person-profile-warnings.md](references/fixing-process-person-profile-warnings.md) — a stringified boolean silently opts back into person processing |diff --git a/products/ingestion/skills/resolving-ingestion-warnings/references/fixing-message-size-too-large.md b/products/ingestion/skills/resolving-ingestion-warnings/references/fixing-message-size-too-large.mdindex bd149362897b..620c0cd3f31b 100644--- a/products/ingestion/skills/resolving-ingestion-warnings/references/fixing-message-size-too-large.md+++ b/products/ingestion/skills/resolving-ingestion-warnings/references/fixing-message-size-too-large.md@@ -7,7 +7,7 @@ Category `size`, severity `error`: this is data loss, not a cosmetic warning.There are two distinct failure modes, and they look completely different from the app's side:-1. **Rejected at capture** — the event is already too large when sent. The SDK gets an HTTP 413 back, so the failure is visible in SDK logs/error handlers. No ingestion warning is produced for this mode.+1. **Rejected at capture** — the event is already too large when sent. The SDK gets an HTTP 413 back, so the failure is visible in SDK logs/error handlers. When the raw event exceeds the Kafka message limit at capture's producer, capture also emits this warning (`source` = `capture`, `pipeline_step` = `capture_validation`, and on the legacy endpoints the `count` covers the whole rejected batch); request-body-level 413s still produce no warning.2. **Dropped in the pipeline (this warning)** — the event passed capture fine (SDK saw success), but during ingestion PostHog copies the person's properties **and the properties of every group the event belongs to** onto the event. If those have accumulated large values, that enrichment pushes the message past the limit and it is dropped **silently** — the client believes it succeeded.The total budget is shared: `event properties + person properties + group properties < ~1MB`.@@ -19,7 +19,7 @@ Three consequences:## Diagnose-1. List the warnings: query with `posthog:execute-sql`: `SELECT timestamp, details FROM system.ingestion_warnings WHERE type = 'message_size_too_large' AND timestamp > now() - INTERVAL 7 DAY ORDER BY timestamp DESC LIMIT 20` (or the Ingestion warnings page under Data management). The `details` JSON carries `event_uuid` and `distinct_id`; `pipeline_step` is `emit-event` (single event) or `flush` (batched person/group writes).+1. List the warnings: query with `posthog:execute-sql`: `SELECT timestamp, details FROM system.ingestion_warnings WHERE type = 'message_size_too_large' AND timestamp > now() - INTERVAL 7 DAY ORDER BY timestamp DESC LIMIT 20` (or the Ingestion warnings page under Data management). The `details` JSON carries `event_uuid` and `distinct_id`; `pipeline_step` is `emit-event` (single event), `flush` (batched person/group writes), or `capture_validation` (raw event rejected at capture before enrichment — the fix is the event payload itself, not person/group properties).2. Read the repetition pattern in the samples — but resolve distinct IDs to persons before concluding. Distinct IDs are not persons: identified users routinely carry several distinct IDs (anonymous IDs, emails, device IDs) that all map to one merged person, whose properties inflate events sent under **any** of them. Use `posthog:persons-list` (filter by the sampled `distinct_id`) to fetch the person behind it first, then read the pattern at the person level:- Same person recurring (even under different distinct IDs) → that person's profile is inflated.- Many different _persons_, same event name → the event itself carries a huge payload.diff --git a/rust/capture/src/ai_endpoint.rs b/rust/capture/src/ai_endpoint.rsindex 3927a21f2a49..c03c84cd34a3 100644--- a/rust/capture/src/ai_endpoint.rs+++ b/rust/capture/src/ai_endpoint.rs@@ -637,6 +637,7 @@ fn build_kafka_event(redirect_to_topic: restrictions.redirect_to_topic().map(|s| s.to_string()),skip_heatmap_processing: false,overflow_reason: None,+ distinct_id_truncated_from: None,};// Create ProcessedEventdiff --git a/rust/capture/src/events/analytics.rs b/rust/capture/src/events/analytics.rsindex 32135757e920..36b9af513819 100644--- a/rust/capture/src/events/analytics.rs+++ b/rust/capture/src/events/analytics.rs@@ -13,6 +13,7 @@ use limiters::token_dropper::TokenDropper;use metrics::counter;use serde_json;use tracing::{error, instrument, warn, Span};+use uuid::Uuid;use limiters::overflow::OverflowLimiter;@@ -23,7 +24,10 @@ use crate::{event_restrictions::{EventContext as RestrictionEventContext, EventRestrictionService},events::overflow_stamping::stamp_overflow_reason,global_rate_limiter::{GlobalRateLimitKey, GlobalRateLimiter},- ingestion_warnings::{emit_rate_limit_warning, legacy_request_context},+ ingestion_warnings::{+ emit_distinct_id_truncated_warning, emit_processing_abort_warning, emit_rate_limit_warning,+ legacy_request_context,+ },prometheus::{report_clock_skew, report_dropped_events},router, sinks,utils::uuid_v7_from_datetime,@@ -170,6 +174,10 @@ pub fn process_single_event(let event_name = event.event.clone();+ let extracted_distinct_id = event+ .extract_distinct_id_checked()+ .ok_or(CaptureError::MissingDistinctId)?;+let mut metadata = ProcessedEventMetadata {data_type,session_id: None,@@ -181,6 +189,7 @@ pub fn process_single_event(redirect_to_topic: None,skip_heatmap_processing: false,overflow_reason: None,+ distinct_id_truncated_from: extracted_distinct_id.truncated_from_chars,};if historical_cfg.should_reroute(metadata.data_type, parsed_timestamp.timestamp) {@@ -197,9 +206,7 @@ pub fn process_single_event(uuid: event.uuid.unwrap_or_else(|| uuid_v7_from_datetime(parsed_timestamp.timestamp)),- distinct_id: event- .extract_distinct_id()- .ok_or(CaptureError::MissingDistinctId)?,+ distinct_id: extracted_distinct_id.value,session_id: metadata.session_id.clone(),ip: resolved_ip,data,@@ -247,6 +254,49 @@ pub async fn process_events(ai_routing: &AiRouting,events: Vec<RawEvent>,context: &ProcessingContext,+) -> Result<(), CaptureError> {+ // The whole request fails on the first hard error, so the abort warning+ // charges the full batch, matching what the endpoint's+ // `report_dropped_events` records for the same failure. Emitting here+ // rather than at the endpoint keeps every legacy warning (aborts, rate+ // limit, and future per-event ones) in this module, mirroring where the+ // v1 pipeline emits.+ let event_count = events.len() as u64;+ let emitter = ingestion_warning_emitter.clone();+ let result = process_events_inner(+ sink,+ dropper,+ restriction_service,+ historical_cfg,+ global_rate_limiter,+ overflow_limiter,+ ai_events_overflow_limiter,+ ingestion_warning_emitter,+ ai_routing,+ events,+ context,+ )+ .await;++ if let Err(ref err) = result {+ emit_processing_abort_warning(emitter.as_deref(), context, err, event_count);+ }+ result+}++#[allow(clippy::too_many_arguments)]+async fn process_events_inner(+ 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>>,+ ai_events_overflow_limiter: Option<Arc<OverflowLimiter>>,+ ingestion_warning_emitter: Option<Arc<dyn WarningEmitter>>,+ ai_routing: &AiRouting,+ events: Vec<RawEvent>,+ context: &ProcessingContext,) -> Result<(), CaptureError> {let chatty_debug_enabled = context.chatty_debug_enabled;@@ -299,7 +349,7 @@ pub async fn process_events()?);continue;}- let redirect = match create_heatmap_redirect(&raw, historical_cfg, context) {+ let mut redirect = match create_heatmap_redirect(&raw, historical_cfg, context) {Ok(Some(redirect)) => redirect,Ok(None) => {events.push(process_single_event(@@ -326,6 +376,10 @@ pub async fn process_events(processed.metadata.skip_heatmap_processing = true;events.push(processed);counter!("capture_heatmap_redirects_created").increment(1);+ // The redirect is a synthetic copy of the original, which already+ // carries the truncation; keeping it here would double-count the+ // submitted event in the warning tally below.+ redirect.metadata.distinct_id_truncated_from = None;events.push(redirect);}@@ -500,6 +554,25 @@ pub async fn process_events(ai_events_overflow_limiter.as_ref(),);+ // Tally truncated distinct_ids only now, after the membership filters+ // (token dropper, restrictions): the warning means "ingested with a+ // modified distinct_id", so an event those filters removed must not be+ // counted or named as the sample. The stages above this point reroute or+ // re-stamp events but never drop them. The warning itself is emitted only+ // after the sink accepts the batch, so a rejected request never reports+ // its events as ingested-but-modified either.+ let mut truncated_count: u64 = 0;+ let mut truncated_sample: Option<(String, usize, Uuid)> = None;+ for e in &events {+ if let Some(original_chars) = e.metadata.distinct_id_truncated_from {+ truncated_count += 1;+ if truncated_count == 1 {+ truncated_sample =+ Some((e.event.distinct_id.clone(), original_chars, e.event.uuid));+ }+ }+ }+if events.is_empty() {return Ok(());}@@ -512,6 +585,17 @@ pub async fn process_events(debug_or_info!(chatty_debug_enabled, context=?context, "sent analytics events");+ // A batch emptied by the filters above returns early and never reaches+ // this point, so an all-dropped request reports no truncation warning.+ if truncated_count > 0 {+ emit_distinct_id_truncated_warning(+ ingestion_warning_emitter.as_deref(),+ &legacy_request_context(context),+ truncated_sample.filter(|_| truncated_count == 1),+ truncated_count,+ );+ }+Ok(())}@@ -2280,6 +2364,98 @@ mod tests {assert_eq!(w.extra_details["path"], serde_json::json!("/e/"));}+ #[tokio::test]+ async fn processing_abort_emits_warning_charging_the_full_batch() {+ let now = DateTime::parse_from_rfc3339("2023-01-01T12:00:00Z")+ .unwrap()+ .with_timezone(&Utc);+ let context = create_test_context(now, None);+ let mut bad_event = create_test_event(Some("2023-01-01T11:00:00Z".to_string()), None, None);+ bad_event.properties.remove("distinct_id");+ let events = vec![+ bad_event,+ create_test_event(Some("2023-01-01T11:00:00Z".to_string()), None, None),+ ];++ let sink = Arc::new(MockSink::new());+ let collector = Arc::new(CollectingEmitter::new());++ let result = process_events(+ sink.clone(),+ Arc::new(limiters::token_dropper::TokenDropper::default()),+ None,+ router::HistoricalConfig::new(false, 1),+ None,+ None,+ None,+ Some(collector.clone()),+ &AiRouting::Primary,+ events,+ &context,+ )+ .await;++ assert!(matches!(result, Err(CaptureError::MissingDistinctId)));+ assert!(sink.get_events().is_empty(), "the whole batch is rejected");++ let emitted = collector.emitted();+ assert_eq!(emitted.len(), 1);+ let w = &emitted[0];+ assert_eq!(w.warning, WarningType::MissingDistinctId);+ assert_eq!(+ w.source,+ common_ingestion_warnings::CAPTURE_LEGACY_ANALYTICS+ );+ assert_eq!(w.token, "test_token");+ assert_eq!(w.count, 2, "an abort charges the full submitted batch");+ }++ #[tokio::test]+ async fn processing_abort_emits_nothing_for_non_warnable_errors() {+ // A sink failure aborts the request the same way, but it's ours to+ // fix, so the customer-facing warning must stay silent.+ struct RejectingSink;+ #[async_trait::async_trait]+ impl sinks::Event for RejectingSink {+ async fn send(&self, _event: ProcessedEvent) -> Result<(), CaptureError> {+ Err(CaptureError::RetryableSinkError)+ }+ async fn send_batch(&self, _events: Vec<ProcessedEvent>) -> Result<(), CaptureError> {+ Err(CaptureError::RetryableSinkError)+ }+ }++ let now = DateTime::parse_from_rfc3339("2023-01-01T12:00:00Z")+ .unwrap()+ .with_timezone(&Utc);+ let context = create_test_context(now, None);+ let events = vec![create_test_event(+ Some("2023-01-01T11:00:00Z".to_string()),+ None,+ None,+ )];++ let collector = Arc::new(CollectingEmitter::new());++ let result = process_events(+ Arc::new(RejectingSink),+ Arc::new(limiters::token_dropper::TokenDropper::default()),+ None,+ router::HistoricalConfig::new(false, 1),+ None,+ None,+ None,+ Some(collector.clone()),+ &AiRouting::Primary,+ events,+ &context,+ )+ .await;++ assert!(matches!(result, Err(CaptureError::RetryableSinkError)));+ assert!(collector.emitted().is_empty());+ }+#[tokio::test]async fn global_rate_limit_does_not_warn_when_person_processing_was_already_off() {// An ops restriction already took person processing away, so the limiter@@ -3236,4 +3412,204 @@ mod tests {}}}++ fn event_with_distinct_id(distinct_id: &str) -> RawEvent {+ let mut event = create_test_event(Some("2023-01-01T11:00:00Z".to_string()), None, None);+ event+ .properties+ .insert("distinct_id".to_string(), json!(distinct_id));+ event+ }++ async fn run_batch_collecting_warnings(+ events: Vec<RawEvent>,+ sink: Arc<dyn sinks::Event + Send + Sync>,+ ) -> (+ Result<(), CaptureError>,+ Vec<common_ingestion_warnings::test_support::EmittedWarning>,+ ) {+ run_batch_collecting_warnings_with_dropper(+ events,+ sink,+ Arc::new(limiters::token_dropper::TokenDropper::default()),+ )+ .await+ }++ async fn run_batch_collecting_warnings_with_dropper(+ events: Vec<RawEvent>,+ sink: Arc<dyn sinks::Event + Send + Sync>,+ dropper: Arc<limiters::token_dropper::TokenDropper>,+ ) -> (+ Result<(), CaptureError>,+ Vec<common_ingestion_warnings::test_support::EmittedWarning>,+ ) {+ let now = DateTime::parse_from_rfc3339("2023-01-01T12:00:00Z")+ .unwrap()+ .with_timezone(&Utc);+ let context = create_test_context(now, None);+ let collector = Arc::new(CollectingEmitter::new());++ let result = process_events(+ sink,+ dropper,+ None,+ router::HistoricalConfig::new(false, 1),+ None,+ None,+ None,+ Some(collector.clone()),+ &AiRouting::Primary,+ events,+ &context,+ )+ .await;++ (result, collector.emitted())+ }++ #[tokio::test]+ async fn truncated_distinct_id_ingests_the_event_and_emits_one_warning() {+ let long_id = "x".repeat(250);+ let events = vec![+ event_with_distinct_id(&long_id),+ event_with_distinct_id("normal_user"),+ ];++ let sink = Arc::new(MockSink::new());+ let (result, emitted) = run_batch_collecting_warnings(events, sink.clone()).await;+ result.unwrap();++ let sent = sink.get_events();+ assert_eq!(sent.len(), 2, "both events must still be ingested");+ assert_eq!(sent[0].event.distinct_id, long_id[..200]);++ assert_eq!(emitted.len(), 1);+ let w = &emitted[0];+ assert_eq!(w.warning, WarningType::DistinctIdTruncated);+ assert_eq!(+ w.source,+ common_ingestion_warnings::CAPTURE_LEGACY_ANALYTICS+ );+ assert_eq!(w.token, "test_token");+ assert_eq!(w.count, 1);+ assert_eq!(w.extra_details["distinctId"], json!(long_id[..200]));+ assert_eq!(w.extra_details["distinctIdLength"], json!(250));+ assert_eq!(+ w.extra_details["eventUuid"],+ json!(sent[0].event.uuid),+ "sample must name the truncated event, not the healthy one"+ );+ }++ #[tokio::test]+ async fn multiple_truncated_distinct_ids_group_into_one_anonymous_warning() {+ let events = vec![+ event_with_distinct_id(&"x".repeat(250)),+ event_with_distinct_id(&"y".repeat(300)),+ ];++ let (result, emitted) =+ run_batch_collecting_warnings(events, Arc::new(MockSink::new())).await;+ result.unwrap();++ assert_eq!(emitted.len(), 1);+ let w = &emitted[0];+ assert_eq!(w.warning, WarningType::DistinctIdTruncated);+ assert_eq!(w.count, 2);+ // With several truncated ids any single sample would be an arbitrary+ // pick, so the identifier details are omitted.+ assert!(!w.extra_details.contains_key("distinctId"));+ assert!(!w.extra_details.contains_key("distinctIdLength"));+ assert!(!w.extra_details.contains_key("eventUuid"));+ }++ #[tokio::test]+ async fn no_truncation_warning_for_ids_within_the_cap() {+ let events = vec![event_with_distinct_id(&"z".repeat(200))];++ let (result, emitted) =+ run_batch_collecting_warnings(events, Arc::new(MockSink::new())).await;+ result.unwrap();++ assert!(emitted.is_empty());+ }++ #[tokio::test]+ async fn truncation_warning_counts_only_events_that_survive_the_filters() {+ // The warning means "ingested with a modified distinct_id", so a+ // truncated event the token dropper (or a restriction) removes must+ // not be counted or named as the sample.+ let dropped_id = "x".repeat(250);+ let surviving_id = "y".repeat(300);+ // The dropper matches on the post-truncation id, since that is what+ // the processed event carries.+ let dropper = Arc::new(limiters::token_dropper::TokenDropper::new(&format!(+ "test_token:{}",+ &dropped_id[..200]+ )));++ // Only truncated event is dropped: nothing was ingested-but-modified,+ // so no warning at all.+ let sink = Arc::new(MockSink::new());+ let (result, emitted) = run_batch_collecting_warnings_with_dropper(+ vec![+ event_with_distinct_id(&dropped_id),+ event_with_distinct_id("normal_user"),+ ],+ sink.clone(),+ dropper.clone(),+ )+ .await;+ result.unwrap();+ assert_eq!(sink.get_events().len(), 1);+ assert!(emitted.is_empty());++ // One truncated event dropped, another survives: count and sample+ // must reflect only the survivor.+ let sink = Arc::new(MockSink::new());+ let (result, emitted) = run_batch_collecting_warnings_with_dropper(+ vec![+ event_with_distinct_id(&dropped_id),+ event_with_distinct_id(&surviving_id),+ ],+ sink.clone(),+ dropper,+ )+ .await;+ result.unwrap();+ let sent = sink.get_events();+ assert_eq!(sent.len(), 1);++ assert_eq!(emitted.len(), 1);+ let w = &emitted[0];+ assert_eq!(w.count, 1);+ assert_eq!(w.extra_details["distinctId"], json!(surviving_id[..200]));+ assert_eq!(w.extra_details["distinctIdLength"], json!(300));+ assert_eq!(w.extra_details["eventUuid"], json!(sent[0].event.uuid));+ }++ #[tokio::test]+ async fn truncation_warning_is_not_emitted_when_the_sink_rejects_the_batch() {+ // The warning means "ingested with a modified distinct_id"; a batch+ // the sink refused was not ingested, so emitting would misreport.+ struct RejectingSink;+ #[async_trait::async_trait]+ impl sinks::Event for RejectingSink {+ async fn send(&self, _event: ProcessedEvent) -> Result<(), CaptureError> {+ Err(CaptureError::RetryableSinkError)+ }+ async fn send_batch(&self, _events: Vec<ProcessedEvent>) -> Result<(), CaptureError> {+ Err(CaptureError::RetryableSinkError)+ }+ }++ let events = vec![event_with_distinct_id(&"x".repeat(250))];++ let (result, emitted) =+ run_batch_collecting_warnings(events, Arc::new(RejectingSink)).await;+ assert!(matches!(result, Err(CaptureError::RetryableSinkError)));++ assert!(emitted.is_empty());+ }}diff --git a/rust/capture/src/events/overflow_stamping.rs b/rust/capture/src/events/overflow_stamping.rsindex ed84ebda081d..28fd74dc4c01 100644--- a/rust/capture/src/events/overflow_stamping.rs+++ b/rust/capture/src/events/overflow_stamping.rs@@ -166,6 +166,7 @@ mod tests {redirect_to_topic: None,skip_heatmap_processing: false,overflow_reason: None,+ distinct_id_truncated_from: None,};ProcessedEvent { event, metadata }diff --git a/rust/capture/src/events/recordings.rs b/rust/capture/src/events/recordings.rsindex 8e68c7bb1ec3..32ba7e4f4f5f 100644--- a/rust/capture/src/events/recordings.rs+++ b/rust/capture/src/events/recordings.rs@@ -398,6 +398,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,};// Serialize snapshot data synchronouslydiff --git a/rust/capture/src/ingestion_warnings.rs b/rust/capture/src/ingestion_warnings.rsindex a8bd50d34519..f7388629d6a3 100644--- a/rust/capture/src/ingestion_warnings.rs+++ b/rust/capture/src/ingestion_warnings.rs@@ -21,11 +21,13 @@ use std::collections::HashSet;use common_ingestion_warnings::{emit_request_warning, WarningEmitter, WarningRequestContext, WarningSource, WarningType,- UNKNOWN_ATTRIBUTION,+ CAPTURE_LEGACY_ANALYTICS, UNKNOWN_ATTRIBUTION,};use common_types::{EventWithLibraryInfo, RawEvent};use serde_json::{json, Map};+use uuid::Uuid;+use crate::api::CaptureError;use crate::v0_request::ProcessingContext;use crate::v1::context::RequestContext;@@ -133,6 +135,39 @@ pub fn emit_rate_limit_warning();}+/// 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,+ );+}+fn unknown_if_missing(value: Option<&str>) -> String {match value {Some(v) if !v.trim().is_empty() => v.to_string(),@@ -140,9 +175,110 @@ fn unknown_if_missing(value: Option<&str>) -> String {}}+/// Map a legacy-path request abort to the ingestion warning customers should+/// see, or `None` for failures customers can't act on.+///+/// This is the legacy pipeline's counterpart to v1's `Error::tag()` →+/// [`WarningType::from_tag`] route. It matches enum variants instead of the+/// `to_metric_tag()` strings so renames are compile-checked, and it lives here+/// rather than in `common_ingestion_warnings` so that crate never learns+/// capture's error taxonomy.+///+/// `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::MissingEventName => Some(WarningType::MissingEventName),+ CaptureError::MissingDistinctId => Some(WarningType::MissingDistinctId),+ // Only the Kafka sink raises EventTooBig during processing; the+ // transport-level size limits fail at the parsing stage, before a+ // verified token exists, and so never reach the abort path. This is+ // the same drop the nodejs pipeline reports as message_size_too_large+ // when its own produce hits the broker limit.+ 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,++ // Validation conditions with no warning yet (candidates, not+ // oversights), plus the recordings-only variants this analytics+ // mapper never sees.+ CaptureError::InvalidCookielessMode+ | CaptureError::InvalidTimestamp+ | CaptureError::MissingSnapshotData+ | CaptureError::MissingSessionId+ | CaptureError::MissingWindowId+ | CaptureError::InvalidSessionId => 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 legacy-path `process_events` abort, if the+/// error maps to one.+///+/// The legacy pipeline rejects the whole request on the first invalid event.+/// For validation aborts that means nothing was sent, so `count` charges the+/// full batch, matching what `report_dropped_events` records for the same+/// failure; it's floored at 1 for v1 parity, since a zero count would read as+/// "nothing happened" in the v2 table. `EventTooBig` is the exception: the+/// sink raises it per message after earlier events in the batch were already+/// enqueued (and typically deliver despite the 413), so charging the batch+/// would report delivered events as failed. It emits `count = 1` — at least+/// one event was rejected — matching the sink's per-event+/// `kafka_message_size` drop metric.+pub fn emit_processing_abort_warning(+ emitter: Option<&dyn WarningEmitter>,+ context: &ProcessingContext,+ err: &CaptureError,+ event_count: u64,+) {+ let Some(warning) = warning_for_capture_error(err) else {+ return;+ };+ let count = match err {+ CaptureError::EventTooBig(_) => 1,+ _ => event_count.max(1),+ };+ emit_request_warning(+ emitter,+ &legacy_request_context(context),+ CAPTURE_LEGACY_ANALYTICS,+ warning,+ Map::new(),+ count,+ );+}+#[cfg(test)]mod tests {use super::*;+ use common_ingestion_warnings::test_support::CollectingEmitter;use serde_json::json;fn raw_event(properties: serde_json::Value) -> RawEvent {@@ -261,4 +397,147 @@ mod tests {assert_eq!(ctx.lib_version, expected_lib_version, "{label}: libVersion");}}++ #[test]+ fn abort_warnings_map_only_customer_actionable_errors() {+ let cases: [(CaptureError, Option<WarningType>); 13] = [+ (+ CaptureError::MissingEventName,+ Some(WarningType::MissingEventName),+ ),+ (+ CaptureError::MissingDistinctId,+ Some(WarningType::MissingDistinctId),+ ),+ (+ CaptureError::EventTooBig("too big".to_string()),+ Some(WarningType::MessageSizeTooLarge),+ ),+ // Excluded on purpose; see warning_for_capture_error's doc.+ (CaptureError::InvalidCookielessMode, None),+ (CaptureError::EmptyBatch, None),+ (CaptureError::EmptyPayload, None),+ (CaptureError::InvalidTimestamp, None),+ (+ CaptureError::RequestParsingError("bad json".to_string()),+ None,+ ),+ (CaptureError::NoTokenError, None),+ (CaptureError::BillingLimit, None),+ (CaptureError::RetryableSinkError, None),+ (CaptureError::NonRetryableSinkError, None),+ (CaptureError::InternalError("boom".to_string()), None),+ ];++ for (err, expected) in cases {+ assert_eq!(+ warning_for_capture_error(&err),+ expected,+ "mapping for {err:?}"+ );+ }+ }++ // Guards the trust chain end to end: a mapper arm for a type that is not+ // capture-produced would be demoted to a generic client warning by the+ // nodejs consumer, and one routed via DIRECT_EMIT would violate the+ // common crate's one-route invariant. Both fail silently in production,+ // so pin them here like the common crate's weld test does for from_tag.+ #[test]+ fn mapped_abort_warnings_ride_the_capture_produced_tag_route() {+ let mapping_errors = [+ CaptureError::MissingEventName,+ CaptureError::MissingDistinctId,+ 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"+ );+ assert_eq!(+ WarningType::from_tag(warning.as_str()),+ Some(warning),+ "{warning:?} must be tag-routed"+ );+ assert!(+ !WarningType::DIRECT_EMIT.contains(&warning),+ "{warning:?} must not also be direct-emit"+ );+ }+ }++ #[test]+ fn abort_helper_charges_full_batch_with_legacy_validation_source() {+ // (error, event_count, expected emitted count): a validation abort+ // charges the batch size (nothing was sent), flooring zero to 1 so+ // the v2 row never reads as a no-op, matching v1's batch-abort+ // convention. EventTooBig charges 1: earlier batch events were+ // already enqueued and typically deliver, so a batch count would+ // report delivered events as failed.+ let cases = [+ (+ CaptureError::MissingDistinctId,+ WarningType::MissingDistinctId,+ 25u64,+ 25u64,+ ),+ (+ CaptureError::MissingDistinctId,+ WarningType::MissingDistinctId,+ 0u64,+ 1u64,+ ),+ (+ CaptureError::EventTooBig("too big".to_string()),+ WarningType::MessageSizeTooLarge,+ 25u64,+ 1u64,+ ),+ ];++ for (error, expected_warning, event_count, expected_count) in cases {+ let emitter = CollectingEmitter::default();+ let context = legacy_context(SdkAttribution {+ lib: Some("web".to_string()),+ lib_version: Some("1.2.3".to_string()),+ });++ emit_processing_abort_warning(Some(&emitter), &context, &error, event_count);++ let emitted = emitter.emitted();+ assert_eq!(emitted.len(), 1, "{error:?} event_count={event_count}");+ let warning = &emitted[0];+ assert_eq!(warning.token, "tok");+ assert_eq!(+ warning.source,+ common_ingestion_warnings::CAPTURE_LEGACY_ANALYTICS+ );+ assert_eq!(warning.warning, expected_warning);+ assert_eq!(warning.count, expected_count, "{error:?}");+ assert_eq!(warning.extra_details.get("lib"), Some(&json!("web")));+ assert_eq!(+ warning.extra_details.get("libVersion"),+ Some(&json!("1.2.3"))+ );+ assert_eq!(warning.extra_details.get("path"), Some(&json!("/e/")));+ }+ }++ #[test]+ fn abort_helper_emits_nothing_for_unmapped_errors() {+ let emitter = CollectingEmitter::default();+ let context = legacy_context(SdkAttribution::default());++ emit_processing_abort_warning(+ Some(&emitter),+ &context,+ &CaptureError::RetryableSinkError,+ 10,+ );++ assert!(emitter.emitted().is_empty());+ }}diff --git a/rust/capture/src/otel/filtering.rs b/rust/capture/src/otel/filtering.rsindex 38298fab222e..db1b8df71807 100644--- a/rust/capture/src/otel/filtering.rs+++ b/rust/capture/src/otel/filtering.rs@@ -126,6 +126,7 @@ pub fn build_events(redirect_to_topic: restrictions.redirect_to_topic().map(|s| s.to_string()),skip_heatmap_processing: false,overflow_reason: None,+ distinct_id_truncated_from: None,};processed.push(ProcessedEvent {diff --git a/rust/capture/src/sinks/fallback.rs b/rust/capture/src/sinks/fallback.rsindex 507ec2c9d9b6..ba888de867a3 100644--- a/rust/capture/src/sinks/fallback.rs+++ b/rust/capture/src/sinks/fallback.rs@@ -163,6 +163,7 @@ mod tests {redirect_to_topic: None,skip_heatmap_processing: false,overflow_reason: None,+ distinct_id_truncated_from: None,},};@@ -215,6 +216,7 @@ mod tests {redirect_to_topic: None,skip_heatmap_processing: false,overflow_reason: None,+ distinct_id_truncated_from: None,},};diff --git a/rust/capture/src/sinks/kafka.rs b/rust/capture/src/sinks/kafka.rsindex a6b675cb12cb..5dfafe26dcaf 100644--- a/rust/capture/src/sinks/kafka.rs+++ b/rust/capture/src/sinks/kafka.rs@@ -1007,6 +1007,7 @@ mod tests {redirect_to_topic: None,skip_heatmap_processing: false,overflow_reason: None,+ distinct_id_truncated_from: None,};let event = ProcessedEvent {@@ -1328,6 +1329,7 @@ mod tests {redirect_to_topic: input.redirect_to_topic.clone(),skip_heatmap_processing: false,overflow_reason: input.overflow_reason.clone(),+ distinct_id_truncated_from: None,};ProcessedEvent { event, metadata }diff --git a/rust/capture/src/sinks/s3.rs b/rust/capture/src/sinks/s3.rsindex 11cd03655dc6..65d3cab44e51 100644--- a/rust/capture/src/sinks/s3.rs+++ b/rust/capture/src/sinks/s3.rs@@ -365,6 +365,7 @@ mod tests {redirect_to_topic: None,skip_heatmap_processing: false,overflow_reason: None,+ distinct_id_truncated_from: None,},}}diff --git a/rust/capture/src/sinks/split.rs b/rust/capture/src/sinks/split.rsindex 7226aa0aede5..72a11baa58a6 100644--- a/rust/capture/src/sinks/split.rs+++ b/rust/capture/src/sinks/split.rs@@ -141,6 +141,7 @@ mod tests {redirect_to_topic: None,skip_heatmap_processing: false,overflow_reason: None,+ distinct_id_truncated_from: None,},}}diff --git a/rust/capture/src/v0_request.rs b/rust/capture/src/v0_request.rsindex 75bbc0bdb388..4ecb06a5e96b 100644--- a/rust/capture/src/v0_request.rs+++ b/rust/capture/src/v0_request.rs@@ -320,6 +320,11 @@ pub struct ProcessedEventMetadata {/// [`OverflowReason`] for who sets this and what each variant maps to in/// the kafka sink.pub overflow_reason: Option<OverflowReason>,+ /// Char count of the event's original distinct_id when extraction cut it+ /// down to the 200-char cap; `None` when it was ingested unmodified.+ /// Feeds the `distinct_id_truncated` ingestion warning; nothing routes on+ /// it.+ pub distinct_id_truncated_from: Option<usize>,}#[cfg(test)]diff --git a/rust/capture/tests/common/utils.rs b/rust/capture/tests/common/utils.rsindex 36a53e885ee5..73d63b6269f5 100644--- a/rust/capture/tests/common/utils.rs+++ b/rust/capture/tests/common/utils.rs@@ -228,6 +228,25 @@ impl ServerHandle {config.kafka.kafka_historical_topic = historical.topic_name().to_string();Self::for_config(config).await}+ /// Like `for_topics`, with the synthetic ingestion warnings emitter enabled+ /// and pointed at its own topic via the emitter's dedicated config, so+ /// legacy-path warning envelopes are readable independently of the events+ /// that triggered them.+ pub async fn for_topics_with_warnings(+ main: &EphemeralTopic,+ historical: &EphemeralTopic,+ warnings_topic: &EphemeralTopic,+ ) -> Self {+ let mut config = DEFAULT_CONFIG.clone();+ config.kafka.kafka_topic = main.topic_name().to_string();+ config.kafka.kafka_historical_topic = historical.topic_name().to_string();+ 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+ }+pub async fn for_recordings(main: &EphemeralTopic) -> Self {let mut config = DEFAULT_CONFIG.clone();config.kafka.kafka_topic = main.topic_name().to_string();diff --git a/rust/capture/tests/ingestion_warnings_integration.rs b/rust/capture/tests/ingestion_warnings_integration.rsindex 47b132e035c3..2ab80cf61494 100644--- a/rust/capture/tests/ingestion_warnings_integration.rs+++ b/rust/capture/tests/ingestion_warnings_integration.rs@@ -21,7 +21,7 @@ use utils::*;use anyhow::Result;use common_types::CapturedEvent;-use serde_json::Value;+use serde_json::{json, Value};use uuid::Uuid;use capture::v1::analytics::types::Event;@@ -81,3 +81,61 @@ async fn v1_validation_drop_emits_warning_envelope_to_kafka() -> Result<()> {warnings_topic.assert_empty();Ok(())}++#[tokio::test]+async fn legacy_processing_abort_emits_warning_envelope_to_kafka() -> Result<()> {+ setup_tracing();+ let token = random_string("phc_legacy_warn", 16);+ let events_topic = EphemeralTopic::new().await;+ let historical_topic = EphemeralTopic::new().await;+ let warnings_topic = EphemeralTopic::new().await;+ let server =+ ServerHandle::for_topics_with_warnings(&events_topic, &historical_topic, &warnings_topic)+ .await;++ // The legacy pipeline aborts the whole request on the first invalid+ // event, so the warning charges the full batch count even though+ // processing never reached the second event.+ let properties = json!({"$lib": "posthog-rs", "$lib_version": "1.0.0"});+ let payload = json!({+ "api_key": token,+ "batch": [+ {"event": "no-id-0", "properties": properties},+ {"event": "no-id-1", "properties": properties},+ ],+ });+ let res = server.capture_events(payload.to_string()).await;+ assert_eq!(+ res.status(),+ reqwest::StatusCode::BAD_REQUEST,+ "a legacy batch abort rejects the whole 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": "missing_distinct_id",+ "$$client_ingestion_warning_source": "capture",+ "$$client_ingestion_warning_details": {+ "count": 2,+ "lib": "posthog-rs",+ "libVersion": "1.0.0",+ "path": "/i/v0/e",+ "pipelineStep": "capture_validation",+ },+ })+ );++ events_topic.assert_empty();+ warnings_topic.assert_empty();+ Ok(())+}diff --git a/rust/common/ingestion_warnings/src/lib.rs b/rust/common/ingestion_warnings/src/lib.rsindex 72b652ccb12e..f75e3852987d 100644--- a/rust/common/ingestion_warnings/src/lib.rs+++ b/rust/common/ingestion_warnings/src/lib.rs@@ -154,6 +154,17 @@ pub const CAPTURE_LEGACY_RATE_LIMIT: WarningSource = WarningSource {pipeline_step: "capture_rate_limit",};+/// Capture's legacy analytics validation path (`rust/capture/src/events/analytics.rs`+/// and its `v0_endpoint` caller). Unlike `CAPTURE_V1_ANALYTICS`, the legacy+/// pipeline aborts the whole request on the first invalid event, so warnings+/// from this source charge the full batch's event count rather than a per-event+/// tally.+pub const CAPTURE_LEGACY_ANALYTICS: WarningSource = WarningSource {+ service: serializer::SOURCE_CAPTURE,+ path: "legacy_analytics",+ 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.rsindex 2723bd79e914..e9a52bfc15cc 100644--- a/rust/common/ingestion_warnings/src/registry.rs+++ b/rust/common/ingestion_warnings/src/registry.rs@@ -36,7 +36,7 @@ impl WarningType {/// 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; 1] = [Self::HighVolumeDistinctId];+ pub const DIRECT_EMIT: [Self; 2] = [Self::HighVolumeDistinctId, Self::DistinctIdTruncated];/// Map a capture error tag (`v1::Error::tag()` / per-event drop detail) to a/// registered warning type. Returns `None` for anything not on the allowlist —@@ -56,6 +56,7 @@ impl WarningType {"missing_event_uuid" => Some(Self::MissingEventUuid),"invalid_event_uuid" => Some(Self::InvalidEventUuid),"duplicate_event_uuid" => Some(Self::DuplicateEventUuid),+ "message_size_too_large" => Some(Self::MessageSizeTooLarge),_ => None,}}diff --git a/rust/common/ingestion_warnings/warning_types.generated.json b/rust/common/ingestion_warnings/warning_types.generated.jsonindex 94c61e6fc9b4..a464e5a2bf78 100644--- a/rust/common/ingestion_warnings/warning_types.generated.json+++ b/rust/common/ingestion_warnings/warning_types.generated.json@@ -55,6 +55,12 @@"severity": "error","captureProduced": true},+ {+ "type": "distinct_id_truncated",+ "category": "event",+ "severity": "warning",+ "captureProduced": true+ },{"type": "duplicate_event_uuid","category": "event",@@ -191,7 +197,7 @@"type": "message_size_too_large","category": "size","severity": "error",- "captureProduced": false+ "captureProduced": true},{"type": "message_timestamp_diff_too_large",diff --git a/rust/common/types/src/event.rs b/rust/common/types/src/event.rsindex 8abb868029ac..8883d0a52969 100644--- a/rust/common/types/src/event.rs+++ b/rust/common/types/src/event.rs@@ -438,6 +438,16 @@ impl HasEventName for RawEvent {}}+/// A distinct_id extracted from a [`RawEvent`], with the truncation outcome.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct ExtractedDistinctId {+ /// The id as ingested: stringified, NUL-scrubbed, capped at 200 chars.+ pub value: String,+ /// Char count of the original id when it exceeded the cap and `value` was+ /// cut down; `None` when the id was ingested unmodified.+ pub truncated_from_chars: Option<usize>,+}+impl RawEvent {pub fn extract_token(&self) -> Option<String> {match &self.token {@@ -455,6 +465,13 @@ impl RawEvent {/// and can send string, number, array, or map values. We try to best-effort/// stringify complex values, and make sure it's not longer than 200 chars.pub fn extract_distinct_id(&self) -> Option<String> {+ self.extract_distinct_id_checked().map(|e| e.value)+ }++ /// Like [`Self::extract_distinct_id`], but also reports whether the value+ /// was cut down to the 200-char cap, so callers can tell the sender their+ /// id was modified. Same extraction and truncation behavior.+ pub fn extract_distinct_id_checked(&self) -> Option<ExtractedDistinctId> {// Breaking change compared to capture-py: None / Null is not allowed.let value = match &self.distinct_id {None | Some(Value::Null) => match self.properties.get("distinct_id") {@@ -482,11 +499,30 @@ impl RawEvent {counter!("capture_distinct_id_has_whitespace_total").increment(1);}+ // 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 {- Some(distinct_id)- } else {- Some(distinct_id.chars().take(200).collect())+ return Some(ExtractedDistinctId {+ value: distinct_id,+ truncated_from_chars: None,+ });+ }++ let char_count = distinct_id.chars().count();+ if char_count <= 200 {+ // Over 200 bytes but not 200 chars: the historical+ // `chars().take(200)` truncation never cut these, so they are+ // not reported as truncated either.+ 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),+ })}// Extracts the cookieless mode from the event properties. If the value is not@@ -560,6 +596,42 @@ mod tests {assert_eq!(event.extract_distinct_id(), Some("hello".to_string()));}+ #[test]+ fn test_extract_distinct_id_checked_reports_truncation_only_when_chars_were_cut() {+ // (input, expected value, expected truncated_from_chars)+ let over_cap = "x".repeat(250);+ // 150 chars of a 3-byte codepoint: 450 bytes but under the 200-char+ // cap, so the value must pass through unmodified and unflagged.+ let multibyte_under_cap = "\u{20AC}".repeat(150);+ let multibyte_over_cap = "\u{20AC}".repeat(250);+ let cases = [+ ("short".to_string(), "short".to_string(), None),+ ("y".repeat(200), "y".repeat(200), None),+ (over_cap.clone(), over_cap[..200].to_string(), Some(250)),+ (multibyte_under_cap.clone(), multibyte_under_cap, None),+ (+ multibyte_over_cap.clone(),+ multibyte_over_cap.chars().take(200).collect(),+ Some(250),+ ),+ ];++ for (input, expected_value, expected_truncation) in cases {+ let event = RawEvent {+ distinct_id: Some(Value::String(input.clone())),+ ..Default::default()+ };+ let extracted = event+ .extract_distinct_id_checked()+ .expect("id should extract");+ assert_eq!(extracted.value, expected_value, "value for {input:.20?}");+ assert_eq!(+ extracted.truncated_from_chars, expected_truncation,+ "truncation flag for {input:.20?}"+ );+ }+ }+#[test]fn test_captured_event_serialization_with_historical_migration_true() {let event = CapturedEvent {diff --git a/rust/common/types/src/lib.rs b/rust/common/types/src/lib.rsindex 7ca2a2ae8c46..5d9c219a6d0d 100644--- a/rust/common/types/src/lib.rs+++ b/rust/common/types/src/lib.rs@@ -13,6 +13,7 @@ pub use event::CapturedEvent;pub use event::CapturedEventHeaders;pub use event::ClickHouseEvent;pub use event::EventWithLibraryInfo;+pub use event::ExtractedDistinctId;pub use event::HasEventName;pub use event::InternallyCapturedEvent;pub use event::LibraryInfo;