: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
chore(capture): drop v0 KAFKA_* fallback from warnings emitter (#74490)
Eli Reisman13a5dd946b7e
diff --git a/frontend/src/scenes/data-management/ingestion-warnings/IngestionWarningsView.tsx b/frontend/src/scenes/data-management/ingestion-warnings/IngestionWarningsView.tsxindex 09936c2c620d..a5af21156cd6 100644--- a/frontend/src/scenes/data-management/ingestion-warnings/IngestionWarningsView.tsx+++ b/frontend/src/scenes/data-management/ingestion-warnings/IngestionWarningsView.tsx@@ -53,6 +53,7 @@ export const WARNING_TYPE_TO_DESCRIPTION: Record<string, string> = {missing_event_uuid: 'Rejected a batch containing an event with no UUID',invalid_event_uuid: 'Rejected a batch containing an event with an invalid UUID',duplicate_event_uuid: 'Rejected a batch containing duplicate event UUIDs',+ high_volume_distinct_id: 'Skipped person profile processing for a high-volume distinct ID',}// Explicit anchor on https://posthog.com/docs/data/ingestion-warnings for each warning type.@@ -72,6 +73,7 @@ export const WARNING_TYPE_TO_DOCS_ANCHOR: Record<string, string> = {replay_timestamp_too_far: 'replay-event-timestamp-was-too-far-in-the-future',set_on_exception: 'invalid-set-operations-on-exception-events',invalid_heatmap_data: 'invalid-heatmap-data',+ high_volume_distinct_id: 'skipped-person-profile-processing-for-a-high-volume-distinct-id',}export const WARNING_TYPE_RENDERER = {diff --git a/nodejs/src/ingestion/common/ingestion-warning-types.ts b/nodejs/src/ingestion/common/ingestion-warning-types.tsindex 22a0f229a486..0aabad4c536b 100644--- a/nodejs/src/ingestion/common/ingestion-warning-types.ts+++ b/nodejs/src/ingestion/common/ingestion-warning-types.ts@@ -13,7 +13,7 @@* importers are unaffected.*/-export type IngestionWarningCategory = 'size' | 'merge' | 'event' | 'transformation' | 'replay'+export type IngestionWarningCategory = 'size' | 'merge' | 'event' | 'transformation' | 'replay' | 'quota'export type IngestionWarningSeverity = 'info' | 'warning' | 'error'/**@@ -83,6 +83,12 @@ export const INGESTION_WARNING_TYPES = {// Error tracking — exception event processingerror_tracking_exception_processing_errors: { category: 'event', severity: 'warning' },+ // Quota and rate limiting — platform-imposed limits, not team-configured ones.+ // Severity is 'warning' rather than 'error' because nothing is dropped: the+ // event is ingested with person profile processing turned off and rerouted to+ // overflow. See `apply_token_distinct_id_limits` in rust/capture.+ high_volume_distinct_id: { category: 'quota', severity: 'warning', captureProduced: true },+// Transformations — user-configured hog transformationsevent_dropped_by_transformation: { category: 'transformation', severity: 'info' },@@ -113,9 +119,12 @@ export type IngestionWarningType = keyof typeof INGESTION_WARNING_TYPES** Derived from the `captureProduced` flag above rather than hand-listed, so this* allowlist can never skew from the registry. The flag is also exported in the- * generated Rust artifact, where a test welds capture's `from_tag` emit- * allowlist to exactly this set — skew in either direction silently drops- * warnings (never emitted, or emitted and rejected here at the consumer).+ * generated Rust artifact, where a test welds this set to the union of capture's+ * two emit routes: types derived from an error tag (`from_tag`) and types capture+ * emits directly, with no tag behind them (`DIRECT_EMIT`). Skew in either+ * direction silently drops warnings — a flagged type on neither route is never+ * emitted, and a type on a route without the flag is emitted and then rejected+ * here at the consumer.*/export const CAPTURE_PRODUCED_WARNING_TYPES: ReadonlySet<IngestionWarningType> = new Set((Object.entries(INGESTION_WARNING_TYPES) as [IngestionWarningType, { captureProduced?: boolean }][])diff --git a/rust/capture/src/config.rs b/rust/capture/src/config.rsindex bd094a0b1cb8..0e2d62332553 100644--- a/rust/capture/src/config.rs+++ b/rust/capture/src/config.rs@@ -456,21 +456,24 @@ pub struct Config {#[envconfig(default = "1048576")]pub capture_ingestion_warnings_kafka_message_max_bytes: u32,- // Warnings-cluster overrides, same shape as the traces/metrics overrides in- // `KafkaConfig` below. When unset, each reuses the corresponding `kafka_*`- // value: `kafka_client_ingestion_warning_topic`, `kafka_hosts`, `kafka_tls`.+ // 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` /+ // `kafka_client_ingestion_warning_topic`. charts sets all three per env,+ // pointed at the MSK cluster the clientwarnings consumer reads from.//- // The emitter runs in the v1 analytics handler but its destination has- // always been read from the v0 `KAFKA_*` block. Retiring that block would- // silently fall these back to their envconfig defaults (an empty topic and- // TLS off), which is wrong in every environment, so the emitter owns its own- // names here. Setting them in charts makes the fallback dead config. TLS is- // separate from `kafka_hosts` because pointing the emitter at a cluster whose- // TLS requirement differs from the main one otherwise fails the producer's- // startup metadata fetch, which disables it for the pod's life.- pub capture_ingestion_warnings_kafka_topic: Option<String>,- pub capture_ingestion_warnings_kafka_hosts: Option<String>,- pub capture_ingestion_warnings_kafka_tls: Option<bool>,+ // Defaults are inert on purpose: empty hosts or topic makes+ // `create_ingestion_warning_emitter` report the emitter disabled and return+ // (fail open) rather than produce to a wrong or empty destination. TLS is a+ // separate knob from hosts because the warnings cluster's TLS requirement+ // need not match the main one — capture-ai is the live example, with a+ // PLAINTEXT WarpStream event sink and a TLS MSK warnings destination.+ #[envconfig(default = "")]+ pub capture_ingestion_warnings_kafka_topic: String,+ #[envconfig(default = "")]+ pub capture_ingestion_warnings_kafka_hosts: String,+ #[envconfig(default = "false")]+ pub capture_ingestion_warnings_kafka_tls: bool,}#[derive(Envconfig, Clone)]diff --git a/rust/capture/src/events/analytics.rs b/rust/capture/src/events/analytics.rsindex 0e3a8c51d1f1..32135757e920 100644--- a/rust/capture/src/events/analytics.rs+++ b/rust/capture/src/events/analytics.rs@@ -7,6 +7,7 @@ use std::collections::{HashMap, HashSet};use std::sync::Arc;use chrono::DateTime;+use common_ingestion_warnings::{WarningEmitter, CAPTURE_LEGACY_RATE_LIMIT};use common_types::{CapturedEvent, RawEvent};use limiters::token_dropper::TokenDropper;use metrics::counter;@@ -22,6 +23,7 @@ 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},prometheus::{report_clock_skew, report_dropped_events},router, sinks,utils::uuid_v7_from_datetime,@@ -241,6 +243,7 @@ pub async fn process_events(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,@@ -406,6 +409,12 @@ pub async fn process_events(// end state matches, but the pass order differs.// 2. Lane assignment is a single `DataType::from_event_name` match in// legacy versus assign-then-reroute in v1.+ // 3. Events whose person processing was already off: v1 skips its stamps+ // entirely (so such an event is never rerouted to overflow) and reports+ // it as outcome="already_disabled". Legacy still stamps and reroutes it,+ // and still counts it in the metric and log below; only the warning+ // excludes it. So legacy's limited count can exceed its warned count,+ // where v1's cannot.// Both paths consult the same shared limiter for every non-dropped event, so// per-key counts are identical regardless of which pipeline serves the key.// Import is unaffected by both: the GRL never runs (guard below) and no@@ -414,11 +423,21 @@ pub async fn process_events(if let Some(ref limiter) = global_rate_limiter {let mut limited_distinct_ids: HashSet<&str> = HashSet::new();let mut limited_event_count: u64 = 0;+ // Narrower than the tallies above: events an upstream event+ // restriction had already taken person processing away from are+ // excluded. The limiter didn't change their fate, so telling the+ // customer we skipped person processing for them would inflate the+ // count and name distinct_ids the limit never affected. v1 draws the+ // same line via `already_disabled` in+ // `v1::analytics::process::apply_token_distinct_id_limits`.+ let mut warned_distinct_ids: HashSet<&str> = HashSet::new();+ let mut warned_event_count: u64 = 0;for event in events.iter_mut() {let cache_key =GlobalRateLimitKey::TokenDistinctId(&context.token, &event.event.distinct_id).to_cache_key();if limiter.is_limited(&cache_key, 1).await.is_some() {+ let already_disabled = event.metadata.skip_person_processing;event.metadata.skip_person_processing = true;// Reroute the hot key to overflow. AnalyticsMain only: historical// never overflows, the AI lane keeps its dedicated topic (v1@@ -429,6 +448,10 @@ pub async fn process_events(}limited_distinct_ids.insert(&event.event.distinct_id);limited_event_count += 1;+ if !already_disabled {+ warned_distinct_ids.insert(&event.event.distinct_id);+ warned_event_count += 1;+ }}}if limited_event_count > 0 {@@ -451,6 +474,16 @@ pub async fn process_events("events rate limited by distinct_id -- person processing disabled");}++ if warned_event_count > 0 {+ emit_rate_limit_warning(+ ingestion_warning_emitter.as_deref(),+ &legacy_request_context(context),+ CAPTURE_LEGACY_RATE_LIMIT,+ &warned_distinct_ids,+ warned_event_count,+ );+ }}}@@ -485,9 +518,12 @@ pub async fn process_events(#[cfg(test)]mod tests {use super::*;+ use crate::ingestion_warnings::SdkAttribution;use crate::utils::uuid_v7_from_datetime;use crate::v0_request::{OverflowReason, ProcessingContext};use chrono::{DateTime, TimeZone, Utc};+ use common_ingestion_warnings::test_support::CollectingEmitter;+ use common_ingestion_warnings::WarningType;use common_types::RawEvent;use serde_json::json;use std::collections::HashMap;@@ -510,6 +546,7 @@ mod tests {historical_migration: false,chatty_debug_enabled: false,capture_mode: crate::config::CaptureMode::Events,+ sdk_attribution: crate::ingestion_warnings::SdkAttribution::default(),}}@@ -779,6 +816,7 @@ mod tests {None,None,None,+ None,&AiRouting::Primary,events,&context,@@ -829,6 +867,7 @@ mod tests {None,None,None,+ None,&AiRouting::Primary,events,&context,@@ -880,6 +919,7 @@ mod tests {None,None,None,+ None,&AiRouting::Primary,events,&context,@@ -931,6 +971,7 @@ mod tests {None,None,None,+ None,&AiRouting::Primary,events,&context,@@ -989,6 +1030,7 @@ mod tests {None,None,None,+ None,&AiRouting::Primary,events,&context,@@ -1027,6 +1069,7 @@ mod tests {None,None,None,+ None,&AiRouting::Primary,events,&context,@@ -1083,6 +1126,7 @@ mod tests {None,None,None,+ None,&AiRouting::Primary,events,&context,@@ -1133,6 +1177,7 @@ mod tests {None,None,None,+ None,&AiRouting::Primary,events,&context,@@ -1200,6 +1245,7 @@ mod tests {None,None,None,+ None,&routing,events,&context,@@ -1281,6 +1327,7 @@ mod tests {None,None,None,+ None,&AiRouting::Secondary,events,&context,@@ -1343,6 +1390,7 @@ mod tests {None,None,None,+ None,&AiRouting::Secondary,events,&context,@@ -1404,6 +1452,7 @@ mod tests {None,None,None,+ None,&AiRouting::Primary,events,&context,@@ -1479,6 +1528,7 @@ mod tests {None,None,None,+ None,&AiRouting::Primary,events,&context,@@ -1553,6 +1603,7 @@ mod tests {None,None,None,+ None,&AiRouting::Primary,events,&context,@@ -1622,6 +1673,7 @@ mod tests {None,None,None,+ None,&AiRouting::Primary,events,&context,@@ -1683,6 +1735,7 @@ mod tests {None,None,None,+ None,&AiRouting::Primary,events,&context,@@ -1738,6 +1791,7 @@ mod tests {None,None, // no overflow limiterNone,+ None,&AiRouting::Primary,events,&context,@@ -1776,6 +1830,7 @@ mod tests {None,Some(limiter),None,+ None,&AiRouting::Primary,events,&context,@@ -1828,6 +1883,7 @@ mod tests {None,None,ai_limiter,+ None,&AiRouting::Secondary,events,&context,@@ -1866,6 +1922,7 @@ mod tests {None,Some(limiter),None,+ None,&AiRouting::Primary,events,&context,@@ -1908,6 +1965,7 @@ mod tests {None,Some(limiter),None,+ None,&AiRouting::Primary,events,&context,@@ -1967,6 +2025,7 @@ mod tests {None,Some(limiter),None,+ None,&AiRouting::Primary,events,&context,@@ -2008,6 +2067,7 @@ mod tests {None,Some(limiter),None,+ None,&AiRouting::Primary,events,&context,@@ -2061,6 +2121,7 @@ mod tests {Some(global_limiter),Some(overflow_limiter),None,+ None,&AiRouting::Primary,events,&context,@@ -2126,6 +2187,7 @@ mod tests {Some(global_limiter),None, // no overflow limiter -- isolate global RL behaviorNone,+ None,&AiRouting::Primary,events,&context,@@ -2144,6 +2206,142 @@ mod tests {);}+ // The legacy path carries the bulk of rate-limited traffic, and it's the one+ // whose SDK attribution has to survive a snapshot taken back at batch+ // construction — by this stage the events are serialized.+ #[rstest::rstest]+ #[case::sdk_reported(+ Some(SdkAttribution {+ lib: Some("web".to_string()),+ lib_version: Some("1.2.3".to_string()),+ }),+ "web",+ "1.2.3"+ )]+ #[case::sdk_absent(None, "unknown", "unknown")]+ #[tokio::test]+ async fn global_rate_limit_emits_a_warning_naming_the_hot_key(+ #[case] attribution: Option<SdkAttribution>,+ #[case] expected_lib: &str,+ #[case] expected_lib_version: &str,+ ) {+ let now = DateTime::parse_from_rfc3339("2023-01-01T12:00:00Z")+ .unwrap()+ .with_timezone(&Utc);+ let mut context = create_test_context(now, None);+ if let Some(attribution) = attribution {+ context.sdk_attribution = attribution;+ }+ let events = vec![create_test_event(+ Some("2023-01-01T11:00:00Z".to_string()),+ None,+ None,+ )];++ let sink = Arc::new(MockSink::new());+ let dropper = Arc::new(limiters::token_dropper::TokenDropper::default());+ let historical_cfg = router::HistoricalConfig::new(false, 1);+ let global_limiter = Arc::new(GlobalRateLimiter::mock_limiting(&["test_token:test_user"]));+ let collector = Arc::new(CollectingEmitter::new());++ process_events(+ sink.clone(),+ dropper,+ None,+ historical_cfg,+ Some(global_limiter),+ None,+ None,+ Some(collector.clone()),+ &AiRouting::Primary,+ events,+ &context,+ )+ .await+ .unwrap();++ let emitted = collector.emitted();+ assert_eq!(emitted.len(), 1);+ let w = &emitted[0];+ assert_eq!(w.token, "test_token");+ assert_eq!(w.warning, WarningType::HighVolumeDistinctId);+ assert_eq!(w.source, CAPTURE_LEGACY_RATE_LIMIT);+ assert_eq!(w.count, 1);+ assert_eq!(+ w.extra_details["distinctId"],+ serde_json::json!("test_user")+ );+ assert_eq!(w.extra_details["distinctIdCount"], serde_json::json!(1));+ assert_eq!(w.extra_details["lib"], serde_json::json!(expected_lib));+ assert_eq!(+ w.extra_details["libVersion"],+ serde_json::json!(expected_lib_version)+ );+ assert_eq!(w.extra_details["path"], serde_json::json!("/e/"));+ }++ #[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+ // changed nothing the customer would recognize. It still reroutes the hot+ // key, but a warning here would overstate the limit's reach.+ 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 sink = Arc::new(MockSink::new());+ let dropper = Arc::new(limiters::token_dropper::TokenDropper::default());+ let historical_cfg = router::HistoricalConfig::new(false, 1);+ let global_limiter = Arc::new(GlobalRateLimiter::mock_limiting(&["test_token:test_user"]));+ let collector = Arc::new(CollectingEmitter::new());++ let service =+ EventRestrictionService::new(vec![Pipeline::Analytics], Duration::from_secs(300));+ let mut manager = RestrictionManager::new();+ manager.insert_restrictions(+ Pipeline::Analytics,+ "test_token",+ vec![Restriction {+ restriction_type: RestrictionType::SkipPersonProcessing,+ scope: RestrictionScope::AllEvents,+ args: None,+ }],+ );+ service.update(manager).await;++ process_events(+ sink.clone(),+ dropper,+ Some(service),+ historical_cfg,+ Some(global_limiter),+ None,+ None,+ Some(collector.clone()),+ &AiRouting::Primary,+ events,+ &context,+ )+ .await+ .unwrap();++ assert!(collector.emitted().is_empty());+ let captured = sink.get_events();+ assert_eq!(captured.len(), 1);+ assert!(captured[0].metadata.skip_person_processing);+ assert_eq!(+ captured[0].metadata.overflow_reason,+ Some(OverflowReason::ForceLimited),+ "the hot key is still rerouted to overflow"+ );+ }+#[tokio::test]async fn global_rate_limit_does_not_overflow_historical_events() {// Invariant: a globally rate-limited AnalyticsHistorical event gets person@@ -2172,6 +2370,7 @@ mod tests {Some(global_limiter),None, // no overflow limiter -- isolate global RL behaviorNone,+ None,&AiRouting::Primary,events,&context,@@ -2221,6 +2420,7 @@ mod tests {None,None,None,+ None,&AiRouting::Primary,events,&context,@@ -2262,6 +2462,7 @@ mod tests {None,None,None,+ None,&AiRouting::Primary,events,&context,@@ -2308,6 +2509,7 @@ mod tests {Some(global_limiter),None,None,+ None,&AiRouting::Primary,events,&context,@@ -2362,6 +2564,7 @@ mod tests {None,Some(limiter),None,+ None,&AiRouting::Primary,events,&context,@@ -2415,6 +2618,7 @@ mod tests {None,Some(limiter),None,+ None,&AiRouting::Primary,events,&context,@@ -2471,6 +2675,7 @@ mod tests {None,Some(limiter),None,+ None,&AiRouting::Primary,events,&context,@@ -2718,6 +2923,7 @@ mod tests {None,None,None,+ None,&AiRouting::Primary,events,&context,@@ -2768,6 +2974,7 @@ mod tests {None,None,None,+ None,&AiRouting::Primary,events,&context,@@ -2807,6 +3014,7 @@ mod tests {None,None,None,+ None,&AiRouting::Primary,events,&context,@@ -2854,6 +3062,7 @@ mod tests {None,None,None,+ None,&AiRouting::Primary,events,&context,diff --git a/rust/capture/src/events/recordings.rs b/rust/capture/src/events/recordings.rsindex 218064bd0da4..8e68c7bb1ec3 100644--- a/rust/capture/src/events/recordings.rs+++ b/rust/capture/src/events/recordings.rs@@ -625,6 +625,7 @@ mod tests {user_agent: None,path: "/s/".to_string(),capture_mode: crate::config::CaptureMode::Recordings,+ sdk_attribution: crate::ingestion_warnings::SdkAttribution::default(),}}diff --git a/rust/capture/src/ingestion_warnings.rs b/rust/capture/src/ingestion_warnings.rsnew file mode 100644index 000000000000..a8bd50d34519--- /dev/null+++ b/rust/capture/src/ingestion_warnings.rs@@ -0,0 +1,264 @@+//! Per-path SDK attribution for ingestion warnings.+//!+//! Every capture pipeline learns the client SDK differently, and the differences+//! are permanent, not transitional:+//!+//! * v1 requires the `PostHog-Sdk-Info` header and materializes+//! `$lib`/`$lib_version` from it, overriding whatever the body claims+//! ([`crate::v1::context::RequestContext::sdk_lib_and_version`]).+//! * The legacy path has no such header contract. Its only source is the events'+//! `$lib`/`$lib_version` properties, which are gone by the time the pipeline+//! holds serialized `CapturedEvent`s — so the batch handler snapshots them+//! onto [`ProcessingContext`] while the events are still typed.+//! * Replay and the AI endpoint each carry their own quirks and will need their+//! own conversion here when they start emitting.+//!+//! Normalizing lives here rather than in `common_ingestion_warnings` so that+//! crate never learns capture's event shapes: it takes concrete strings and+//! stamps them.++use std::collections::HashSet;++use common_ingestion_warnings::{+ emit_request_warning, WarningEmitter, WarningRequestContext, WarningSource, WarningType,+ UNKNOWN_ATTRIBUTION,+};+use common_types::{EventWithLibraryInfo, RawEvent};+use serde_json::{json, Map};++use crate::v0_request::ProcessingContext;+use crate::v1::context::RequestContext;++/// 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+/// bytes). Oversized values are treated as absent rather than truncated: they+/// would otherwise ride into every warning payload for the batch and into the+/// `Debug` output of [`ProcessingContext`], which the legacy path logs several+/// times per request when chatty debug is on.+const MAX_SDK_ATTRIBUTION_LEN: usize = 200;++/// SDK identity as reported by a batch, for attribution only.+///+/// Both fields are unvalidated client input. Nothing routes on them.+#[derive(Debug, Clone, Default, PartialEq, Eq)]+pub struct SdkAttribution {+ pub lib: Option<String>,+ pub lib_version: Option<String>,+}++impl SdkAttribution {+ /// Take attribution from the first event of a batch.+ ///+ /// One batch is one SDK in every real client: batching is a client-side+ /// buffer flush, so events in it share a `$lib`. Scanning further to+ /// reconcile disagreement would cost a pass over the batch on the hot path+ /// to improve a field that is only ever displayed.+ pub fn from_first_event(events: &[RawEvent]) -> Self {+ let Some(info) = events.first().and_then(|e| e.extract_library_info()) else {+ return Self::default();+ };+ Self {+ lib: within_bound(info.name),+ lib_version: info.version.and_then(within_bound),+ }+ }+}++fn within_bound(value: String) -> Option<String> {+ (value.len() <= MAX_SDK_ATTRIBUTION_LEN).then_some(value)+}++/// Warning attribution for a legacy-path batch.+///+/// SDK fields come from the snapshot the handler took during batch construction;+/// a batch that reported no `$lib` (or a `$lib` with no version, which the JS+/// SDK can do) stamps [`UNKNOWN_ATTRIBUTION`] rather than dropping the key.+pub fn legacy_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(),+ }+}++/// Warning attribution for a v1 request.+///+/// `sdk_lib_and_version` is all-or-nothing — the header is a single+/// `name/version` string — so both fields fall back together.+pub fn v1_request_context(context: &RequestContext) -> WarningRequestContext {+ let (lib, lib_version) = context+ .sdk_lib_and_version()+ .unwrap_or((UNKNOWN_ATTRIBUTION, UNKNOWN_ATTRIBUTION));+ WarningRequestContext {+ token: context.api_token.clone(),+ lib: lib.to_string(),+ lib_version: lib_version.to_string(),+ path: context.path.to_string(),+ }+}++/// Emit the `high_volume_distinct_id` warning for one batch's rate-limited+/// events. Shared by the v1 and legacy rate limiter stages, which differ only in+/// their [`WarningSource`] — the payload must not drift between them, since a+/// reader of the v2 table can't tell which pipeline served a request.+///+/// `distinct_id` is included only when the batch had exactly one hot key; with+/// several it would be an arbitrary pick, and `distinctIdCount` already says how+/// many there were. The value needs no size bounding here: both pipelines drop+/// oversized distinct_ids before the limiter runs.+pub fn emit_rate_limit_warning(+ emitter: Option<&dyn WarningEmitter>,+ request: &WarningRequestContext,+ source: WarningSource,+ limited_distinct_ids: &HashSet<&str>,+ limited_event_count: u64,+) {+ let mut details = Map::new();+ details.insert(+ "distinctIdCount".to_string(),+ json!(limited_distinct_ids.len()),+ );+ if let [distinct_id] = limited_distinct_ids.iter().copied().collect::<Vec<_>>()[..] {+ details.insert("distinctId".to_string(), json!(distinct_id));+ }++ emit_request_warning(+ emitter,+ request,+ source,+ WarningType::HighVolumeDistinctId,+ details,+ limited_event_count,+ );+}++fn unknown_if_missing(value: Option<&str>) -> String {+ match value {+ Some(v) if !v.trim().is_empty() => v.to_string(),+ _ => UNKNOWN_ATTRIBUTION.to_string(),+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use serde_json::json;++ fn raw_event(properties: serde_json::Value) -> RawEvent {+ RawEvent {+ event: "$pageview".to_string(),+ properties: properties+ .as_object()+ .expect("test properties must be an object")+ .iter()+ .map(|(k, v)| (k.clone(), v.clone()))+ .collect(),+ ..Default::default()+ }+ }++ fn legacy_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: "/e/".to_string(),+ is_mirror_deploy: false,+ historical_migration: false,+ chatty_debug_enabled: false,+ capture_mode: crate::config::CaptureMode::Events,+ sdk_attribution: attribution,+ }+ }++ #[test]+ fn first_event_supplies_attribution_for_the_whole_batch() {+ let events = vec![+ raw_event(json!({"$lib": "web", "$lib_version": "1.2.3"})),+ raw_event(json!({"$lib": "posthog-python", "$lib_version": "9.9.9"})),+ ];+ assert_eq!(+ SdkAttribution::from_first_event(&events),+ SdkAttribution {+ lib: Some("web".to_string()),+ lib_version: Some("1.2.3".to_string()),+ }+ );+ }++ // Each of these is a payload capture accepts today, so each must produce a+ // stampable context rather than a missing key. Oversized values are dropped+ // rather than truncated, so they land on the same fallback.+ #[test]+ fn unusable_attribution_becomes_unknown() {+ let at_bound = "w".repeat(MAX_SDK_ATTRIBUTION_LEN);+ let over_bound = "w".repeat(MAX_SDK_ATTRIBUTION_LEN + 1);+ let cases = [+ (+ "no events",+ vec![],+ UNKNOWN_ATTRIBUTION,+ UNKNOWN_ATTRIBUTION,+ ),+ (+ "no properties",+ vec![raw_event(json!({}))],+ UNKNOWN_ATTRIBUTION,+ UNKNOWN_ATTRIBUTION,+ ),+ (+ "lib without version",+ vec![raw_event(json!({"$lib": "web"}))],+ "web",+ UNKNOWN_ATTRIBUTION,+ ),+ (+ "non-string lib",+ vec![raw_event(json!({"$lib": 42, "$lib_version": "1.2.3"}))],+ UNKNOWN_ATTRIBUTION,+ UNKNOWN_ATTRIBUTION,+ ),+ (+ "empty lib",+ vec![raw_event(json!({"$lib": "", "$lib_version": ""}))],+ UNKNOWN_ATTRIBUTION,+ UNKNOWN_ATTRIBUTION,+ ),+ (+ "oversized lib",+ vec![raw_event(+ json!({"$lib": over_bound, "$lib_version": "1.2.3"}),+ )],+ UNKNOWN_ATTRIBUTION,+ "1.2.3",+ ),+ (+ "oversized version",+ vec![raw_event(+ json!({"$lib": "web", "$lib_version": over_bound}),+ )],+ "web",+ UNKNOWN_ATTRIBUTION,+ ),+ (+ "lib at the bound",+ vec![raw_event(+ json!({"$lib": at_bound, "$lib_version": "1.2.3"}),+ )],+ at_bound.as_str(),+ "1.2.3",+ ),+ ];++ for (label, events, expected_lib, expected_lib_version) in cases {+ let attribution = SdkAttribution::from_first_event(&events);+ let ctx = legacy_request_context(&legacy_context(attribution));+ assert_eq!(ctx.lib, expected_lib, "{label}: lib");+ assert_eq!(ctx.lib_version, expected_lib_version, "{label}: libVersion");+ }+ }+}diff --git a/rust/capture/src/lib.rs b/rust/capture/src/lib.rsindex 81af898845f5..2133f5957fe9 100644--- a/rust/capture/src/lib.rs+++ b/rust/capture/src/lib.rs@@ -6,6 +6,7 @@ pub mod event_restrictions;pub mod events;pub mod extractors;pub mod global_rate_limiter;+pub mod ingestion_warnings;pub mod log_util;pub mod metrics_middleware;pub mod otel;diff --git a/rust/capture/src/payload/analytics.rs b/rust/capture/src/payload/analytics.rsindex d027ec9dc596..122afbdce042 100644--- a/rust/capture/src/payload/analytics.rs+++ b/rust/capture/src/payload/analytics.rs@@ -16,6 +16,7 @@ use crate::{api::CaptureError,debug_or_info,extractors::extract_body_with_timeout,+ ingestion_warnings::SdkAttribution,payload::{extract_and_record_metadata, extract_payload_bytes, EventQuery},router,utils::extract_and_verify_token,@@ -108,6 +109,10 @@ pub async fn handle_event_payload(let now = state.timesource.current_time();+ // Snapshot SDK identity while the events are still typed — later stages only+ // see serialized payloads.+ let sdk_attribution = SdkAttribution::from_first_event(&events);+let context = ProcessingContext {sent_at,token,@@ -120,6 +125,7 @@ pub async fn handle_event_payload(user_agent: Some(metadata.user_agent.to_string()),chatty_debug_enabled,capture_mode: state.capture_mode,+ sdk_attribution,};debug_or_info!(chatty_debug_enabled, context=?context, event_count=?events.len(), "processing complete");diff --git a/rust/capture/src/payload/recordings.rs b/rust/capture/src/payload/recordings.rsindex a49206583288..b1b8d7cdf8e6 100644--- a/rust/capture/src/payload/recordings.rs+++ b/rust/capture/src/payload/recordings.rs@@ -16,6 +16,7 @@ use crate::{debug_or_info,events::recordings::RawRecording,extractors::extract_body_with_timeout,+ ingestion_warnings::SdkAttribution,payload::{decompress_payload, extract_and_record_metadata, extract_payload_bytes, EventQuery},router,token::validate_token,@@ -127,6 +128,10 @@ 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(),};// Apply all billing limit quotas and drop partial or wholediff --git a/rust/capture/src/setup.rs b/rust/capture/src/setup.rsindex 245739a40ee0..e66407af8013 100644--- a/rust/capture/src/setup.rs+++ b/rust/capture/src/setup.rs@@ -728,12 +728,12 @@ fn build_warnings_kafka_config(/// `common_kafka::kafka_producer::create_threaded_kafka_producer_no_ping` from a/// dedicated, warnings-only `common_kafka::config::KafkaConfig` (fire-and-forget/// acks/retries, a small queue) with `observe_delivery` as its delivery-/// callback — by default it shares only the destination cluster (hosts/TLS) and-/// the `client_ingestion_warning` topic with capture's main event producer,-/// never its tuning or connection. All three are overridable via-/// `CAPTURE_INGESTION_WARNINGS_KAFKA_{HOSTS,TLS,TOPIC}`. When built, a background-/// task heartbeats the advisory lifecycle handle, sweeps the throttle's per-key-/// state, and flushes the producer once at shutdown.+/// callback. Its destination (hosts/TLS/topic) comes entirely from+/// `CAPTURE_INGESTION_WARNINGS_KAFKA_{HOSTS,TLS,TOPIC}`; it no longer borrows+/// anything from capture's main event config (the v0 `KAFKA_*` block), so+/// retiring that block cannot silently misroute or mute it. When built, a+/// background task heartbeats the advisory lifecycle handle, sweeps the+/// throttle's per-key state, and flushes the producer once at shutdown.////// Uses the no-ping constructor so an unreachable warnings cluster costs/// capture nothing at boot: no 15s metadata fetch on the startup path, and no@@ -754,22 +754,14 @@ async fn create_ingestion_warning_emitter(// "enabled but broken".let report_disabled = || gauge!(INGESTION_WARNINGS_EMITTER_ENABLED).set(0.0);- let hosts = config- .capture_ingestion_warnings_kafka_hosts- .clone()- .unwrap_or_else(|| config.kafka.kafka_hosts.clone());- let topic = config- .capture_ingestion_warnings_kafka_topic- .clone()- .unwrap_or_else(|| config.kafka.kafka_client_ingestion_warning_topic.clone());- let tls = config- .capture_ingestion_warnings_kafka_tls- .unwrap_or(config.kafka.kafka_tls);+ let hosts = config.capture_ingestion_warnings_kafka_hosts.clone();+ let topic = config.capture_ingestion_warnings_kafka_topic.clone();+ let tls = config.capture_ingestion_warnings_kafka_tls;if hosts.is_empty() {warn!(- "ingestion warnings enabled but no Kafka hosts \- (CAPTURE_INGESTION_WARNINGS_KAFKA_HOSTS, KAFKA_HOSTS); emitter disabled"+ "ingestion warnings enabled but CAPTURE_INGESTION_WARNINGS_KAFKA_HOSTS is unset; \+ emitter disabled");report_disabled();return None;@@ -777,8 +769,7 @@ async fn create_ingestion_warning_emitter(if topic.is_empty() {warn!(- "ingestion warnings enabled but no Kafka topic \- (CAPTURE_INGESTION_WARNINGS_KAFKA_TOPIC, KAFKA_CLIENT_INGESTION_WARNING_TOPIC); \+ "ingestion warnings enabled but CAPTURE_INGESTION_WARNINGS_KAFKA_TOPIC is unset; \emitter disabled");report_disabled();@@ -1002,6 +993,88 @@ mod tests {assert_eq!(cfg.kafka_producer_partitioner, None);}+ #[tokio::test]+ async fn ingestion_warnings_emitter_does_not_consult_v0_kafka_block() {+ // Regression guard for the v0 fallback removal: with warnings enabled but+ // no dedicated hosts, the emitter must stay disabled rather than reuse the+ // v0 KAFKA_HOSTS / KAFKA_CLIENT_INGESTION_WARNING_TOPIC block. If the+ // fallback were still live, it would build a producer against v0-broker.+ let cfg_env: HashMap<String, String> = [+ ("REDIS_URL", "redis://localhost:6379/"),+ ("CAPTURE_MODE", "events"),+ ("KAFKA_HOSTS", "v0-broker:9092"),+ ("KAFKA_TOPIC", "events_plugin_ingestion"),+ ("KAFKA_CLIENT_INGESTION_WARNING_TOPIC", "v0-warnings-topic"),+ ("CAPTURE_INGESTION_WARNINGS_ENABLED", "true"),+ // CAPTURE_INGESTION_WARNINGS_KAFKA_HOSTS deliberately left unset.+ ]+ .into_iter()+ .map(|(k, v)| (k.to_string(), v.to_string()))+ .collect();+ let config: Config =+ envconfig::Envconfig::init_from_hashmap(&cfg_env).expect("test config");++ // The v0 block is populated, so a live fallback would have hosts to use;+ // the dedicated hosts are empty, which is the only thing that should count.+ assert_eq!(config.kafka.kafka_hosts, "v0-broker:9092");+ assert!(config.capture_ingestion_warnings_kafka_hosts.is_empty());++ let emitter = create_ingestion_warning_emitter(&config, None).await;+ assert!(+ emitter.is_none(),+ "emitter must stay disabled on empty dedicated hosts, not fall back to KAFKA_HOSTS"+ );+ }++ #[tokio::test]+ async fn disabled_emitter_with_live_handle_does_not_shut_capture_down() {+ // `register_components` moves the warnings handle in here and keeps no+ // clone, so bailing out early drops the last reference and fires+ // `ComponentEvent::Died`. Removing the v0 fallback is what makes that+ // reachable in production: a pod told to emit warnings but given no+ // dedicated hosts now takes this path on every start. Warnings are+ // best-effort, so it has to cost capture nothing.+ let cfg_env: HashMap<String, String> = [+ ("REDIS_URL", "redis://localhost:6379/"),+ ("CAPTURE_MODE", "events"),+ ("KAFKA_HOSTS", "v0-broker:9092"),+ ("KAFKA_TOPIC", "events_plugin_ingestion"),+ ("CAPTURE_INGESTION_WARNINGS_ENABLED", "true"),+ ]+ .into_iter()+ .map(|(k, v)| (k.to_string(), v.to_string()))+ .collect();+ let config: Config =+ envconfig::Envconfig::init_from_hashmap(&cfg_env).expect("test config");++ let shutdown = tokio_util::sync::CancellationToken::new();+ let mut manager = lifecycle::Manager::builder("test")+ .with_trap_signals(false)+ .with_prestop_check(false)+ .with_shutdown_token(shutdown.clone())+ .build();+ // Mirrors the registration in `register_components`.+ let handle = manager.register(+ "ingestion-warnings",+ lifecycle::ComponentOptions::new()+ .with_liveness_deadline(Duration::from_secs(30))+ .is_advisory(true),+ );+ let server = manager.register("server", lifecycle::ComponentOptions::new());+ let _guard = manager.monitor_background();++ let emitter = create_ingestion_warning_emitter(&config, Some(handle)).await;+ assert!(emitter.is_none(), "emitter must stay disabled");++ // Long enough for a Died-driven cancel to have landed.+ tokio::time::sleep(Duration::from_millis(300)).await;+ assert!(+ !shutdown.is_cancelled(),+ "a disabled warnings emitter must not initiate capture shutdown"+ );+ assert!(!server.is_shutting_down(), "capture must still be serving");+ }+#[test]#[should_panic(expected = "S3_FALLBACK_ENABLED cannot be combined with AI secondary routing")]fn register_components_rejects_s3_fallback_with_ai_secondary() {diff --git a/rust/capture/src/v0_endpoint.rs b/rust/capture/src/v0_endpoint.rsindex 20b0994bce16..5d0b09643a98 100644--- a/rust/capture/src/v0_endpoint.rs+++ b/rust/capture/src/v0_endpoint.rs@@ -68,6 +68,7 @@ pub async fn event(state.global_rate_limiter_token_distinctid.clone(),state.overflow_limiter.clone(),state.ai_events_overflow_limiter.clone(),+ state.ingestion_warning_emitter.clone(),&state.ai_routing,events,&context,diff --git a/rust/capture/src/v0_request.rs b/rust/capture/src/v0_request.rsindex 3603c70c83f2..80d856d97ddc 100644--- a/rust/capture/src/v0_request.rs+++ b/rust/capture/src/v0_request.rs@@ -10,6 +10,7 @@ use crate::{api::CaptureError,config::CaptureMode,event_restrictions::Pipeline,+ ingestion_warnings::SdkAttribution,payload::{decompress_payload, Compression},};@@ -148,6 +149,12 @@ pub struct ProcessingContext {/// analytics path: skip the global rate limiter and drop any batch not/// flagged `historical_migration: true`.pub capture_mode: CaptureMode,+ /// SDK identity snapshotted from the batch's first event, for ingestion+ /// warning attribution. Captured at batch construction because the events+ /// are typed there; downstream stages hold serialized payloads and would+ /// have to re-parse JSON on the hot path to recover it. Display only —+ /// nothing routes on it. See [`crate::ingestion_warnings`].+ pub sdk_attribution: SdkAttribution,}// these are the legacy endpoints capture maintains. Can eliminate thisdiff --git a/rust/capture/src/v1/analytics/process.rs b/rust/capture/src/v1/analytics/process.rsindex 88c9847df805..111074ad5616 100644--- a/rust/capture/src/v1/analytics/process.rs+++ b/rust/capture/src/v1/analytics/process.rs@@ -23,13 +23,16 @@ use limiters::overflow::{OverflowLimiter, OverflowLimiterResult};use tracing::Level;use super::context::Context;+use crate::ingestion_warnings::{emit_rate_limit_warning, v1_request_context};use crate::router;use crate::v1::context::RequestContext;use crate::v1::sinks::event::Event as SinkEvent;use crate::v1::sinks::types::SinkResult;use crate::v1::sinks::{serialize_batch, Destination};use crate::v1::Error;-use common_ingestion_warnings::{WarningType, CAPTURE_V1_ANALYTICS};+use common_ingestion_warnings::{+ emit_request_warning, WarningEmitter, WarningType, CAPTURE_V1_ANALYTICS, CAPTURE_V1_RATE_LIMIT,+};/// Maps event name to its Kafka destination, mirroring legacy DataType assignment.///@@ -160,7 +163,13 @@ pub async fn process_batch(// overflowable lane is reachable, so behavior is identical across paths.if state.capture_mode.applies_global_rate_limit() {if let Some(ref limiter) = state.global_rate_limiter_token_distinctid {- let _ = apply_token_distinct_id_limits(limiter, context, &mut events).await;+ let _ = apply_token_distinct_id_limits(+ limiter,+ context,+ state.ingestion_warning_emitter.as_deref(),+ &mut events,+ )+ .await;}}@@ -321,19 +330,6 @@ pub fn merge_sink_results(events: &mut [WrappedEvent], sink_results: &[Box<dyn S}}-/// Stamps request-level context (sdk lib/version, request path) into a-/// warning's details map. Keys are camelCase to match the v2 `DEFAULT`-/// extractors' expectations for entity keys.-fn warning_context_details(context: &Context) -> serde_json::Map<String, serde_json::Value> {- let mut details = serde_json::Map::new();- if let Some((lib, version)) = context.sdk_lib_and_version() {- details.insert("lib".to_string(), serde_json::json!(lib));- details.insert("libVersion".to_string(), serde_json::json!(version));- }- details.insert("path".to_string(), serde_json::json!(context.path));- details-}-/// Best-effort v2 ingestion warning for a whole-batch validation abort (4xx)./// The batch is rejected as a unit, so `count` charges the full batch length;/// no per-event identifiers exist at this point. Unregistered tags emit@@ -344,19 +340,17 @@ fn emit_batch_abort_warning(err: &Error,batch_len: usize,) {- let Some(ref emitter) = state.ingestion_warning_emitter else {- return;- };let Some(warning) = WarningType::from_tag(err.tag()) else {return;};// `empty_batch` aborts have batch_len == 0; the rejected request is still// one occurrence, so never charge a count of zero.- emitter.emit(- context.api_token.clone(),+ emit_request_warning(+ state.ingestion_warning_emitter.as_deref(),+ &v1_request_context(context),CAPTURE_V1_ANALYTICS,warning,- warning_context_details(context),+ serde_json::Map::new(),batch_len.max(1) as u64,);}@@ -371,9 +365,12 @@ fn emit_validation_drop_warnings(context: &Context,events: &[WrappedEvent],) {- let Some(ref emitter) = state.ingestion_warning_emitter else {+ let emitter = state.ingestion_warning_emitter.as_deref();+ if emitter.is_none() {+ // Checked up front so a deployment with warnings off doesn't pay for the+ // grouping pass below.return;- };+ }// (count, identifiers-of-the-single-event-if-unique) per warning type.type DropGroup<'a> = (u64, Option<(&'a str, Uuid)>);@@ -394,8 +391,9 @@ fn emit_validation_drop_warnings(}}+ let request = v1_request_context(context);for (warning, (count, single_event)) in grouped {- let mut details = warning_context_details(context);+ let mut details = serde_json::Map::new();if let Some((distinct_id, uuid)) = single_event {// A public request can submit a `distinct_id` far larger than// CAPTURE_V1_DISTINCT_ID_MAX_SIZE (that oversized value is exactly@@ -416,8 +414,9 @@ fn emit_validation_drop_warnings(}details.insert("eventUuid".to_string(), serde_json::json!(uuid.to_string()));}- emitter.emit(- context.api_token.clone(),+ emit_request_warning(+ emitter,+ &request,CAPTURE_V1_ANALYTICS,warning,details,@@ -829,6 +828,7 @@ struct TokenDistinctIdTally {async fn apply_token_distinct_id_limits(limiter: &GlobalRateLimiter,context: &RequestContext,+ emitter: Option<&dyn WarningEmitter>,events: &mut [WrappedEvent],) -> TokenDistinctIdTally {let mut limited_distinct_ids: HashSet<&str> = HashSet::new();@@ -916,6 +916,14 @@ async fn apply_token_distinct_id_limits(distinct_ids = %preview,"events rate limited by distinct_id -- person processing disabled");++ emit_rate_limit_warning(+ emitter,+ &v1_request_context(context),+ CAPTURE_V1_RATE_LIMIT,+ &limited_distinct_ids,+ limited_event_count,+ );}TokenDistinctIdTally {@@ -2353,7 +2361,7 @@ mod tests {wrapped_event("$identify", "user-2"),];- apply_token_distinct_id_limits(&limiter, &ctx, &mut events).await;+ apply_token_distinct_id_limits(&limiter, &ctx, None, &mut events).await;for ev in &events {assert_eq!(ev.result, EventResult::Ok);@@ -2371,7 +2379,7 @@ mod tests {wrapped_event("$identify", "user-2"),];- apply_token_distinct_id_limits(&limiter, &ctx, &mut events).await;+ apply_token_distinct_id_limits(&limiter, &ctx, None, &mut events).await;let ok_ev = find_by_did(&events, "user-1");assert_eq!(ok_ev.result, EventResult::Ok);@@ -2391,7 +2399,7 @@ mod tests {let ctx = td_context();let mut events = vec![malformed_wrapped_event()];- apply_token_distinct_id_limits(&limiter, &ctx, &mut events).await;+ apply_token_distinct_id_limits(&limiter, &ctx, None, &mut events).await;let ev = &events[0];assert_eq!(ev.result, EventResult::Drop);@@ -2409,7 +2417,7 @@ mod tests {wrapped_event("$click", "user-1"),];- apply_token_distinct_id_limits(&limiter, &ctx, &mut events).await;+ apply_token_distinct_id_limits(&limiter, &ctx, None, &mut events).await;for ev in &events {assert_eq!(ev.result, EventResult::Warning, "should be Warning");@@ -2442,7 +2450,7 @@ mod tests {pd.result = EventResult::Drop;pd.destination = Destination::Drop;- apply_token_distinct_id_limits(&limiter, &ctx, &mut events).await;+ apply_token_distinct_id_limits(&limiter, &ctx, None, &mut events).await;// Pre-dropped event untouchedlet dropped = find_by_did(&events, "user-1");@@ -2473,7 +2481,7 @@ mod tests {events[0].force_disable_person_processing = true;events[0].details = Some(DETAIL_PERSON_PROCESSING_DISABLED);- apply_token_distinct_id_limits(&limiter, &ctx, &mut events).await;+ apply_token_distinct_id_limits(&limiter, &ctx, None, &mut events).await;// Already-flagged event WAS evaluated against the limiter...assert!(@@ -2514,7 +2522,7 @@ mod tests {events[2].result = EventResult::Drop;events[2].destination = Destination::Drop;- let tally = apply_token_distinct_id_limits(&limiter, &ctx, &mut events).await;+ let tally = apply_token_distinct_id_limits(&limiter, &ctx, None, &mut events).await;let mut seen = calls.lock().unwrap().clone();seen.sort();@@ -2554,7 +2562,7 @@ mod tests {wrapped_event("$pageview", "cool-1"),];- let tally = apply_token_distinct_id_limits(&limiter, &ctx, &mut events).await;+ let tally = apply_token_distinct_id_limits(&limiter, &ctx, None, &mut events).await;assert_eq!(tally,@@ -2566,6 +2574,64 @@ mod tests {);}+ // The hot key is what a customer needs to act on, so it must reach the+ // warning — but only when the batch identifies it unambiguously. With+ // several hot keys any single pick would be arbitrary, so the count stands+ // in for them.+ #[rstest::rstest]+ #[case::one_hot_key(vec!["phc_tok:hot-1"], vec!["hot-1", "hot-1", "cool-1"], 2, 1, Some("hot-1"))]+ #[case::several_hot_keys(vec!["phc_tok:hot-1", "phc_tok:hot-2"], vec!["hot-1", "hot-2", "cool-1"], 2, 2, None)]+ #[tokio::test]+ async fn td_limits_emit_a_warning_naming_the_hot_key(+ #[case] limited_keys: Vec<&str>,+ #[case] distinct_ids: Vec<&str>,+ #[case] expected_count: u64,+ #[case] expected_distinct_id_count: u64,+ #[case] expected_distinct_id: Option<&str>,+ ) {+ let limiter = mock_limiter(limited_keys);+ let ctx = td_context();+ let emitter = CollectingEmitter::default();+ let mut events: Vec<WrappedEvent> = distinct_ids+ .iter()+ .map(|did| wrapped_event("$pageview", did))+ .collect();++ apply_token_distinct_id_limits(&limiter, &ctx, Some(&emitter), &mut events).await;++ let emitted = emitter.emitted();+ assert_eq!(emitted.len(), 1, "one warning per batch, not per event");+ let w = &emitted[0];+ assert_eq!(w.warning, WarningType::HighVolumeDistinctId);+ assert_eq!(w.source, CAPTURE_V1_RATE_LIMIT);+ assert_eq!(w.count, expected_count);+ assert_eq!(+ w.extra_details["distinctIdCount"],+ serde_json::json!(expected_distinct_id_count)+ );+ assert_eq!(+ w.extra_details.get("distinctId").and_then(|v| v.as_str()),+ expected_distinct_id+ );+ // Attribution comes from the request's PostHog-Sdk-Info header.+ assert_eq!(w.extra_details["lib"], serde_json::json!("posthog-rs"));+ assert_eq!(w.extra_details["libVersion"], serde_json::json!("1.0.0"));+ }++ #[tokio::test]+ async fn td_limits_within_the_limit_emit_nothing() {+ // Warnings are for the customer, so a clean batch must stay silent even+ // with the limiter and emitter both wired up.+ let limiter = mock_limiter(vec![]);+ let ctx = td_context();+ let emitter = CollectingEmitter::default();+ let mut events = vec![wrapped_event("$pageview", "user-1")];++ apply_token_distinct_id_limits(&limiter, &ctx, Some(&emitter), &mut events).await;++ assert!(emitter.emitted().is_empty());+ }+#[tokio::test]async fn td_limits_historical_event_not_rerouted_to_overflow() {// Invariant: AnalyticsHistorical must never be rerouted to Overflow.@@ -2578,7 +2644,7 @@ mod tests {vec![wrapped_event("$pageview", "user-1").with_destination(Destination::AnalyticsHistorical)];- apply_token_distinct_id_limits(&limiter, &ctx, &mut events).await;+ apply_token_distinct_id_limits(&limiter, &ctx, None, &mut events).await;let ev = find_by_did(&events, "user-1");assert_eq!(ev.result, EventResult::Warning);@@ -2866,7 +2932,7 @@ mod tests {wrapped_event("$pageview", "user-pos-4"),];- apply_token_distinct_id_limits(&limiter, &ctx, &mut events).await;+ apply_token_distinct_id_limits(&limiter, &ctx, None, &mut events).await;assert_eq!(distinct_id_sequence(&events),@@ -2935,7 +3001,7 @@ mod tests {let mut tdctx = test_utils::test_context();tdctx.api_token = "phc_tok".to_string();let limiter = mock_limiter(vec!["phc_tok:user-pos-2"]);- apply_token_distinct_id_limits(&limiter, &tdctx, &mut events).await;+ apply_token_distinct_id_limits(&limiter, &tdctx, None, &mut events).await;assert_eq!(distinct_id_sequence(&events),expected,diff --git a/rust/capture/src/v1/quota_limiter_shim.rs b/rust/capture/src/v1/quota_limiter_shim.rsindex af84c76f4ffb..d4278d1b6334 100644--- a/rust/capture/src/v1/quota_limiter_shim.rs+++ b/rust/capture/src/v1/quota_limiter_shim.rs@@ -263,9 +263,9 @@ mod tests {capture_ingestion_warnings_enabled: false,capture_ingestion_warnings_kafka_queue_mib: 16,capture_ingestion_warnings_kafka_message_max_bytes: 1048576,- capture_ingestion_warnings_kafka_topic: None,- capture_ingestion_warnings_kafka_hosts: None,- capture_ingestion_warnings_kafka_tls: None,+ capture_ingestion_warnings_kafka_topic: String::new(),+ capture_ingestion_warnings_kafka_hosts: String::new(),+ capture_ingestion_warnings_kafka_tls: false,}}diff --git a/rust/capture/tests/common/utils.rs b/rust/capture/tests/common/utils.rsindex bfae78358288..36a53e885ee5 100644--- a/rust/capture/tests/common/utils.rs+++ b/rust/capture/tests/common/utils.rs@@ -179,9 +179,9 @@ pub static DEFAULT_CONFIG: Lazy<Config> = Lazy::new(|| Config {capture_ingestion_warnings_enabled: false,capture_ingestion_warnings_kafka_queue_mib: 16,capture_ingestion_warnings_kafka_message_max_bytes: 1048576,- capture_ingestion_warnings_kafka_topic: None,- capture_ingestion_warnings_kafka_hosts: None,- capture_ingestion_warnings_kafka_tls: None,+ capture_ingestion_warnings_kafka_topic: String::new(),+ capture_ingestion_warnings_kafka_hosts: String::new(),+ capture_ingestion_warnings_kafka_tls: false,});/// Build the per-sink env snapshot the v1 sink loader expects, with every@@ -258,8 +258,11 @@ impl ServerHandle {let mut config = DEFAULT_CONFIG.clone();config.capture_v1_sinks = "msk".to_string();config.capture_ingestion_warnings_enabled = true;- config.capture_ingestion_warnings_kafka_topic =- Some(warnings_topic.topic_name().to_string());+ // The emitter reads only its own dedicated config now (no v0 KAFKA_*+ // fallback), so point it at the same ephemeral broker as the main sink.+ 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();let sink_env = v1_sink_env_for_topic("msk", topic.topic_name());Self::for_config_with_sink_env(config, sink_env).await}diff --git a/rust/common/ingestion_warnings/src/lib.rs b/rust/common/ingestion_warnings/src/lib.rsindex d8bdc088e8cd..62fa6c5beca4 100644--- a/rust/common/ingestion_warnings/src/lib.rs+++ b/rust/common/ingestion_warnings/src/lib.rs@@ -36,6 +36,7 @@//! `nodejs/src/ingestion/common/steps/event-processing/handle-client-ingestion-warning-step.ts`.pub mod registry;+pub mod request;pub mod serializer;pub mod test_support;pub mod throttle;@@ -52,6 +53,7 @@ use serde_json::{Map, Value};use tracing::warn;pub use registry::WarningType;+pub use request::{emit_request_warning, WarningRequestContext, UNKNOWN_ATTRIBUTION};pub use throttle::{ThrottleDecision, WarningThrottle};/// Counter of emission attempts: labels `type` (warning type), `source`@@ -110,6 +112,24 @@ pub const CAPTURE_V1_ANALYTICS: WarningSource = WarningSource {pipeline_step: "capture_validation",};+/// Capture's v1 analytics per-`(token, distinct_id)` rate limiter.+pub const CAPTURE_V1_RATE_LIMIT: WarningSource = WarningSource {+ service: serializer::SOURCE_CAPTURE,+ path: "v1_analytics",+ pipeline_step: "capture_rate_limit",+};++/// Capture's legacy analytics pipeline (`rust/capture/src/events/analytics.rs`),+/// per-`(token, distinct_id)` rate limiter. Split from the v1 source by `path`+/// because the two pipelines rate-limit at different points in their passes and+/// serve different deployments — the distinction is invisible in the message+/// (both are `capture`) but decides which pipeline's volume a spike belongs to.+pub const CAPTURE_LEGACY_RATE_LIMIT: WarningSource = WarningSource {+ service: serializer::SOURCE_CAPTURE,+ path: "legacy_analytics",+ pipeline_step: "capture_rate_limit",+};+/// 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 f56f4b643338..2723bd79e914 100644--- a/rust/common/ingestion_warnings/src/registry.rs+++ b/rust/common/ingestion_warnings/src/registry.rs@@ -25,9 +25,23 @@include!(concat!(env!("OUT_DIR"), "/warning_types.rs"));impl WarningType {+ /// Types capture emits directly, with no error tag behind them.+ ///+ /// The tag route only reaches conditions capture already models as an+ /// `Error` or a per-event drop detail. Some warnings aren't failures at all:+ /// a rate-limited event is ingested (degraded, not dropped), so there is no+ /// tag to map and inventing one would mean inventing an error that never+ /// gets returned. 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; 1] = [Self::HighVolumeDistinctId];+/// 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 —- /// callers emit nothing in that case.+ /// callers emit nothing in that case. Direct-emit types are deliberately+ /// absent: see [`WarningType::DIRECT_EMIT`].pub fn from_tag(tag: &str) -> Option<Self> {match tag {"missing_event_name" => Some(Self::MissingEventName),@@ -53,21 +67,35 @@ mod tests {use rstest::rstest;#[test]- fn from_tag_domain_equals_the_capture_trust_allowlist() {- // Two hand-maintained copies of "the types capture emits" must stay- // equal: the `from_tag` arms here (the emit allowlist) and the- // registry's `captureProduced` flags (the Node consumer's trust- // allowlist, carried through the artifact). Skew fails silently in- // production in either direction — a flagged type without an arm is- // never emitted; an arm without the flag is emitted and then- // rejected at the consumer's trust check. Comparing the variant- // itself (not just presence) also pins each arm to the right type,- // so a mis-mapped tag can't hide behind an unrelated `Some`.+ fn capture_emit_routes_equal_the_capture_trust_allowlist() {+ // Two hand-maintained answers to "which types does capture emit?" must+ // stay equal: capture's emit routes here (`from_tag` plus+ // `DIRECT_EMIT`) and the registry's `captureProduced` flags (the Node+ // consumer's trust allowlist, carried through the artifact). Skew fails+ // silently in production in either direction — a flagged type on+ // neither route is never emitted; a type on a route without the flag is+ // emitted and then rejected at the consumer's trust check.+ //+ // Comparing the variant itself (not just presence) pins each `from_tag`+ // arm to the right type, so a mis-mapped tag can't hide behind an+ // unrelated `Some`.for warning in WarningType::ALL {+ let tag_derived = WarningType::from_tag(warning.as_str()) == Some(warning);+ let direct = WarningType::DIRECT_EMIT.contains(&warning);+assert_eq!(- WarningType::from_tag(warning.as_str()),- warning.capture_produced().then_some(warning),- "{}: from_tag arm and captureProduced flag disagree — add the missing side",+ tag_derived || direct,+ warning.capture_produced(),+ "{}: emit routes and captureProduced flag disagree — add the missing side",+ warning.as_str()+ );++ // One route per type. Both would mean a warning capture can produce+ // two ways, with the tag route silently winning wherever a tag is+ // available, so its details would differ by call path.+ assert!(+ !(tag_derived && direct),+ "{}: on both emit routes — pick one",warning.as_str());}@@ -91,6 +119,9 @@ mod tests {#[case::sink("rejected")]#[case::unknown("some_future_tag")]#[case::empty("")]+ // Direct-emit types must stay off the tag route even though their name reads+ // like a tag, or they'd be reachable both ways.+ #[case::direct_emit("high_volume_distinct_id")]fn from_tag_rejects_unregistered_tags(#[case] tag: &str) {assert_eq!(WarningType::from_tag(tag),diff --git a/rust/common/ingestion_warnings/src/request.rs b/rust/common/ingestion_warnings/src/request.rsnew file mode 100644index 000000000000..defed1965843--- /dev/null+++ b/rust/common/ingestion_warnings/src/request.rs@@ -0,0 +1,155 @@+//! Request-scoped attribution shared by every warning one request produces.+//!+//! This is the envelope-producer seam: services that know only API tokens+//! (capture) stamp per-request attribution here and emit through+//! [`WarningEmitter`]. Row producers do not belong here — personhog leader+//! commits terminal rows via [`crate::serializer::Warning::into_row`], with a+//! `team_id` and no request behind it.++use serde_json::{Map, Value};++use crate::{WarningEmitter, WarningSource, WarningType};++/// Value stamped for attribution a request genuinely doesn't carry.+///+/// SDK attribution is client-supplied, so any request can omit it: a bare+/// `POST /e/` with no `$lib`, a proxy that strips properties, a batch whose+/// first event is minimal. Emitting the key as `"unknown"` rather than+/// omitting it keeps every warning's payload the same shape, which is what+/// makes the v2 detail columns groupable — `GROUP BY lib` silently loses rows+/// where the key is absent, and a reader can't tell "no SDK reported" from+/// "this emit site forgot to stamp it".+pub const UNKNOWN_ATTRIBUTION: &str = "unknown";++/// Per-request attribution for warnings, resolved once by the caller.+///+/// Fields are plain owned strings, deliberately: each capture path reports SDK+/// identity differently (v1 reads request-level context, the legacy path takes+/// it from the first event of the batch, replay and AI have their own quirks),+/// so normalizing — including substituting [`UNKNOWN_ATTRIBUTION`] — is the+/// caller's job. Keeping `Option` and event introspection out of this crate is+/// what stops it from growing per-caller knowledge of capture's event shapes.+#[derive(Debug, Clone)]+pub struct WarningRequestContext {+ /// The offending event's API token. The consumer resolves it to a team, and+ /// it scopes the emitter's throttle.+ pub token: String,+ /// SDK name, e.g. `web`, `posthog-python`.+ pub lib: String,+ /// SDK version as reported, e.g. `1.234.5`.+ pub lib_version: String,+ /// Request path the warning came in on, e.g. `/i/v0/e/`.+ pub path: String,+}++impl WarningRequestContext {+ /// Attribution as warning details. camelCase to match the v2 `DEFAULT`+ /// extractors' expectations for entity keys.+ fn as_details(&self) -> [(&'static str, &str); 3] {+ [+ ("lib", self.lib.as_str()),+ ("libVersion", self.lib_version.as_str()),+ ("path", self.path.as_str()),+ ]+ }+}++/// Emit one warning with request attribution merged into `extra_details`.+///+/// `emitter` is an `Option` because warnings are opt-in per deployment and+/// every call site would otherwise repeat the same short-circuit; `None` is a+/// no-op, never an error. Attribution keys win over `extra_details` on+/// collision, for the same reason the serializer's injected row keys do: a+/// caller cannot be allowed to misreport where a warning came from.+///+/// Use this for warnings capture emits directly (see+/// [`WarningType::DIRECT_EMIT`]) as well as for tag-derived ones — the route+/// that picks the [`WarningType`] is independent of stamping attribution onto+/// it.+pub fn emit_request_warning(+ emitter: Option<&dyn WarningEmitter>,+ request: &WarningRequestContext,+ source: WarningSource,+ warning: WarningType,+ extra_details: Map<String, Value>,+ count: u64,+) {+ let Some(emitter) = emitter else {+ return;+ };++ let mut details = extra_details;+ for (key, value) in request.as_details() {+ details.insert(key.to_string(), Value::String(value.to_string()));+ }++ emitter.emit(request.token.clone(), source, warning, details, count);+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::test_support::CollectingEmitter;+ use crate::CAPTURE_V1_ANALYTICS;++ fn context() -> WarningRequestContext {+ WarningRequestContext {+ token: "tok".to_string(),+ lib: "web".to_string(),+ lib_version: "1.2.3".to_string(),+ path: "/i/v0/e/".to_string(),+ }+ }++ #[test]+ fn no_emitter_is_a_silent_no_op() {+ // The whole point of the Option: a deployment with warnings off must+ // not need every call site to remember to check.+ emit_request_warning(+ None,+ &context(),+ CAPTURE_V1_ANALYTICS,+ WarningType::HighVolumeDistinctId,+ Map::new(),+ 1,+ );+ }++ #[test]+ fn attribution_is_stamped_and_wins_over_caller_details() {+ let emitter = CollectingEmitter::default();+ let mut extra = Map::new();+ extra.insert("distinctId".to_string(), Value::String("abc".to_string()));+ // A caller trying to relabel where the warning came from must not win.+ extra.insert("lib".to_string(), Value::String("spoofed".to_string()));++ emit_request_warning(+ Some(&emitter),+ &context(),+ CAPTURE_V1_ANALYTICS,+ WarningType::HighVolumeDistinctId,+ extra,+ 7,+ );++ let emitted = emitter.emitted();+ assert_eq!(emitted.len(), 1);+ let w = &emitted[0];+ assert_eq!(w.token, "tok");+ assert_eq!(w.warning, WarningType::HighVolumeDistinctId);+ assert_eq!(w.count, 7);+ assert_eq!(w.extra_details["lib"], Value::String("web".to_string()));+ assert_eq!(+ w.extra_details["libVersion"],+ Value::String("1.2.3".to_string())+ );+ assert_eq!(+ w.extra_details["path"],+ Value::String("/i/v0/e/".to_string())+ );+ assert_eq!(+ w.extra_details["distinctId"],+ Value::String("abc".to_string())+ );+ }+}diff --git a/rust/common/ingestion_warnings/warning_types.generated.json b/rust/common/ingestion_warnings/warning_types.generated.jsonindex 0f0837f2cd22..94c61e6fc9b4 100644--- a/rust/common/ingestion_warnings/warning_types.generated.json+++ b/rust/common/ingestion_warnings/warning_types.generated.json@@ -103,6 +103,12 @@"severity": "error","captureProduced": false},+ {+ "type": "high_volume_distinct_id",+ "category": "quota",+ "severity": "warning",+ "captureProduced": true+ },{"type": "ignored_invalid_timestamp","category": "event",