Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(capture): route $ai events to a configurable topic (#68719)

Paweł Ledwoń5faef44632ee
diff --git a/rust/capture/src/ai_endpoint.rs b/rust/capture/src/ai_endpoint.rs
index b5f250c9086c..3927a21f2a49 100644
--- a/rust/capture/src/ai_endpoint.rs
+++ b/rust/capture/src/ai_endpoint.rs
@@ -443,6 +443,7 @@ async fn ai_handler_inner(
stamp_overflow_reason(
std::slice::from_mut(&mut processed_event),
state.overflow_limiter.as_ref(),
+ state.ai_events_overflow_limiter.as_ref(),
);
// Step 9: Send event to Kafka
diff --git a/rust/capture/src/config.rs b/rust/capture/src/config.rs
index 3611812ab598..5b8eff7b0a59 100644
--- a/rust/capture/src/config.rs
+++ b/rust/capture/src/config.rs
@@ -318,6 +318,20 @@ pub struct Config {
#[envconfig(default = "")]
pub ai_secondary_kafka_client_id: String,
+ // --- Dedicated $ai_* topic routing on analytics deployments ---
+ /// Routing mode for `$ai_*` events into the dedicated AI topic
+ /// (`kafka.capture_analytics_ai_events_topic`, i.e. `CAPTURE_ANALYTICS_AI_EVENTS_TOPIC`): `primary` (default)
+ /// diverts nothing, `secondary` diverts all `$ai_*` events, and
+ /// `secondary_allowlist` diverts only tokens listed in
+ /// `capture_analytics_ai_events_allowlist_tokens`. The topic is required whenever the
+ /// mode is not `primary`.
+ #[envconfig(default = "primary")]
+ pub capture_analytics_ai_events_mode: AiSinkMode,
+
+ /// Comma-separated project API tokens whose `$ai_*` events are diverted to
+ /// `capture_analytics_ai_events_topic` when `capture_analytics_ai_events_mode` is `secondary_allowlist`.
+ pub capture_analytics_ai_events_allowlist_tokens: Option<String>,
+
// HTTP/1 header read timeout in milliseconds - closes connections that don't
// send complete headers within this duration (slow loris protection).
// Set env var to enable; unset to disable.
@@ -422,6 +436,21 @@ pub struct KafkaConfig {
pub kafka_replay_overflow_topic: String,
#[envconfig(default = "events_plugin_ingestion_dlq")]
pub kafka_dlq_topic: String,
+ /// Dedicated Kafka topic for `$ai_*` events (env: `CAPTURE_ANALYTICS_AI_EVENTS_TOPIC`).
+ /// Unlike the `ai_secondary_*` family on `Config` (which picks a secondary
+ /// CLUSTER on `CaptureMode::Ai` deployments), this picks a TOPIC on the
+ /// same sink: per `Config::capture_analytics_ai_events_mode`, both the v0 pipeline
+ /// (via `DataType::AiEvents`) and the v1 pipeline (via
+ /// `Destination::AiEvents`) divert `$ai_*` events here instead of the
+ /// analytics main topic. Setup also injects it into every v1 sink config.
+ pub capture_analytics_ai_events_topic: Option<String>,
+ /// Optional overflow topic for the AI lane (env: `CAPTURE_ANALYTICS_AI_EVENTS_OVERFLOW_TOPIC`).
+ /// Unset means AI events never overflow (the pre-overflow behavior). When
+ /// set, the AI lane participates in the same overflow limiter and
+ /// restriction-driven force_overflow as the analytics main lane, rerouting
+ /// here instead of the analytics overflow topic. Settable in advance of
+ /// the AI routing mode, so no startup validation ties it to the mode.
+ pub capture_analytics_ai_events_overflow_topic: Option<String>,
#[envconfig(default = "false")]
pub kafka_tls: bool,
#[envconfig(default = "")]
@@ -496,9 +525,61 @@ pub struct KafkaConfig {
#[cfg(test)]
mod tests {
- use super::{AiRouting, AiSinkMode};
+ use super::{AiRouting, AiSinkMode, Config};
+ use std::collections::HashMap;
use std::str::FromStr;
+ fn required_config_env() -> HashMap<String, String> {
+ [
+ ("REDIS_URL", "redis://localhost:6379/"),
+ ("KAFKA_HOSTS", "localhost:9092"),
+ ]
+ .into_iter()
+ .map(|(k, v)| (k.to_string(), v.to_string()))
+ .collect()
+ }
+
+ #[test]
+ fn capture_analytics_ai_events_topic_defaults() {
+ let config: Config =
+ envconfig::Envconfig::init_from_hashmap(&required_config_env()).unwrap();
+ assert_eq!(config.kafka.capture_analytics_ai_events_topic, None);
+ assert_eq!(config.capture_analytics_ai_events_mode, AiSinkMode::Primary);
+ assert_eq!(config.capture_analytics_ai_events_allowlist_tokens, None);
+ }
+
+ #[test]
+ fn capture_analytics_ai_events_topic_parses() {
+ let mut env = required_config_env();
+ env.insert(
+ "CAPTURE_ANALYTICS_AI_EVENTS_TOPIC".into(),
+ "ai_events".into(),
+ );
+ env.insert(
+ "CAPTURE_ANALYTICS_AI_EVENTS_MODE".into(),
+ "secondary_allowlist".into(),
+ );
+ env.insert(
+ "CAPTURE_ANALYTICS_AI_EVENTS_ALLOWLIST_TOKENS".into(),
+ "tok_a,tok_b".into(),
+ );
+ let config: Config = envconfig::Envconfig::init_from_hashmap(&env).unwrap();
+ assert_eq!(
+ config.kafka.capture_analytics_ai_events_topic.as_deref(),
+ Some("ai_events")
+ );
+ assert_eq!(
+ config.capture_analytics_ai_events_mode,
+ AiSinkMode::SecondaryAllowlist
+ );
+ assert_eq!(
+ config
+ .capture_analytics_ai_events_allowlist_tokens
+ .as_deref(),
+ Some("tok_a,tok_b")
+ );
+ }
+
#[test]
fn ai_sink_mode_from_str() {
// Locks the AI_SINK_MODE env contract: accepted spellings (incl. the
diff --git a/rust/capture/src/event_restrictions/types.rs b/rust/capture/src/event_restrictions/types.rs
index eb4743eb74a7..72a2c8dda212 100644
--- a/rust/capture/src/event_restrictions/types.rs
+++ b/rust/capture/src/event_restrictions/types.rs
@@ -43,13 +43,14 @@ impl Pipeline {
impl Pipeline {
/// Pipelines a given capture deployment produces events to. The events
- /// deployment writes to both `analytics` (normal events) and
- /// `errortracking` (`$exception` events split off in `process_single_event`),
- /// so its restriction service must serve restrictions for both pipelines.
+ /// deployment writes to `analytics` (normal events), `errortracking`
+ /// (`$exception` events split off in `process_single_event`), and `ai`
+ /// (`$ai_*` events diverted by the `AiRouting` policy), so its restriction
+ /// service must serve restrictions for all three pipelines.
/// Other deployments serve their single pipeline.
pub fn for_capture_mode(mode: CaptureMode) -> Vec<Pipeline> {
match mode {
- CaptureMode::Events => vec![Self::Analytics, Self::ErrorTracking],
+ CaptureMode::Events => vec![Self::Analytics, Self::ErrorTracking, Self::Ai],
CaptureMode::Recordings => vec![Self::SessionRecordings],
CaptureMode::Ai => vec![Self::Ai],
}
@@ -381,7 +382,7 @@ mod tests {
fn test_pipeline_for_capture_mode() {
assert_eq!(
Pipeline::for_capture_mode(CaptureMode::Events),
- vec![Pipeline::Analytics, Pipeline::ErrorTracking]
+ vec![Pipeline::Analytics, Pipeline::ErrorTracking, Pipeline::Ai]
);
assert_eq!(
Pipeline::for_capture_mode(CaptureMode::Recordings),
diff --git a/rust/capture/src/events/analytics.rs b/rust/capture/src/events/analytics.rs
index ebd2cec52f81..65f71bcb4aa6 100644
--- a/rust/capture/src/events/analytics.rs
+++ b/rust/capture/src/events/analytics.rs
@@ -17,6 +17,7 @@ use limiters::overflow::OverflowLimiter;
use crate::{
api::CaptureError,
+ config::AiRouting,
debug_or_info,
event_restrictions::{EventContext as RestrictionEventContext, EventRestrictionService},
events::overflow_stamping::stamp_overflow_reason,
@@ -74,6 +75,9 @@ fn create_heatmap_redirect(
historical_cfg: router::HistoricalConfig,
context: &ProcessingContext,
) -> Result<Option<ProcessedEvent>, CaptureError> {
+ // The redirect is always a `$$heatmap` event, so AI routing can never
+ // apply to it; hardcode the flag off instead of threading it through.
+ let route_ai_events = false;
let Some(distinct_id) = event.extract_distinct_id() else {
return Ok(None);
};
@@ -103,14 +107,19 @@ fn create_heatmap_redirect(
set_once: None,
};
- process_single_event(&heatmap_event, historical_cfg, context).map(Some)
+ process_single_event(&heatmap_event, historical_cfg, route_ai_events, context).map(Some)
}
-/// Process a single analytics event from RawEvent to ProcessedEvent
+/// Process a single analytics event from RawEvent to ProcessedEvent.
+///
+/// `route_ai_events` is the per-batch `AiRouting` decision (see
+/// `process_events`); when set, `$ai_*` events classify as
+/// `DataType::AiEvents` instead of the analytics main/historical lanes.
#[instrument(skip_all, fields(event_name, request_id))]
pub fn process_single_event(
event: &RawEvent,
historical_cfg: router::HistoricalConfig,
+ route_ai_events: bool,
context: &ProcessingContext,
) -> Result<ProcessedEvent, CaptureError> {
if event.event.is_empty() {
@@ -120,7 +129,8 @@ pub fn process_single_event(
Span::current().record("is_mirror_deploy", context.is_mirror_deploy);
Span::current().record("request_id", &context.request_id);
- let data_type = DataType::from_event_name(&event.event, context.historical_migration);
+ let data_type =
+ DataType::from_event_name(&event.event, context.historical_migration, route_ai_events);
// Redact the IP address of internally-generated events when tagged as such
let resolved_ip = if event.properties.contains_key("capture_internal") {
@@ -209,16 +219,18 @@ pub fn process_single_event(
/// Process a batch of analytics events.
///
-/// All routing policy lives here: token dropping, event restrictions, global
+/// All routing policy lives here: token dropping, `$ai_*` lane assignment
+/// (per the deployment-level [`AiRouting`] policy, resolved into
+/// `DataType::AiEvents` at classification time), event restrictions, global
/// rate limiting (per `token:distinct_id`), historical rerouting, and
/// per-key overflow rerouting via [`OverflowLimiter`]. Overflow stamping
/// goes through the shared [`stamp_overflow_reason`] helper, which the AI
/// (`ai_endpoint::ai_handler`) and OTEL (`otel::otel_handler`) paths also
/// call so every `DataType::AnalyticsMain` event gets identical limiter
/// semantics regardless of entry point. The kafka sink is a pure mechanism
-/// layer — it reads `ProcessedEventMetadata::overflow_reason`,
-/// `force_overflow`, `redirect_to_dlq`, and `redirect_to_topic` to decide
-/// which topic and key to produce to.
+/// layer — it reads `ProcessedEventMetadata::data_type`,
+/// `overflow_reason`, `force_overflow`, `redirect_to_dlq`, and
+/// `redirect_to_topic` to decide which topic and key to produce to.
#[instrument(skip_all, fields(events = events.len(), request_id))]
#[allow(clippy::too_many_arguments)]
pub async fn process_events(
@@ -228,6 +240,8 @@ pub async fn process_events(
historical_cfg: router::HistoricalConfig,
global_rate_limiter: Option<Arc<GlobalRateLimiter>>,
overflow_limiter: Option<Arc<OverflowLimiter>>,
+ ai_events_overflow_limiter: Option<Arc<OverflowLimiter>>,
+ ai_routing: &AiRouting,
events: Vec<RawEvent>,
context: &ProcessingContext,
) -> Result<(), CaptureError> {
@@ -236,6 +250,12 @@ pub async fn process_events(
Span::current().record("request_id", &context.request_id);
Span::current().record("is_mirror_deploy", context.is_mirror_deploy);
+ // A request carries a single token, so the `$ai_*` lane decision is per
+ // batch, mirroring v1's `process_batch`. The flag feeds
+ // `DataType::from_event_name` via `process_single_event`; the kafka sink
+ // maps the resulting `DataType::AiEvents` to `CAPTURE_ANALYTICS_AI_EVENTS_TOPIC`.
+ let route_ai_events = ai_routing.routes_to_secondary(&context.token);
+
// Build the processed batch one raw event at a time so we can split a
// heatmap-carrying event into a stripped original + a `$$heatmap`
// redirect *before* serialization happens inside `process_single_event`.
@@ -249,23 +269,38 @@ pub async fn process_events(
let mut events: Vec<ProcessedEvent> = Vec::with_capacity(raw_events.len());
for mut raw in raw_events {
if raw.event == "$$heatmap" || !has_heatmap_data(&raw) {
- events.push(process_single_event(&raw, historical_cfg, context)?);
+ events.push(process_single_event(
+ &raw,
+ historical_cfg,
+ route_ai_events,
+ context,
+ )?);
continue;
}
let redirect = match create_heatmap_redirect(&raw, historical_cfg, context) {
Ok(Some(redirect)) => redirect,
Ok(None) => {
- events.push(process_single_event(&raw, historical_cfg, context)?);
+ events.push(process_single_event(
+ &raw,
+ historical_cfg,
+ route_ai_events,
+ context,
+ )?);
continue;
}
Err(err) => {
error!("failed to create heatmap redirect: {err:#}");
- events.push(process_single_event(&raw, historical_cfg, context)?);
+ events.push(process_single_event(
+ &raw,
+ historical_cfg,
+ route_ai_events,
+ context,
+ )?);
continue;
}
};
raw.properties.remove("$heatmap_data");
- let mut processed = process_single_event(&raw, historical_cfg, context)?;
+ let mut processed = process_single_event(&raw, historical_cfg, route_ai_events, context)?;
processed.metadata.skip_heatmap_processing = true;
events.push(processed);
counter!("capture_heatmap_redirects_created").increment(1);
@@ -292,7 +327,10 @@ pub async fn process_events(
// tagged only for `analytics` will never silently drop an exception event
// on the way to the error tracking topic, and vice versa. Data types
// without a pipeline (heatmaps, ingestion warnings, snapshots) flow
- // through unrestricted.
+ // through unrestricted. `AiEvents` looks up the `ai` pipeline: a diverted
+ // AI event is governed by ai-scoped restrictions (drop/DLQ/redirect still
+ // win over the lane, redirect_to_topic beats the AI topic in the sink,
+ // force_overflow keeps it on the AI lane) -- mirroring v1.
if let Some(ref service) = restriction_service {
let mut filtered_events = Vec::with_capacity(events.len());
let now_ts = context.now.timestamp();
@@ -348,7 +386,9 @@ pub async fn process_events(
if limiter.is_limited(&cache_key, 1).await.is_some() {
event.metadata.skip_person_processing = true;
// Reroute the hot key to overflow. AnalyticsMain only: historical
- // never overflows and only AnalyticsMain acts on overflow_reason.
+ // never overflows, the AI lane keeps its dedicated topic (v1
+ // gates the same way on Destination::AnalyticsMain), and only
+ // AnalyticsMain acts on overflow_reason.
if event.metadata.data_type == DataType::AnalyticsMain {
event.metadata.overflow_reason = Some(OverflowReason::ForceLimited);
}
@@ -385,7 +425,11 @@ pub async fn process_events(
// and OTEL (`otel::otel_handler`) paths so every handler that emits
// `DataType::AnalyticsMain` events gets identical limiter semantics and
// metric labels — see `events::overflow_stamping`.
- stamp_overflow_reason(&mut events, overflow_limiter.as_ref());
+ stamp_overflow_reason(
+ &mut events,
+ overflow_limiter.as_ref(),
+ ai_events_overflow_limiter.as_ref(),
+ );
if events.is_empty() {
return Ok(());
@@ -488,7 +532,7 @@ mod tests {
};
let historical_cfg = router::HistoricalConfig::new(false, 1);
- let processed = process_single_event(&event, historical_cfg, &context).unwrap();
+ let processed = process_single_event(&event, historical_cfg, false, &context).unwrap();
let expected_millis = processed
.metadata
@@ -524,7 +568,7 @@ mod tests {
};
let historical_cfg = router::HistoricalConfig::new(false, 1);
- let processed = process_single_event(&event, historical_cfg, &context).unwrap();
+ let processed = process_single_event(&event, historical_cfg, false, &context).unwrap();
// The event keeps its pre-epoch timestamp, but the uuid floors to the epoch rather than wrapping to garbage.
assert!(
@@ -547,7 +591,7 @@ mod tests {
let context = create_test_context(now, None);
let event = create_test_event(Some("2023-01-01T11:00:00Z".to_string()), None, None);
let historical_cfg = router::HistoricalConfig::new(false, 1);
- let result = process_single_event(&event, historical_cfg, &context);
+ let result = process_single_event(&event, historical_cfg, false, &context);
assert!(result.is_ok());
let processed = result.unwrap();
@@ -573,7 +617,7 @@ mod tests {
let event = create_test_event(Some("2023-01-01T11:59:55Z".to_string()), None, None);
let historical_cfg = router::HistoricalConfig::new(false, 1);
- let result = process_single_event(&event, historical_cfg, &context);
+ let result = process_single_event(&event, historical_cfg, false, &context);
assert!(result.is_ok());
let processed = result.unwrap();
@@ -597,7 +641,7 @@ mod tests {
let event = create_test_event(Some("2023-01-01T11:00:00Z".to_string()), None, Some(true));
let historical_cfg = router::HistoricalConfig::new(false, 1);
- let result = process_single_event(&event, historical_cfg, &context);
+ let result = process_single_event(&event, historical_cfg, false, &context);
assert!(result.is_ok());
let processed = result.unwrap();
@@ -620,7 +664,7 @@ mod tests {
let event = create_test_event(Some("2023-01-01T11:00:00Z".to_string()), None, None);
let historical_cfg = router::HistoricalConfig::new(false, 1);
- let result = process_single_event(&event, historical_cfg, &context);
+ let result = process_single_event(&event, historical_cfg, false, &context);
assert!(result.is_ok());
let processed = result.unwrap();
@@ -641,7 +685,7 @@ mod tests {
let event = create_test_event(Some("2023-01-01T11:00:00Z".to_string()), None, None);
let historical_cfg = router::HistoricalConfig::new(false, 1);
- let result = process_single_event(&event, historical_cfg, &context);
+ let result = process_single_event(&event, historical_cfg, false, &context);
assert!(result.is_ok());
let processed = result.unwrap();
@@ -697,6 +741,8 @@ mod tests {
historical_cfg,
None,
None,
+ None,
+ &AiRouting::Primary,
events,
&context,
)
@@ -745,6 +791,8 @@ mod tests {
historical_cfg,
None,
None,
+ None,
+ &AiRouting::Primary,
events,
&context,
)
@@ -794,6 +842,8 @@ mod tests {
historical_cfg,
None,
None,
+ None,
+ &AiRouting::Primary,
events,
&context,
)
@@ -843,6 +893,8 @@ mod tests {
historical_cfg,
None,
None,
+ None,
+ &AiRouting::Primary,
events,
&context,
)
@@ -899,6 +951,8 @@ mod tests {
historical_cfg,
None,
None,
+ None,
+ &AiRouting::Primary,
events,
&context,
)
@@ -935,6 +989,8 @@ mod tests {
historical_cfg,
None,
None,
+ None,
+ &AiRouting::Primary,
events,
&context,
)
@@ -989,6 +1045,8 @@ mod tests {
historical_cfg,
None,
None,
+ None,
+ &AiRouting::Primary,
events,
&context,
)
@@ -1037,6 +1095,8 @@ mod tests {
historical_cfg,
None,
None,
+ None,
+ &AiRouting::Primary,
events,
&context,
)
@@ -1051,6 +1111,217 @@ mod tests {
);
}
+ /// The `$ai_*` lane assignment is decided once per batch from the request
+ /// token: `secondary` diverts every `$ai_*` event, an allowlist diverts
+ /// only listed tokens, and `primary` never diverts. Non-AI events stay on
+ /// their normal route in every mode. The topic itself is resolved in the
+ /// kafka sink from `DataType::AiEvents`, not here.
+ #[rstest]
+ #[case::secondary(AiRouting::Secondary, true)]
+ #[case::allowlisted_token(
+ AiRouting::SecondaryAllowlist(["test_token".to_string()].into_iter().collect()),
+ true
+ )]
+ #[case::unlisted_token(
+ AiRouting::SecondaryAllowlist(["other_token".to_string()].into_iter().collect()),
+ false
+ )]
+ #[case::primary(AiRouting::Primary, false)]
+ #[tokio::test]
+ async fn test_process_events_ai_lane_assignment(
+ #[case] routing: AiRouting,
+ #[case] expect_diverted: bool,
+ ) {
+ 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_with_name(
+ "$ai_generation",
+ Some("2023-01-01T11:00:00Z".to_string()),
+ None,
+ None,
+ ),
+ create_test_event_with_name(
+ "$pageview",
+ Some("2023-01-01T11:00:00Z".to_string()),
+ None,
+ None,
+ ),
+ ];
+
+ let sink = Arc::new(MockSink::new());
+ let dropper = Arc::new(limiters::token_dropper::TokenDropper::default());
+ let historical_cfg = router::HistoricalConfig::new(false, 1);
+
+ process_events(
+ sink.clone(),
+ dropper,
+ None,
+ historical_cfg,
+ None,
+ None,
+ None,
+ &routing,
+ events,
+ &context,
+ )
+ .await
+ .unwrap();
+
+ let captured = sink.get_events();
+ assert_eq!(captured.len(), 2);
+ let ai_event = captured
+ .iter()
+ .find(|e| e.event.event == "$ai_generation")
+ .unwrap();
+ let expected = if expect_diverted {
+ DataType::AiEvents
+ } else {
+ DataType::AnalyticsMain
+ };
+ assert_eq!(ai_event.metadata.data_type, expected);
+ // Lane assignment must not leak into the restriction-driven redirect
+ // mechanism; the sink resolves the AI topic from the data type alone.
+ assert_eq!(ai_event.metadata.redirect_to_topic, None);
+ let pageview = captured
+ .iter()
+ .find(|e| e.event.event == "$pageview")
+ .unwrap();
+ assert_eq!(pageview.metadata.data_type, DataType::AnalyticsMain);
+ assert_eq!(pageview.metadata.redirect_to_topic, None);
+ }
+
+ /// A diverted `$ai_*` event is governed by ai-scoped restrictions (the
+ /// same slice the dedicated AI endpoints consult), not analytics ones:
+ /// an ai-scoped DropEvent drops it, an analytics-scoped one must not
+ /// cross pipelines into the AI lane.
+ #[rstest]
+ #[case::ai_scoped_drop_applies(Pipeline::Ai, true)]
+ #[case::analytics_scoped_drop_does_not_cross(Pipeline::Analytics, false)]
+ #[tokio::test]
+ async fn test_process_events_drop_restriction_on_diverted_ai_events(
+ #[case] restriction_pipeline: Pipeline,
+ #[case] expect_dropped: bool,
+ ) {
+ 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_with_name(
+ "$ai_generation",
+ 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 service = EventRestrictionService::new(
+ vec![Pipeline::Analytics, Pipeline::Ai],
+ Duration::from_secs(300),
+ );
+ let mut manager = RestrictionManager::new();
+ manager.insert_restrictions(
+ restriction_pipeline,
+ "test_token",
+ vec![Restriction {
+ restriction_type: RestrictionType::DropEvent,
+ scope: RestrictionScope::AllEvents,
+ args: None,
+ }],
+ );
+ service.update(manager).await;
+
+ process_events(
+ sink.clone(),
+ dropper,
+ Some(service),
+ historical_cfg,
+ None,
+ None,
+ None,
+ &AiRouting::Secondary,
+ events,
+ &context,
+ )
+ .await
+ .unwrap();
+
+ let captured = sink.get_events();
+ if expect_dropped {
+ assert!(captured.is_empty());
+ } else {
+ assert_eq!(captured.len(), 1);
+ assert_eq!(captured[0].metadata.data_type, DataType::AiEvents);
+ }
+ }
+
+ /// An ai-scoped RedirectToTopic applies to a diverted `$ai_*` event: the
+ /// event keeps its AI lane, but the stamped redirect beats the data type
+ /// in the sink so operators can reroute an AI token's traffic ad hoc,
+ /// matching v1 where the restriction overwrites `Destination::AiEvents`
+ /// with `Destination::Custom`.
+ #[tokio::test]
+ async fn test_process_events_restriction_redirect_applies_to_ai_events() {
+ 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_with_name(
+ "$ai_generation",
+ 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 service = EventRestrictionService::new(
+ vec![Pipeline::Analytics, Pipeline::Ai],
+ Duration::from_secs(300),
+ );
+ let mut manager = RestrictionManager::new();
+ manager.insert_restrictions(
+ Pipeline::Ai,
+ "test_token",
+ vec![Restriction {
+ restriction_type: RestrictionType::RedirectToTopic,
+ scope: RestrictionScope::AllEvents,
+ args: Some(json!({"topic": "custom_events_topic"})),
+ }],
+ );
+ service.update(manager).await;
+
+ process_events(
+ sink.clone(),
+ dropper,
+ Some(service),
+ historical_cfg,
+ None,
+ None,
+ None,
+ &AiRouting::Secondary,
+ events,
+ &context,
+ )
+ .await
+ .unwrap();
+
+ let captured = sink.get_events();
+ assert_eq!(captured.len(), 1);
+ assert_eq!(captured[0].metadata.data_type, DataType::AiEvents);
+ assert_eq!(
+ captured[0].metadata.redirect_to_topic,
+ Some("custom_events_topic".to_string())
+ );
+ }
+
// ============ non-analytics data types bypass restrictions ============
// The `EventRestrictionService` in analytics handlers is scoped to the
// analytics pipeline. Events whose `data_type` belongs to a different
@@ -1095,6 +1366,8 @@ mod tests {
historical_cfg,
None,
None,
+ None,
+ &AiRouting::Primary,
events,
&context,
)
@@ -1168,6 +1441,8 @@ mod tests {
historical_cfg,
None,
None,
+ None,
+ &AiRouting::Primary,
events,
&context,
)
@@ -1240,6 +1515,8 @@ mod tests {
historical_cfg,
None,
None,
+ None,
+ &AiRouting::Primary,
events,
&context,
)
@@ -1307,6 +1584,8 @@ mod tests {
historical_cfg,
None,
None,
+ None,
+ &AiRouting::Primary,
events,
&context,
)
@@ -1366,6 +1645,8 @@ mod tests {
historical_cfg,
None,
None,
+ None,
+ &AiRouting::Primary,
events,
&context,
)
@@ -1419,6 +1700,8 @@ mod tests {
historical_cfg,
None,
None, // no overflow limiter
+ None,
+ &AiRouting::Primary,
events,
&context,
)
@@ -1455,6 +1738,8 @@ mod tests {
historical_cfg,
None,
Some(limiter),
+ None,
+ &AiRouting::Primary,
events,
&context,
)
@@ -1469,6 +1754,56 @@ mod tests {
);
}
+ /// End-to-end gate for the AI overflow valve: a diverted `$ai_*` event
+ /// is overflow-stamped only when the AI limiter is wired (setup builds
+ /// it exactly when `CAPTURE_ANALYTICS_AI_EVENTS_OVERFLOW_TOPIC` is
+ /// configured), and keeps its AI lane either way.
+ #[rstest]
+ #[case::limiter_present(true, Some(OverflowReason::ForceLimited))]
+ #[case::limiter_absent(false, None)]
+ #[tokio::test]
+ async fn test_ai_events_overflow_stamp_gated_on_limiter_presence(
+ #[case] ai_limiter_present: bool,
+ #[case] expected_reason: Option<OverflowReason>,
+ ) {
+ 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_with_name(
+ "$ai_generation",
+ 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 ai_limiter = ai_limiter_present
+ .then(|| build_limiter(10, 10, Some("test_token".to_string()), false));
+
+ process_events(
+ sink.clone(),
+ dropper,
+ None,
+ historical_cfg,
+ None,
+ None,
+ ai_limiter,
+ &AiRouting::Secondary,
+ events,
+ &context,
+ )
+ .await
+ .unwrap();
+
+ let captured = sink.get_events();
+ assert_eq!(captured.len(), 1);
+ assert_eq!(captured[0].metadata.data_type, DataType::AiEvents);
+ assert_eq!(captured[0].metadata.overflow_reason, expected_reason);
+ }
+
#[tokio::test]
async fn test_overflow_stamp_rate_limited_when_burst_exceeded() {
let now = DateTime::parse_from_rfc3339("2023-01-01T12:00:00Z")
@@ -1493,6 +1828,8 @@ mod tests {
historical_cfg,
None,
Some(limiter),
+ None,
+ &AiRouting::Primary,
events,
&context,
)
@@ -1533,6 +1870,8 @@ mod tests {
historical_cfg,
None,
Some(limiter),
+ None,
+ &AiRouting::Primary,
events,
&context,
)
@@ -1590,6 +1929,8 @@ mod tests {
historical_cfg,
None,
Some(limiter),
+ None,
+ &AiRouting::Primary,
events,
&context,
)
@@ -1629,6 +1970,8 @@ mod tests {
historical_cfg,
None,
Some(limiter),
+ None,
+ &AiRouting::Primary,
events,
&context,
)
@@ -1680,6 +2023,8 @@ mod tests {
historical_cfg,
Some(global_limiter),
Some(overflow_limiter),
+ None,
+ &AiRouting::Primary,
events,
&context,
)
@@ -1743,6 +2088,8 @@ mod tests {
historical_cfg,
Some(global_limiter),
None, // no overflow limiter -- isolate global RL behavior
+ None,
+ &AiRouting::Primary,
events,
&context,
)
@@ -1787,6 +2134,8 @@ mod tests {
historical_cfg,
Some(global_limiter),
None, // no overflow limiter -- isolate global RL behavior
+ None,
+ &AiRouting::Primary,
events,
&context,
)
@@ -1843,6 +2192,8 @@ mod tests {
historical_cfg,
None,
Some(limiter),
+ None,
+ &AiRouting::Primary,
events,
&context,
)
@@ -1894,6 +2245,8 @@ mod tests {
historical_cfg,
None,
Some(limiter),
+ None,
+ &AiRouting::Primary,
events,
&context,
)
@@ -1948,6 +2301,8 @@ mod tests {
historical_cfg,
None,
Some(limiter),
+ None,
+ &AiRouting::Primary,
events,
&context,
)
@@ -2193,6 +2548,8 @@ mod tests {
historical_cfg,
None,
None,
+ None,
+ &AiRouting::Primary,
events,
&context,
)
@@ -2241,6 +2598,8 @@ mod tests {
historical_cfg,
None,
None,
+ None,
+ &AiRouting::Primary,
events,
&context,
)
@@ -2278,6 +2637,8 @@ mod tests {
historical_cfg,
None,
None,
+ None,
+ &AiRouting::Primary,
events,
&context,
)
@@ -2323,6 +2684,8 @@ mod tests {
historical_cfg,
None,
None,
+ None,
+ &AiRouting::Primary,
events,
&context,
)
diff --git a/rust/capture/src/events/overflow_stamping.rs b/rust/capture/src/events/overflow_stamping.rs
index 4fae22ea2c3c..ed84ebda081d 100644
--- a/rust/capture/src/events/overflow_stamping.rs
+++ b/rust/capture/src/events/overflow_stamping.rs
@@ -26,22 +26,42 @@ use metrics::counter;
use crate::v0_request::{DataType, OverflowReason, ProcessedEvent};
-/// Stamp `ProcessedEventMetadata::overflow_reason` on every
-/// `DataType::AnalyticsMain` event in `events`, consulting `limiter` and the
-/// pre-existing `force_overflow` flag stamped by event restrictions.
+/// Stamp `ProcessedEventMetadata::overflow_reason` on every overflowing-lane
+/// event in `events`, consulting the lane's limiter and the pre-existing
+/// `force_overflow` flag stamped by event restrictions.
+///
+/// Two lanes can overflow: `AnalyticsMain` always, and `AiEvents` only when
+/// its limiter is present — setup builds `ai_limiter` exactly when the AI
+/// overflow valve (`CAPTURE_ANALYTICS_AI_EVENTS_OVERFLOW_TOPIC`) is armed and
+/// overflow is enabled, so limiter presence IS the valve here; the kafka sink
+/// independently ignores overflow stamps on the AI lane when the topic is
+/// unset. Each lane consults its own limiter instance — `analytics_limiter`
+/// for `AnalyticsMain`, `ai_limiter` for `AiEvents` — so per-key budgets are
+/// isolated: analytics volume never pushes a key's AI events into AI overflow
+/// and vice versa. The stamp carries no topic; the kafka sink maps it to the
+/// lane's own overflow topic, so an overflowing AI event lands on AI
+/// overflow, never analytics overflow.
///
/// Behavior (matches the pre-refactor sink semantics byte-for-byte):
-/// * Non-`AnalyticsMain` events are skipped (heatmaps, exceptions,
+/// * Events on non-overflowing lanes are skipped (heatmaps, exceptions,
/// client-ingestion-warnings, etc. never overflow).
/// * `force_overflow = true` (set upstream by event restrictions) emits the
/// `event_restriction` counter and short-circuits — the limiter is NOT
-/// consulted, matching the pre-refactor sink ordering.
-/// * If `limiter` is `None`, only the `event_restriction` short-circuit can
-/// stamp anything; otherwise the event passes through untouched.
-/// * If `limiter` is `Some`, `is_limited(event.key())` is consulted and the
-/// resulting [`OverflowReason`] is stamped, plus the matching counter.
-/// `ForceLimited` additionally sets `skip_person_processing = true` so the
-/// sink's generic skip-person branch picks up the
+/// consulted, matching the pre-refactor sink ordering. This runs on both
+/// overflowing lanes regardless of limiter presence: the sink honors
+/// `force_overflow` on its own (restriction rerouting must survive
+/// `OVERFLOW_ENABLED=false`). The counter can over-report in one corner —
+/// a forced AI event with the valve unarmed is counted here but ignored by
+/// the sink; only the sink knows the valve.
+/// * If the lane's limiter is `None`, only the `event_restriction`
+/// short-circuit can stamp anything; otherwise the event passes through
+/// untouched. The AI lane's limiter exists exactly when the AI overflow
+/// valve is armed and overflow is enabled, so absence keeps AI events out
+/// of rate-limit overflow.
+/// * If the lane's limiter is `Some`, `is_limited(event.key())` is consulted
+/// and the resulting [`OverflowReason`] is stamped, plus the matching
+/// counter. `ForceLimited` additionally sets `skip_person_processing =
+/// true` so the sink's generic skip-person branch picks up the
/// `force_disable_person_processing` header without a separate code path.
///
/// Counter labels are intentionally identical to the pre-refactor sink so
@@ -49,12 +69,15 @@ use crate::v0_request::{DataType, OverflowReason, ProcessedEvent};
/// `reason` label) keep working without dashboard-side changes.
pub fn stamp_overflow_reason(
events: &mut [ProcessedEvent],
- limiter: Option<&Arc<OverflowLimiter>>,
+ analytics_limiter: Option<&Arc<OverflowLimiter>>,
+ ai_limiter: Option<&Arc<OverflowLimiter>>,
) {
for event in events.iter_mut() {
- if event.metadata.data_type != DataType::AnalyticsMain {
- continue;
- }
+ let lane_limiter = match event.metadata.data_type {
+ DataType::AnalyticsMain => analytics_limiter,
+ DataType::AiEvents => ai_limiter,
+ _ => continue,
+ };
if event.metadata.force_overflow {
counter!(
@@ -65,7 +88,7 @@ pub fn stamp_overflow_reason(
continue;
}
- let Some(limiter) = limiter else {
+ let Some(limiter) = lane_limiter else {
continue;
};
@@ -176,7 +199,7 @@ mod tests {
true, // force_overflow
)];
- stamp_overflow_reason(&mut events, Some(&limiter));
+ stamp_overflow_reason(&mut events, Some(&limiter), None);
assert_eq!(
events[0].metadata.overflow_reason, None,
@@ -193,7 +216,7 @@ mod tests {
let limiter = build_limiter(10, 10, Some("phc_t:user".to_string()), false);
let mut events = vec![build_event(DataType::AnalyticsMain, "phc_t", "user", false)];
- stamp_overflow_reason(&mut events, Some(&limiter));
+ stamp_overflow_reason(&mut events, Some(&limiter), None);
assert_eq!(
events[0].metadata.overflow_reason,
@@ -215,7 +238,7 @@ mod tests {
build_event(DataType::AnalyticsMain, "phc_t", "u", false),
];
- stamp_overflow_reason(&mut events, Some(&limiter));
+ stamp_overflow_reason(&mut events, Some(&limiter), None);
assert_eq!(
events[0].metadata.overflow_reason, None,
@@ -241,7 +264,7 @@ mod tests {
build_event(DataType::AnalyticsMain, "phc_t", "u", false),
];
- stamp_overflow_reason(&mut events, Some(&limiter));
+ stamp_overflow_reason(&mut events, Some(&limiter), None);
assert_eq!(
events[1].metadata.overflow_reason,
@@ -257,7 +280,7 @@ mod tests {
let limiter = build_limiter(10, 10, None, false);
let mut events = vec![build_event(DataType::AnalyticsMain, "phc_t", "u", false)];
- stamp_overflow_reason(&mut events, Some(&limiter));
+ stamp_overflow_reason(&mut events, Some(&limiter), None);
assert_eq!(events[0].metadata.overflow_reason, None);
}
@@ -265,9 +288,10 @@ mod tests {
#[test]
fn non_analytics_main_events_are_skipped() {
// SnapshotMain has its own (replay) overflow path; HeatmapMain,
- // ExceptionErrorTracking, ClientIngestionWarning, AnalyticsHistorical
- // never overflow. Even with a limiter that would otherwise force-route
- // their key, the helper must leave them untouched.
+ // ExceptionErrorTracking, ClientIngestionWarning, AnalyticsHistorical,
+ // and AiEvents (with the AI overflow valve unarmed) never overflow.
+ // Even with a limiter that would otherwise force-route their key, the
+ // helper must leave them untouched.
let limiter = build_limiter(10, 10, Some("phc_t:u".to_string()), false);
let mut events = vec![
build_event(DataType::SnapshotMain, "phc_t", "u", false),
@@ -275,9 +299,10 @@ mod tests {
build_event(DataType::ExceptionErrorTracking, "phc_t", "u", false),
build_event(DataType::ClientIngestionWarning, "phc_t", "u", false),
build_event(DataType::AnalyticsHistorical, "phc_t", "u", false),
+ build_event(DataType::AiEvents, "phc_t", "u", false),
];
- stamp_overflow_reason(&mut events, Some(&limiter));
+ stamp_overflow_reason(&mut events, Some(&limiter), None);
for (i, ev) in events.iter().enumerate() {
assert_eq!(
@@ -293,7 +318,7 @@ mod tests {
fn none_limiter_is_a_no_op_for_non_force_overflow_events() {
let mut events = vec![build_event(DataType::AnalyticsMain, "phc_t", "u", false)];
- stamp_overflow_reason(&mut events, None);
+ stamp_overflow_reason(&mut events, None, None);
assert_eq!(events[0].metadata.overflow_reason, None);
assert!(!events[0].metadata.skip_person_processing);
@@ -306,7 +331,7 @@ mod tests {
// counter) even when the limiter is absent.
let mut events = vec![build_event(DataType::AnalyticsMain, "phc_t", "u", true)];
- stamp_overflow_reason(&mut events, None);
+ stamp_overflow_reason(&mut events, None, None);
assert_eq!(
events[0].metadata.overflow_reason, None,
@@ -318,7 +343,7 @@ mod tests {
fn empty_batch_is_a_no_op() {
let limiter = build_limiter(10, 10, None, false);
let mut events: Vec<ProcessedEvent> = Vec::new();
- stamp_overflow_reason(&mut events, Some(&limiter));
+ stamp_overflow_reason(&mut events, Some(&limiter), None);
}
#[test]
@@ -333,7 +358,7 @@ mod tests {
build_event(DataType::AnalyticsMain, "phc_t", "user_a", false),
];
- stamp_overflow_reason(&mut events, Some(&limiter));
+ stamp_overflow_reason(&mut events, Some(&limiter), None);
assert_eq!(
events[0].metadata.overflow_reason, None,
@@ -351,4 +376,112 @@ mod tests {
"second AnalyticsMain over budget"
);
}
+
+ /// The AI lane joins overflow stamping only when its limiter is present
+ /// (setup builds it exactly when the AI overflow valve is armed); absent
+ /// keeps today's never-overflows behavior even for a force-routed key.
+ #[rstest::rstest]
+ #[case::limiter_present(true, Some(OverflowReason::ForceLimited), true)]
+ #[case::limiter_absent(false, None, false)]
+ fn ai_events_stamping_gated_on_limiter_presence(
+ #[case] ai_limiter_present: bool,
+ #[case] expected_reason: Option<OverflowReason>,
+ #[case] expected_skip_person: bool,
+ ) {
+ let limiter = build_limiter(10, 10, Some("phc_t:u".to_string()), false);
+ let ai_limiter = ai_limiter_present.then_some(&limiter);
+ let mut events = vec![build_event(DataType::AiEvents, "phc_t", "u", false)];
+
+ stamp_overflow_reason(&mut events, None, ai_limiter);
+
+ assert_eq!(events[0].metadata.overflow_reason, expected_reason);
+ assert_eq!(
+ events[0].metadata.skip_person_processing,
+ expected_skip_person
+ );
+ }
+
+ #[test]
+ fn ai_events_rate_limited_mirrors_preserve_locality() {
+ // The AI limiter's preserve-partition-locality flag is mirrored onto
+ // the stamped reason, exactly like the analytics lane.
+ let limiter = build_limiter(1, 1, None, true);
+ let mut events = vec![
+ build_event(DataType::AiEvents, "phc_t", "u", false),
+ build_event(DataType::AiEvents, "phc_t", "u", false),
+ ];
+
+ stamp_overflow_reason(&mut events, None, Some(&limiter));
+
+ assert_eq!(events[0].metadata.overflow_reason, None);
+ assert_eq!(
+ events[1].metadata.overflow_reason,
+ Some(OverflowReason::RateLimited {
+ preserve_locality: true
+ })
+ );
+ }
+
+ /// The two lanes consult separate limiter instances, so one lane
+ /// exhausting a key's budget must not stamp the other lane's events for
+ /// the same `token:distinct_id` key.
+ #[rstest::rstest]
+ #[case::analytics_burst_leaves_ai_untouched(DataType::AnalyticsMain, DataType::AiEvents)]
+ #[case::ai_burst_leaves_analytics_untouched(DataType::AiEvents, DataType::AnalyticsMain)]
+ fn lane_budgets_are_isolated_per_key(
+ #[case] bursting_lane: DataType,
+ #[case] quiet_lane: DataType,
+ ) {
+ // burst=1 for both limiters: the bursting lane's second event goes
+ // over budget, while the quiet lane's single event (same key) must
+ // stay within its own untouched budget.
+ let analytics_limiter = build_limiter(1, 1, None, false);
+ let ai_limiter = build_limiter(1, 1, None, false);
+ let mut events = vec![
+ build_event(bursting_lane, "phc_t", "u", false),
+ build_event(bursting_lane, "phc_t", "u", false),
+ build_event(quiet_lane, "phc_t", "u", false),
+ ];
+
+ stamp_overflow_reason(&mut events, Some(&analytics_limiter), Some(&ai_limiter));
+
+ assert_eq!(events[0].metadata.overflow_reason, None);
+ assert_eq!(
+ events[1].metadata.overflow_reason,
+ Some(OverflowReason::RateLimited {
+ preserve_locality: false
+ }),
+ "second {bursting_lane:?} event over budget"
+ );
+ assert_eq!(
+ events[2].metadata.overflow_reason, None,
+ "{quiet_lane:?} must not inherit the {bursting_lane:?} lane's exhausted budget"
+ );
+ }
+
+ #[test]
+ fn ai_lane_ignores_analytics_limiter_when_own_limiter_absent() {
+ // A missing AI limiter means no rate-limit overflow for the AI lane,
+ // even when the analytics limiter would force-route the same key.
+ let analytics_limiter = build_limiter(10, 10, Some("phc_t:u".to_string()), false);
+ let mut events = vec![build_event(DataType::AiEvents, "phc_t", "u", false)];
+
+ stamp_overflow_reason(&mut events, Some(&analytics_limiter), None);
+
+ assert_eq!(events[0].metadata.overflow_reason, None);
+ }
+
+ #[test]
+ fn ai_events_force_overflow_short_circuits_when_armed() {
+ // Identical to the analytics lane: a restriction-driven
+ // force_overflow bypasses the limiter and leaves the reason unset;
+ // the sink routes on the flag alone.
+ let limiter = build_limiter(10, 10, Some("phc_t:u".to_string()), false);
+ let mut events = vec![build_event(DataType::AiEvents, "phc_t", "u", true)];
+
+ stamp_overflow_reason(&mut events, None, Some(&limiter));
+
+ assert_eq!(events[0].metadata.overflow_reason, None);
+ assert!(!events[0].metadata.skip_person_processing);
+ }
}
diff --git a/rust/capture/src/otel/mod.rs b/rust/capture/src/otel/mod.rs
index e347bfd83588..daa2b9066537 100644
--- a/rust/capture/src/otel/mod.rs
+++ b/rust/capture/src/otel/mod.rs
@@ -209,7 +209,11 @@ pub async fn otel_handler(
// `OVERFLOW_ENABLED=true`). Per-span key evaluation matches the analytics
// batch path: spans with different `token:distinct_id` keys can land
// with different `overflow_reason` stamps in the same batch.
- stamp_overflow_reason(&mut processed_events, state.overflow_limiter.as_ref());
+ stamp_overflow_reason(
+ &mut processed_events,
+ state.overflow_limiter.as_ref(),
+ state.ai_events_overflow_limiter.as_ref(),
+ );
state.sink.send_batch(processed_events).await.map_err(|e| {
report_internal_error_metrics(e.to_metric_tag(), "otel_sink");
diff --git a/rust/capture/src/router.rs b/rust/capture/src/router.rs
index dc6d81f93ed1..8f5e51bb58d3 100644
--- a/rust/capture/src/router.rs
+++ b/rust/capture/src/router.rs
@@ -27,7 +27,7 @@ use limiters::overflow::OverflowLimiter;
use limiters::redis::RedisLimiter;
use limiters::token_dropper::TokenDropper;
-use crate::config::CaptureMode;
+use crate::config::{AiRouting, CaptureMode};
use crate::metrics_middleware::track_metrics;
use crate::prometheus::setup_metrics_recorder;
use crate::quota_limiters::CaptureQuotaLimiter;
@@ -74,6 +74,14 @@ pub struct State {
/// pipeline alongside every other routing decision, and so the sink stays
/// a pure mechanism layer with cheap Arc-based clones.
pub overflow_limiter: Option<Arc<OverflowLimiter>>,
+ /// Dedicated overflow limiter for the AI lane (`DataType::AiEvents` /
+ /// `Destination::AiEvents`). Same knobs as `overflow_limiter` but a
+ /// separate governor instance, so per-key budgets are isolated: analytics
+ /// volume never pushes a key's AI events into AI overflow and AI volume
+ /// never burns the analytics budget. Only built when both
+ /// `OVERFLOW_ENABLED` and the AI overflow valve are set; `None` leaves
+ /// the AI lane subject to restriction-driven `force_overflow` only.
+ pub ai_events_overflow_limiter: Option<Arc<OverflowLimiter>>,
/// Redis-backed replay overflow limiter for session recording sessions.
/// When present, the recordings pipeline calls `is_limited(session_id)`
/// and stamps `ProcessedEventMetadata::overflow_reason = ReplayLimited` so
@@ -83,6 +91,18 @@ pub struct State {
/// V1 sink router for the new capture analytics pipeline.
/// When present, the v1 analytics handler publishes events through this.
pub v1_sink_router: Option<Arc<crate::v1::sinks::Router>>,
+ /// Routing policy for diverting `$ai_*` events to the dedicated AI topic
+ /// (`CAPTURE_ANALYTICS_AI_EVENTS_TOPIC`), derived from `CAPTURE_ANALYTICS_AI_EVENTS_MODE` and
+ /// `CAPTURE_ANALYTICS_AI_EVENTS_ALLOWLIST_TOKENS`. `Primary` keeps everything on the
+ /// analytics main topic; the other modes divert per batch token, in both
+ /// the v0 pipeline (via `DataType::AiEvents`, mapped to the topic in the
+ /// kafka sink) and the v1 pipeline (via `Destination::AiEvents`, mapped
+ /// via the `topic_ai` injected into each sink config at setup).
+ pub ai_routing: AiRouting,
+ /// Whether the AI overflow valve is armed (`CAPTURE_ANALYTICS_AI_EVENTS_OVERFLOW_TOPIC` is
+ /// set). Gates overflow stamping for the AI lane in both pipelines: when
+ /// false, AI events never overflow (pre-overflow behavior).
+ pub ai_events_overflow_enabled: bool,
pub capture_v1_scatter_gather_min_batch: usize,
pub ai_gateway_signing_secret: Option<String>,
/// Best-effort v2 ingestion warnings emitter (fire-and-forget Kafka
@@ -156,10 +176,13 @@ pub fn router<TZ: TimeSource + Send + Sync + 'static, R: Client + Send + Sync +
capture_v1_max_compressed_body_bytes: usize,
capture_v1_max_decompressed_body_bytes: usize,
overflow_limiter: Option<Arc<OverflowLimiter>>,
+ ai_events_overflow_limiter: Option<Arc<OverflowLimiter>>,
replay_overflow_limiter: Option<Arc<RedisLimiter>>,
v1_sink_router: Option<Arc<crate::v1::sinks::Router>>,
capture_v1_scatter_gather_min_batch: usize,
ai_gateway_signing_secret: Option<String>,
+ ai_routing: AiRouting,
+ ai_events_overflow_enabled: bool,
ingestion_warning_emitter: Option<Arc<dyn WarningEmitter>>,
) -> Router {
let state = State {
@@ -184,10 +207,13 @@ pub fn router<TZ: TimeSource + Send + Sync + 'static, R: Client + Send + Sync +
capture_v1_max_compressed_body_bytes,
capture_v1_max_decompressed_body_bytes,
overflow_limiter,
+ ai_events_overflow_limiter,
replay_overflow_limiter,
v1_sink_router,
capture_v1_scatter_gather_min_batch,
ai_gateway_signing_secret,
+ ai_routing,
+ ai_events_overflow_enabled,
ingestion_warning_emitter,
};
diff --git a/rust/capture/src/setup.rs b/rust/capture/src/setup.rs
index c56e83a2a894..c2cdea10f572 100644
--- a/rust/capture/src/setup.rs
+++ b/rust/capture/src/setup.rs
@@ -234,7 +234,7 @@ pub async fn build_components(
if config.export_prometheus {
let partition = partition.clone();
tokio::spawn(async move {
- partition.report_metrics().await;
+ partition.report_metrics("analytics").await;
});
}
@@ -372,6 +372,79 @@ pub async fn build_components(
None
};
+ // Deployment-level policy for diverting `$ai_*` events to a dedicated
+ // topic, shared by the v0 and v1 analytics pipelines. Distinct from the AI
+ // secondary CLUSTER routing above: this stays on the same sink and only
+ // changes the destination topic.
+ let ai_routing = match config.capture_analytics_ai_events_mode {
+ AiSinkMode::Primary => AiRouting::Primary,
+ AiSinkMode::Secondary => AiRouting::Secondary,
+ AiSinkMode::SecondaryAllowlist => AiRouting::SecondaryAllowlist(
+ config
+ .capture_analytics_ai_events_allowlist_tokens
+ .as_deref()
+ .map(parse_token_allowlist)
+ .unwrap_or_default(),
+ ),
+ };
+ assert!(
+ config.capture_analytics_ai_events_mode == AiSinkMode::Primary
+ || config
+ .kafka
+ .capture_analytics_ai_events_topic
+ .as_deref()
+ .is_some_and(|t| !t.is_empty()),
+ "invalid configuration: CAPTURE_ANALYTICS_AI_EVENTS_TOPIC must be set when CAPTURE_ANALYTICS_AI_EVENTS_MODE is not primary (got {:?})",
+ config.capture_analytics_ai_events_mode,
+ );
+ // The AI overflow valve: settable in advance of the routing mode (or
+ // absent), so it is deliberately not validated against it.
+ let ai_events_overflow_enabled = config
+ .kafka
+ .capture_analytics_ai_events_overflow_topic
+ .as_deref()
+ .is_some_and(|t| !t.is_empty());
+ info!(
+ ai_routing = ?ai_routing,
+ capture_analytics_ai_events_topic = ?config.kafka.capture_analytics_ai_events_topic,
+ capture_analytics_ai_events_overflow_topic = ?config.kafka.capture_analytics_ai_events_overflow_topic,
+ ai_events_overflow_enabled,
+ "AI events topic routing policy"
+ );
+
+ // The AI lane gets its own limiter instance with the same knobs: the
+ // governor state (per-`token:distinct_id` budgets) is what must stay
+ // isolated, so analytics volume can never push a key's AI events into
+ // AI overflow and AI volume never burns the analytics budget.
+ let ai_events_overflow_limiter: Option<Arc<OverflowLimiter>> =
+ if config.overflow_enabled && ai_events_overflow_enabled {
+ let limiter = OverflowLimiter::new(
+ config.overflow_per_second_limit,
+ config.overflow_burst_limit,
+ config.ingestion_force_overflow_by_token_distinct_id.clone(),
+ config.overflow_preserve_partition_locality,
+ );
+
+ if config.export_prometheus {
+ let limiter = limiter.clone();
+ tokio::spawn(async move {
+ limiter.report_metrics("ai").await;
+ });
+ }
+
+ {
+ // Keep the governor's per-key state from growing unbounded.
+ let limiter = limiter.clone();
+ tokio::spawn(async move {
+ limiter.clean_state().await;
+ });
+ }
+
+ Some(Arc::new(limiter))
+ } else {
+ None
+ };
+
let v1_sink_router = if !config.capture_v1_sinks.is_empty() {
Some(
create_v1_sink_router(&config, &sink_env, v1_sink_handles)
@@ -410,10 +483,13 @@ pub async fn build_components(
config.capture_v1_max_compressed_body_bytes,
config.capture_v1_max_decompressed_body_bytes,
overflow_limiter,
+ ai_events_overflow_limiter,
replay_overflow_limiter,
v1_sink_router.clone(),
config.capture_v1_scatter_gather_min_batch,
config.ai_gateway_signing_secret.clone(),
+ ai_routing,
+ ai_events_overflow_enabled,
ingestion_warning_emitter,
);
@@ -465,17 +541,30 @@ fn parse_token_allowlist(csv: &str) -> HashSet<String> {
.collect()
}
+/// Builds the v1 sink router. The dedicated `$ai_*` topics are
+/// deployment-level config (`CAPTURE_ANALYTICS_AI_EVENTS_TOPIC` and `CAPTURE_ANALYTICS_AI_EVENTS_OVERFLOW_TOPIC`),
+/// so they are injected into every sink config here; the overwrite is
+/// unconditional so a stray per-sink `TOPIC_AI`/`TOPIC_AI_OVERFLOW` env var
+/// cannot diverge from the shared policy.
fn create_v1_sink_router(
config: &Config,
sink_env: &HashMap<String, String>,
handles: HashMap<crate::v1::sinks::SinkName, lifecycle::Handle>,
) -> anyhow::Result<Arc<crate::v1::sinks::Router>> {
- let sinks_cfg = crate::v1::sinks::load_sinks_from(&config.capture_v1_sinks, sink_env)
+ let mut sinks_cfg = crate::v1::sinks::load_sinks_from(&config.capture_v1_sinks, sink_env)
.context("failed to parse CAPTURE_V1_SINKS")?;
sinks_cfg
.validate()
.context("v1 sink config validation failed")?;
+ for cfg in sinks_cfg.configs.values_mut() {
+ cfg.kafka.topic_ai = config.kafka.capture_analytics_ai_events_topic.clone();
+ cfg.kafka.topic_ai_overflow = config
+ .kafka
+ .capture_analytics_ai_events_overflow_topic
+ .clone();
+ }
+
let mut sink_map: HashMap<crate::v1::sinks::SinkName, Box<dyn crate::v1::sinks::sink::Sink>> =
HashMap::new();
diff --git a/rust/capture/src/sinks/kafka.rs b/rust/capture/src/sinks/kafka.rs
index 2204a61d009e..a6b675cb12cb 100644
--- a/rust/capture/src/sinks/kafka.rs
+++ b/rust/capture/src/sinks/kafka.rs
@@ -23,6 +23,7 @@ use crate::sinks::producer::{KafkaProducer, ProduceRecord};
use crate::sinks::Event;
use crate::v0_request::{DataType, OverflowReason, ProcessedEvent};
use async_trait::async_trait;
+use common_types::CapturedEventHeaders;
use metrics::{counter, gauge, histogram};
use rdkafka::producer::{FutureProducer, Producer};
use rdkafka::util::Timeout;
@@ -30,7 +31,7 @@ use rdkafka::ClientConfig;
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::task::JoinSet;
-use tracing::log::{debug, error, info};
+use tracing::log::{debug, error, info, warn};
use tracing::{info_span, instrument, Instrument};
use super::producer::RdKafkaProducer;
@@ -181,6 +182,15 @@ pub struct KafkaTopicConfig {
pub dlq_topic: String,
pub error_tracking_topic: String,
pub traces_topic: String,
+ /// Dedicated topic for `DataType::AiEvents` (`CAPTURE_ANALYTICS_AI_EVENTS_TOPIC`). Optional
+ /// because the AI lane is opt-in: startup validation guarantees it is set
+ /// whenever the routing policy can produce `AiEvents` records.
+ pub ai_events_topic: Option<String>,
+ /// Overflow topic for the AI lane (`CAPTURE_ANALYTICS_AI_EVENTS_OVERFLOW_TOPIC`). Unset
+ /// means AI events never overflow; when set, stamped/forced overflow on
+ /// `AiEvents` records reroutes here with the same key semantics as the
+ /// analytics overflow topic.
+ pub ai_events_overflow_topic: Option<String>,
}
impl From<&KafkaConfig> for KafkaTopicConfig {
@@ -195,6 +205,8 @@ impl From<&KafkaConfig> for KafkaTopicConfig {
dlq_topic: config.kafka_dlq_topic.clone(),
error_tracking_topic: config.kafka_error_tracking_topic.clone(),
traces_topic: config.kafka_traces_topic.clone(),
+ ai_events_topic: config.capture_analytics_ai_events_topic.clone(),
+ ai_events_overflow_topic: config.capture_analytics_ai_events_overflow_topic.clone(),
}
}
}
@@ -224,6 +236,53 @@ impl<P: KafkaProducer> Clone for KafkaSinkBase<P> {
}
}
+/// Overflow routing shared by the lanes that own a dedicated overflow topic:
+/// the analytics main lane always, and the AI lane once
+/// `CAPTURE_ANALYTICS_AI_EVENTS_OVERFLOW_TOPIC` is set. Keeping both lanes on one function
+/// guarantees identical semantics, including the partition-key handling
+/// driven by `overflow_preserve_partition_locality`.
+///
+/// Precedence (matches the pre-refactor sink ordering): force_overflow
+/// (restrictions) -> overflow_reason (pipeline-stamped) -> the lane's
+/// `default_route`. `ReplayLimited` never applies to these lanes and falls
+/// through to the default.
+fn route_with_overflow<'a>(
+ overflow_topic: &'a str,
+ default_route: (&'a str, Option<&'a str>),
+ event_key: &'a str,
+ force_overflow: bool,
+ skip_person_processing: bool,
+ overflow_reason: Option<&OverflowReason>,
+ headers: &mut CapturedEventHeaders,
+) -> (&'a str, Option<&'a str>) {
+ if force_overflow {
+ // Drop partition key if skip_person_processing is set
+ let key = if skip_person_processing {
+ None
+ } else {
+ Some(event_key)
+ };
+ return (overflow_topic, key);
+ }
+ match overflow_reason {
+ Some(OverflowReason::ForceLimited) => {
+ // Redundant with the generic skip-person path (the pipeline
+ // stamps `metadata.skip_person_processing = true` alongside
+ // `OverflowReason::ForceLimited`), but kept as defense against a
+ // future caller that stamps the reason without the side-effect.
+ headers.set_force_disable_person_processing(true);
+ (overflow_topic, None)
+ }
+ Some(OverflowReason::RateLimited {
+ preserve_locality: true,
+ }) => (overflow_topic, Some(event_key)),
+ Some(OverflowReason::RateLimited {
+ preserve_locality: false,
+ }) => (overflow_topic, None),
+ Some(OverflowReason::ReplayLimited) | None => default_route,
+ }
+}
+
/// The default KafkaSink using rdkafka's FutureProducer
pub type KafkaSink = KafkaSinkBase<RdKafkaProducer<KafkaContext>>;
@@ -486,46 +545,22 @@ impl<P: KafkaProducer> KafkaSinkBase<P> {
(&self.topics.historical_topic, Some(event_key.as_str()))
}
DataType::AnalyticsMain => {
- // Precedence: force_overflow (restrictions) -> overflow_reason
- // (pipeline-stamped) -> default main-topic routing.
- if force_overflow {
- // Drop partition key if skip_person_processing is set
- let key = if skip_person_processing {
- None
- } else {
- Some(event_key.as_str())
- };
- (&self.topics.overflow_topic, key)
+ // Drop the partition key on the default main-topic route
+ // if skip_person_processing is set.
+ let default_key = if skip_person_processing {
+ None
} else {
- match &overflow_reason {
- Some(OverflowReason::ForceLimited) => {
- // Redundant with the generic skip-person path
- // above (the pipeline stamps
- // `metadata.skip_person_processing = true`
- // alongside `OverflowReason::ForceLimited`), but
- // kept as defense against a future caller that
- // stamps the reason without the side-effect.
- headers.set_force_disable_person_processing(true);
- (&self.topics.overflow_topic, None)
- }
- Some(OverflowReason::RateLimited {
- preserve_locality: true,
- }) => (&self.topics.overflow_topic, Some(event_key.as_str())),
- Some(OverflowReason::RateLimited {
- preserve_locality: false,
- }) => (&self.topics.overflow_topic, None),
- // ReplayLimited never applies to AnalyticsMain; fall through to main.
- Some(OverflowReason::ReplayLimited) | None => {
- // Drop partition key if skip_person_processing is set
- let key = if skip_person_processing {
- None
- } else {
- Some(event_key.as_str())
- };
- (&self.topics.main_topic, key)
- }
- }
- }
+ Some(event_key.as_str())
+ };
+ route_with_overflow(
+ &self.topics.overflow_topic,
+ (&self.topics.main_topic, default_key),
+ &event_key,
+ force_overflow,
+ skip_person_processing,
+ overflow_reason.as_ref(),
+ &mut headers,
+ )
}
DataType::ClientIngestionWarning => (
&self.topics.client_ingestion_warning_topic,
@@ -535,6 +570,44 @@ impl<P: KafkaProducer> KafkaSinkBase<P> {
DataType::ExceptionErrorTracking => {
(&self.topics.error_tracking_topic, Some(event_key.as_str()))
}
+ DataType::AiEvents => {
+ // AI events never reroute historical; like the
+ // exception/heatmap lanes the record keeps its event key
+ // on the default route (v1 only nulls keys for
+ // Main/Overflow-shaped destinations). An unset topic
+ // should be impossible here (startup validation requires
+ // CAPTURE_ANALYTICS_AI_EVENTS_TOPIC whenever the routing policy can produce
+ // AiEvents), so fall back to the main topic rather than
+ // failing the batch.
+ let default_topic: &str = match self.topics.ai_events_topic.as_deref() {
+ Some(topic) if !topic.is_empty() => topic,
+ _ => {
+ warn!(
+ "CAPTURE_ANALYTICS_AI_EVENTS_TOPIC not configured for an AiEvents record; falling back to main topic"
+ );
+ &self.topics.main_topic
+ }
+ };
+ match self.topics.ai_events_overflow_topic.as_deref() {
+ // The AI overflow valve is armed: mirror the
+ // analytics main lane's overflow handling onto the
+ // AI topics.
+ Some(overflow_topic) if !overflow_topic.is_empty() => route_with_overflow(
+ overflow_topic,
+ (default_topic, Some(event_key.as_str())),
+ &event_key,
+ force_overflow,
+ skip_person_processing,
+ overflow_reason.as_ref(),
+ &mut headers,
+ ),
+ // Valve unarmed: AI events never overflow;
+ // force_overflow and overflow_reason are
+ // deliberately ignored, and the pipeline never
+ // stamps a reason on this lane anyway.
+ _ => (default_topic, Some(event_key.as_str())),
+ }
+ }
DataType::SnapshotMain => {
let session_id = session_id
.as_deref()
@@ -793,6 +866,8 @@ pub(crate) fn test_topics() -> KafkaTopicConfig {
dlq_topic: "events_plugin_ingestion_dlq".to_string(),
error_tracking_topic: "error_tracking_events".to_string(),
traces_topic: "tracing_ingestion".to_string(),
+ ai_events_topic: Some("ai_events".to_string()),
+ ai_events_overflow_topic: Some("ai_events_overflow".to_string()),
}
}
@@ -844,6 +919,8 @@ mod tests {
kafka_heatmaps_topic: "events_plugin_ingestion".to_string(),
kafka_replay_overflow_topic: "session_recording_snapshot_item_overflow".to_string(),
kafka_dlq_topic: "events_plugin_ingestion_dlq".to_string(),
+ capture_analytics_ai_events_topic: None,
+ capture_analytics_ai_events_overflow_topic: None,
kafka_traces_topic: "traces_ingestion".to_string(),
kafka_metrics_topic: "metrics_ingestion".to_string(),
kafka_tls: false,
@@ -1188,6 +1265,7 @@ mod tests {
use super::*;
use crate::sinks::kafka::{test_topics, KafkaSinkBase, SCATTER_GATHER_MIN_BATCH};
use crate::sinks::producer::MockKafkaProducer;
+ use rstest::rstest;
const MAIN_TOPIC: &str = "events_plugin_ingestion";
const OVERFLOW_TOPIC: &str = "events_plugin_ingestion_overflow";
@@ -1197,6 +1275,8 @@ mod tests {
const CLIENT_INGESTION_WARNING_TOPIC: &str = "client_ingestion_warning";
const REPLAY_OVERFLOW_TOPIC: &str = "replay_overflow";
const ERROR_TRACKING_TOPIC: &str = "error_tracking_events";
+ const AI_EVENTS_TOPIC: &str = "ai_events";
+ const AI_EVENTS_OVERFLOW_TOPIC: &str = "ai_events_overflow";
struct EventInput {
data_type: DataType,
@@ -1940,6 +2020,279 @@ mod tests {
.await;
}
+ // ==================== AiEvents ====================
+ // The dedicated $ai_* lane routes to its own topic, keyed on the
+ // event key. test_topics() arms the AI overflow valve
+ // (CAPTURE_ANALYTICS_AI_EVENTS_OVERFLOW_TOPIC), so overflow handling mirrors the
+ // AnalyticsMain arm onto the AI topics; the unarmed tests below
+ // override the valve off.
+
+ #[tokio::test]
+ async fn ai_events_normal() {
+ assert_routing(
+ EventInput {
+ data_type: DataType::AiEvents,
+ force_overflow: false,
+ skip_person_processing: false,
+ redirect_to_dlq: false,
+ redirect_to_topic: None,
+ overflow_reason: None,
+ },
+ ExpectedRouting {
+ topic: AI_EVENTS_TOPIC,
+ has_key: true,
+ force_disable_person_processing: None,
+ },
+ )
+ .await;
+ }
+
+ #[tokio::test]
+ async fn ai_events_force_overflow_reroutes_when_armed() {
+ // With the valve armed, restriction-driven force_overflow behaves
+ // exactly like the analytics main lane: rerouted, key kept.
+ assert_routing(
+ EventInput {
+ data_type: DataType::AiEvents,
+ force_overflow: true,
+ skip_person_processing: false,
+ redirect_to_dlq: false,
+ redirect_to_topic: None,
+ overflow_reason: None,
+ },
+ ExpectedRouting {
+ topic: AI_EVENTS_OVERFLOW_TOPIC,
+ has_key: true,
+ force_disable_person_processing: None,
+ },
+ )
+ .await;
+ }
+
+ #[tokio::test]
+ async fn ai_events_force_overflow_with_skip_person_drops_key() {
+ // Mirrors analytics_main_force_overflow_with_skip_person.
+ assert_routing(
+ EventInput {
+ data_type: DataType::AiEvents,
+ force_overflow: true,
+ skip_person_processing: true,
+ redirect_to_dlq: false,
+ redirect_to_topic: None,
+ overflow_reason: None,
+ },
+ ExpectedRouting {
+ topic: AI_EVENTS_OVERFLOW_TOPIC,
+ has_key: false,
+ force_disable_person_processing: Some(true),
+ },
+ )
+ .await;
+ }
+
+ /// Stamped overflow reasons on the AI lane route exactly like the
+ /// analytics main lane, including the preserve-partition-locality
+ /// key handling mirrored from the limiter config.
+ #[rstest]
+ #[case::force_limited(OverflowReason::ForceLimited, false, Some(true))]
+ #[case::rate_limited_preserving(
+ OverflowReason::RateLimited {
+ preserve_locality: true
+ },
+ true,
+ None
+ )]
+ #[case::rate_limited_spreading(
+ OverflowReason::RateLimited {
+ preserve_locality: false
+ },
+ false,
+ None
+ )]
+ #[tokio::test]
+ async fn ai_events_stamped_overflow_mirrors_analytics(
+ #[case] reason: OverflowReason,
+ #[case] has_key: bool,
+ #[case] force_disable_person_processing: Option<bool>,
+ ) {
+ assert_routing(
+ EventInput {
+ data_type: DataType::AiEvents,
+ force_overflow: false,
+ skip_person_processing: false,
+ redirect_to_dlq: false,
+ redirect_to_topic: None,
+ overflow_reason: Some(reason),
+ },
+ ExpectedRouting {
+ topic: AI_EVENTS_OVERFLOW_TOPIC,
+ has_key,
+ force_disable_person_processing,
+ },
+ )
+ .await;
+ }
+
+ #[tokio::test]
+ async fn ai_events_unarmed_never_overflows() {
+ // Without CAPTURE_ANALYTICS_AI_EVENTS_OVERFLOW_TOPIC the lane keeps today's
+ // behavior: force_overflow and any stamped reason (which the
+ // gated pipeline would not produce anyway) are ignored.
+ let producer = MockKafkaProducer::new();
+ let mut topics = test_topics();
+ topics.ai_events_overflow_topic = None;
+ let sink = KafkaSinkBase::with_producer(producer.clone(), topics);
+
+ let mut event = create_test_event(&EventInput {
+ data_type: DataType::AiEvents,
+ force_overflow: true,
+ skip_person_processing: false,
+ redirect_to_dlq: false,
+ redirect_to_topic: None,
+ overflow_reason: None,
+ });
+ event.metadata.overflow_reason = Some(OverflowReason::ForceLimited);
+ sink.send(event).await.unwrap();
+
+ let records = producer.get_records();
+ assert_eq!(records.len(), 1);
+ assert_eq!(records[0].topic, AI_EVENTS_TOPIC);
+ assert_eq!(records[0].key.as_deref(), Some("test_token:test_user"));
+ }
+
+ #[tokio::test]
+ async fn ai_events_skip_person_keeps_key() {
+ // skip_person_processing sets the header but must not null the
+ // key: v1's sink only nulls keys for Main/Overflow destinations.
+ assert_routing(
+ EventInput {
+ data_type: DataType::AiEvents,
+ force_overflow: false,
+ skip_person_processing: true,
+ redirect_to_dlq: false,
+ redirect_to_topic: None,
+ overflow_reason: None,
+ },
+ ExpectedRouting {
+ topic: AI_EVENTS_TOPIC,
+ has_key: true,
+ force_disable_person_processing: Some(true),
+ },
+ )
+ .await;
+ }
+
+ #[tokio::test]
+ async fn ai_events_redirect_to_dlq() {
+ assert_routing(
+ EventInput {
+ data_type: DataType::AiEvents,
+ force_overflow: false,
+ skip_person_processing: false,
+ redirect_to_dlq: true,
+ redirect_to_topic: None,
+ overflow_reason: None,
+ },
+ ExpectedRouting {
+ topic: DLQ_TOPIC,
+ has_key: true,
+ force_disable_person_processing: None,
+ },
+ )
+ .await;
+ }
+
+ #[tokio::test]
+ async fn ai_events_redirect_to_topic_wins() {
+ // A restriction-driven redirect beats the AI lane, matching v1
+ // where Destination::Custom overwrites Destination::AiEvents.
+ assert_routing(
+ EventInput {
+ data_type: DataType::AiEvents,
+ force_overflow: false,
+ skip_person_processing: false,
+ redirect_to_dlq: false,
+ redirect_to_topic: Some("custom_topic".to_string()),
+ overflow_reason: None,
+ },
+ ExpectedRouting {
+ topic: "custom_topic",
+ has_key: true,
+ force_disable_person_processing: None,
+ },
+ )
+ .await;
+ }
+
+ #[tokio::test]
+ async fn ai_events_record_matches_other_lanes_byte_for_byte() {
+ // The AI lane must only change the topic: for the same event, the
+ // record key is the event key (token:distinct_id) and the headers
+ // are identical to what another dedicated lane produces.
+ let producer = MockKafkaProducer::new();
+ let sink = KafkaSinkBase::with_producer(producer.clone(), test_topics());
+
+ let base = create_test_event(&EventInput::default());
+ let mut ai_event = base.clone();
+ ai_event.metadata.data_type = DataType::AiEvents;
+ let mut exception_event = base;
+ exception_event.metadata.data_type = DataType::ExceptionErrorTracking;
+
+ sink.send(ai_event).await.unwrap();
+ sink.send(exception_event).await.unwrap();
+
+ let records = producer.get_records();
+ assert_eq!(records.len(), 2);
+ assert_eq!(records[0].topic, AI_EVENTS_TOPIC);
+ assert_eq!(records[1].topic, ERROR_TRACKING_TOPIC);
+ assert_eq!(records[0].key.as_deref(), Some("test_token:test_user"));
+ assert_eq!(records[0].key, records[1].key);
+ assert_eq!(records[0].payload, records[1].payload);
+ assert_eq!(
+ format!("{:?}", records[0].headers),
+ format!("{:?}", records[1].headers)
+ );
+ }
+
+ #[tokio::test]
+ async fn ai_events_missing_topic_falls_back_to_main() {
+ // Should be impossible in production (startup validation), but a
+ // misconfigured sink must degrade to the main topic, not error.
+ let producer = MockKafkaProducer::new();
+ let mut topics = test_topics();
+ topics.ai_events_topic = None;
+ let sink = KafkaSinkBase::with_producer(producer.clone(), topics);
+
+ let input = EventInput {
+ data_type: DataType::AiEvents,
+ ..Default::default()
+ };
+ sink.send(create_test_event(&input)).await.unwrap();
+
+ let records = producer.get_records();
+ assert_eq!(records.len(), 1);
+ assert_eq!(records[0].topic, MAIN_TOPIC);
+ assert_eq!(records[0].key.as_deref(), Some("test_token:test_user"));
+ }
+
+ #[tokio::test]
+ async fn ai_events_empty_topic_falls_back_to_main() {
+ let producer = MockKafkaProducer::new();
+ let mut topics = test_topics();
+ topics.ai_events_topic = Some(String::new());
+ let sink = KafkaSinkBase::with_producer(producer.clone(), topics);
+
+ let input = EventInput {
+ data_type: DataType::AiEvents,
+ ..Default::default()
+ };
+ sink.send(create_test_event(&input)).await.unwrap();
+
+ let records = producer.get_records();
+ assert_eq!(records.len(), 1);
+ assert_eq!(records[0].topic, MAIN_TOPIC);
+ }
+
// ==================== RedirectToTopic ====================
// redirect_to_topic overrides normal routing but DLQ takes priority
diff --git a/rust/capture/src/v0_endpoint.rs b/rust/capture/src/v0_endpoint.rs
index 060d457cf497..20b0994bce16 100644
--- a/rust/capture/src/v0_endpoint.rs
+++ b/rust/capture/src/v0_endpoint.rs
@@ -67,6 +67,8 @@ pub async fn event(
state.historical_cfg,
state.global_rate_limiter_token_distinctid.clone(),
state.overflow_limiter.clone(),
+ state.ai_events_overflow_limiter.clone(),
+ &state.ai_routing,
events,
&context,
)
diff --git a/rust/capture/src/v0_request.rs b/rust/capture/src/v0_request.rs
index 4902af6f28f2..271aa8418e2b 100644
--- a/rust/capture/src/v0_request.rs
+++ b/rust/capture/src/v0_request.rs
@@ -165,6 +165,11 @@ pub enum DataType {
HeatmapMain,
ExceptionErrorTracking,
SnapshotMain,
+ /// Dedicated `$ai_*` lane, mirroring v1's `Destination::AiEvents`. Only
+ /// produced when the deployment's `AiRouting` policy diverts the batch
+ /// token; the kafka sink maps it to `CAPTURE_ANALYTICS_AI_EVENTS_TOPIC`. Like heatmaps and
+ /// exceptions, AI events never overflow and never reroute historical.
+ AiEvents,
}
impl DataType {
@@ -173,15 +178,26 @@ impl DataType {
/// `apply_restrictions` so the analytics → exception → heatmap →
/// ingestion-warning split stays in one place.
///
+ /// `route_ai_events` reflects the per-batch `AiRouting` decision,
+ /// mirroring v1's `destination_for_event_name`: when set, `$ai_*` events
+ /// divert to `AiEvents`, winning over historical (in v1 the historical
+ /// reroute only applies to the analytics-main destination). When unset
+ /// the mapping is a strict no-op relative to the pre-AI-lane behavior.
+ ///
/// `SnapshotMain` is not produced here — replay events arrive on a
/// separate endpoint and never flow through analytics processing.
- pub fn from_event_name(event_name: &str, historical_migration: bool) -> Self {
- match (event_name, historical_migration) {
- ("$$client_ingestion_warning", _) => Self::ClientIngestionWarning,
- ("$exception", _) => Self::ExceptionErrorTracking,
- ("$$heatmap", _) => Self::HeatmapMain,
- (_, true) => Self::AnalyticsHistorical,
- (_, false) => Self::AnalyticsMain,
+ pub fn from_event_name(
+ event_name: &str,
+ historical_migration: bool,
+ route_ai_events: bool,
+ ) -> Self {
+ match event_name {
+ "$$client_ingestion_warning" => Self::ClientIngestionWarning,
+ "$exception" => Self::ExceptionErrorTracking,
+ "$$heatmap" => Self::HeatmapMain,
+ _ if route_ai_events && event_name.starts_with("$ai_") => Self::AiEvents,
+ _ if historical_migration => Self::AnalyticsHistorical,
+ _ => Self::AnalyticsMain,
}
}
@@ -189,9 +205,16 @@ impl DataType {
/// and snapshots have their own dedicated topics and consumers; they
/// don't share Redis-backed restriction config with any other pipeline,
/// so they're not subject to `EventRestrictionService` lookups.
+ ///
+ /// `AiEvents` maps to the `ai` restriction pipeline: an event diverted to
+ /// the AI lane is governed by ai-scoped restrictions, the same slice the
+ /// dedicated AI endpoints consult. Non-diverted `$ai_*` events classify
+ /// as `AnalyticsMain` and stay under analytics restrictions. v1 derives
+ /// the same mapping from `Destination::pipeline`.
pub fn pipeline(self) -> Option<Pipeline> {
match self {
Self::AnalyticsMain | Self::AnalyticsHistorical => Some(Pipeline::Analytics),
+ Self::AiEvents => Some(Pipeline::Ai),
Self::ExceptionErrorTracking => Some(Pipeline::ErrorTracking),
Self::ClientIngestionWarning | Self::HeatmapMain | Self::SnapshotMain => None,
}
@@ -272,7 +295,54 @@ mod tests {
use serde::Deserialize;
use serde_json::json;
- use super::{CaptureError, Compression, RawRequest};
+ use super::{CaptureError, Compression, DataType, RawRequest};
+
+ /// Mirrors v1's `destination_for_event_name` mapping tests: the
+ /// dedicated-name lanes always win, `$ai_*` diverts only when the route
+ /// flag is set (beating historical), and everything else falls through to
+ /// main/historical per the batch flag.
+ #[rstest::rstest]
+ // Dedicated-name lanes are unaffected by both flags.
+ #[case("$exception", false, false, DataType::ExceptionErrorTracking)]
+ #[case("$exception", true, true, DataType::ExceptionErrorTracking)]
+ #[case("$$heatmap", false, false, DataType::HeatmapMain)]
+ #[case("$$heatmap", true, true, DataType::HeatmapMain)]
+ #[case(
+ "$$client_ingestion_warning",
+ false,
+ false,
+ DataType::ClientIngestionWarning
+ )]
+ #[case(
+ "$$client_ingestion_warning",
+ true,
+ true,
+ DataType::ClientIngestionWarning
+ )]
+ // Non-AI events keep the main/historical split.
+ #[case("$pageview", false, false, DataType::AnalyticsMain)]
+ #[case("$pageview", false, true, DataType::AnalyticsMain)]
+ #[case("custom_event", false, true, DataType::AnalyticsMain)]
+ #[case("$pageview", true, false, DataType::AnalyticsHistorical)]
+ #[case("$pageview", true, true, DataType::AnalyticsHistorical)]
+ // $ai_* diverts only when AI routing is enabled, and wins over historical.
+ #[case("$ai_generation", false, true, DataType::AiEvents)]
+ #[case("$ai_span", false, true, DataType::AiEvents)]
+ #[case("$ai_trace", false, true, DataType::AiEvents)]
+ #[case("$ai_generation", true, true, DataType::AiEvents)]
+ #[case("$ai_generation", false, false, DataType::AnalyticsMain)]
+ #[case("$ai_generation", true, false, DataType::AnalyticsHistorical)]
+ fn from_event_name_mapping(
+ #[case] event_name: &str,
+ #[case] historical_migration: bool,
+ #[case] route_ai_events: bool,
+ #[case] expected: DataType,
+ ) {
+ assert_eq!(
+ DataType::from_event_name(event_name, historical_migration, route_ai_events),
+ expected
+ );
+ }
#[test]
fn decode_compression_param() {
diff --git a/rust/capture/src/v1/analytics/process.rs b/rust/capture/src/v1/analytics/process.rs
index f5224ffbc494..f0acaffd1d26 100644
--- a/rust/capture/src/v1/analytics/process.rs
+++ b/rust/capture/src/v1/analytics/process.rs
@@ -1,4 +1,5 @@
use std::collections::{HashMap, HashSet};
+use std::sync::Arc;
use std::time::Instant;
use chrono::{DateTime, Utc};
@@ -17,7 +18,6 @@ use super::response::BatchResponse;
use super::types::{Batch, Event, EventResult, Options, WrappedEvent};
use crate::event_restrictions::{EventContext, EventRestrictionService};
use crate::global_rate_limiter::{GlobalRateLimitKey, GlobalRateLimiter};
-use crate::v0_request::DataType;
use limiters::overflow::{OverflowLimiter, OverflowLimiterResult};
use tracing::Level;
@@ -37,11 +37,18 @@ use common_ingestion_warnings::{WarningType, CAPTURE_V1_ANALYTICS};
/// as opaque RawValue to avoid deserialization. The Node.js events subpipeline
/// (extractHeatmapDataStep) handles extraction when `skip_heatmap_processing` is unset
/// in Kafka headers — removing that fallback would break scroll-depth heatmaps for v1.
-fn destination_for_event_name(name: &str) -> Destination {
+///
+/// When `route_ai_events` is set (this batch's token routes to the AI topic
+/// per the configured `AiRouting` policy: mode plus token allowlist), `$ai_*`
+/// events are diverted to `Destination::AiEvents`; otherwise they fall through
+/// to `AnalyticsMain` exactly as before, so an unconfigured AI topic or
+/// `primary` mode is a strict no-op.
+fn destination_for_event_name(name: &str, route_ai_events: bool) -> Destination {
match name {
"$exception" => Destination::ExceptionErrorTracking,
"$$heatmap" => Destination::HeatmapMain,
"$$client_ingestion_warning" => Destination::ClientIngestionWarning,
+ _ if route_ai_events && name.starts_with("$ai_") => Destination::AiEvents,
_ => Destination::AnalyticsMain,
}
}
@@ -61,7 +68,9 @@ pub async fn process_batch(
}
context.set_batch_metadata(&batch);
- let mut events = match validate_events(context, batch) {
+ // A batch carries a single token, so the AI routing decision is per batch.
+ let route_ai_events = state.ai_routing.routes_to_secondary(&context.api_token);
+ let mut events = match validate_events(context, batch, route_ai_events) {
Ok(events) => events,
Err(err) => {
emit_batch_abort_warning(state, context, &err, batch_len);
@@ -94,6 +103,7 @@ pub async fn process_batch(
service,
&context.api_token,
context.server_received_at.timestamp(),
+ state.ai_events_overflow_enabled,
&mut events,
)
.await;
@@ -103,8 +113,13 @@ pub async fn process_batch(
// Overflow and global rate limit are independent checks on different axes:
// overflow reroutes bursting keys; global rate limit disables person processing.
- if let Some(ref limiter) = state.overflow_limiter {
- apply_overflow_stamping(limiter, context, &mut events);
+ if state.overflow_limiter.is_some() || state.ai_events_overflow_limiter.is_some() {
+ apply_overflow_stamping(
+ state.overflow_limiter.as_ref(),
+ state.ai_events_overflow_limiter.as_ref(),
+ context,
+ &mut events,
+ );
}
if let Some(ref limiter) = state.global_rate_limiter_token_distinctid {
@@ -407,7 +422,11 @@ fn validate_batch(batch: &Batch) -> Result<(), Error> {
Ok(())
}
-fn validate_events(context: &RequestContext, batch: Batch) -> Result<Vec<WrappedEvent>, Error> {
+fn validate_events(
+ context: &RequestContext,
+ batch: Batch,
+ route_ai_events: bool,
+) -> Result<Vec<WrappedEvent>, Error> {
let batch_len = batch.batch.len();
let mut events: Vec<WrappedEvent> = Vec::with_capacity(batch_len);
let mut seen: HashSet<Uuid> = HashSet::with_capacity(batch_len);
@@ -427,7 +446,7 @@ fn validate_events(context: &RequestContext, batch: Batch) -> Result<Vec<Wrapped
));
}
- let destination = destination_for_event_name(&event.event);
+ let destination = destination_for_event_name(&event.event, route_ai_events);
match validate_event(&event) {
Ok(raw_ts) => {
@@ -627,30 +646,43 @@ fn apply_historical_rerouting(
}
fn apply_overflow_stamping(
- limiter: &OverflowLimiter,
+ analytics_limiter: Option<&Arc<OverflowLimiter>>,
+ ai_limiter: Option<&Arc<OverflowLimiter>>,
ctx: &RequestContext,
events: &mut [WrappedEvent],
) {
for event in events.iter_mut() {
- if event.destination != Destination::AnalyticsMain {
- continue;
- }
+ // Each overflowing lane keeps its own overflow destination AND its
+ // own limiter instance, so an overflowing AI event lands on AI
+ // overflow (never analytics overflow) and the per-key budgets are
+ // isolated between the lanes. The AI lane only participates when its
+ // limiter exists — setup builds it exactly when the AI overflow valve
+ // (CAPTURE_ANALYTICS_AI_EVENTS_OVERFLOW_TOPIC) is armed, so limiter
+ // presence encodes the valve here.
+ let (overflow_destination, lane_limiter) = match event.destination {
+ Destination::AnalyticsMain => (Destination::Overflow, analytics_limiter),
+ Destination::AiEvents => (Destination::AiEventsOverflow, ai_limiter),
+ _ => continue,
+ };
if event.result == EventResult::Drop {
continue;
}
+ let Some(limiter) = lane_limiter else {
+ continue;
+ };
let key = event.partition_key(ctx);
match limiter.is_limited(&key) {
OverflowLimiterResult::ForceLimited => {
- event.destination = Destination::Overflow;
+ event.destination = overflow_destination;
// Disables person processing AND nulls partition key at sink.
event.force_disable_person_processing = true;
metrics::counter!(CAPTURE_V1_OVERFLOW_ROUTED, "reason" => "force_limited")
.increment(1);
}
OverflowLimiterResult::Limited => {
- event.destination = Destination::Overflow;
+ event.destination = overflow_destination;
if !limiter.should_preserve_locality() {
// Nulls partition key at sink -- spreads across partitions.
event.force_disable_person_processing = true;
@@ -667,6 +699,7 @@ async fn apply_restrictions(
service: &EventRestrictionService,
token: &str,
now_ts: i64,
+ ai_events_overflow_enabled: bool,
events: &mut [WrappedEvent],
) {
for event in events.iter_mut() {
@@ -674,11 +707,13 @@ async fn apply_restrictions(
continue;
}
- // Derive the pipeline from the event name so each event is matched
- // against the correct restriction slice (Analytics vs ErrorTracking).
- // `pipeline() == None` for heatmaps / ingestion warnings / snapshots
- // → they pass through unrestricted, exactly as v0 does.
- let Some(pipeline) = DataType::from_event_name(&event.event.event, false).pipeline() else {
+ // Derive the pipeline from the destination so each event is matched
+ // against the correct restriction slice (Analytics vs ErrorTracking
+ // vs Ai) — an event diverted to the AI lane is governed by ai-scoped
+ // restrictions, not analytics ones. `pipeline() == None` for heatmaps
+ // / ingestion warnings → they pass through unrestricted, exactly as
+ // v0 does (v0 derives the same mapping from `DataType::pipeline`).
+ let Some(pipeline) = event.destination.pipeline() else {
continue;
};
@@ -702,14 +737,25 @@ async fn apply_restrictions(
}
// Priority: overflow < custom topic < DLQ (DLQ wins, applied last)
- // Overflow only applies to AnalyticsMain: AnalyticsHistorical must never
- // overflow (legacy sink invariant). Today this stage runs before
- // historical rerouting so the destination is always AnalyticsMain here;
- // the explicit guard makes the invariant ordering-independent.
- if applied.force_overflow() && event.destination == Destination::AnalyticsMain {
- event.destination = Destination::Overflow;
- metrics::counter!(CAPTURE_V1_EVENTS_RESTRICTED, "action" => "force_overflow")
- .increment(1);
+ // Overflow only applies to the overflowing lanes: AnalyticsMain, and
+ // AiEvents once the AI overflow valve is armed (each rerouting to its
+ // own overflow destination). AnalyticsHistorical must never overflow
+ // (legacy sink invariant). Today this stage runs before historical
+ // rerouting so an analytics event is always AnalyticsMain here; the
+ // explicit guard makes the invariant ordering-independent.
+ let force_overflow_destination = match event.destination {
+ Destination::AnalyticsMain => Some(Destination::Overflow),
+ Destination::AiEvents if ai_events_overflow_enabled => {
+ Some(Destination::AiEventsOverflow)
+ }
+ _ => None,
+ };
+ if applied.force_overflow() {
+ if let Some(destination) = force_overflow_destination {
+ event.destination = destination;
+ metrics::counter!(CAPTURE_V1_EVENTS_RESTRICTED, "action" => "force_overflow")
+ .increment(1);
+ }
}
if let Some(topic) = applied.redirect_to_topic() {
event.destination = Destination::Custom(topic.to_string());
@@ -1102,7 +1148,7 @@ mod tests {
let normal = valid_event();
let normal_uuid = Uuid::parse_str(&normal.uuid).unwrap();
let batch = valid_batch(vec![perf, normal]);
- let events = validate_events(&ctx, batch).unwrap();
+ let events = validate_events(&ctx, batch, false).unwrap();
assert_eq!(events.len(), 2);
// Vec preserves input order: perf first, normal second.
let p = &events[0];
@@ -1126,7 +1172,7 @@ mod tests {
..valid_event()
};
let batch = valid_batch(vec![p1, p2]);
- let events = validate_events(&ctx, batch).unwrap();
+ let events = validate_events(&ctx, batch, false).unwrap();
assert_eq!(events.len(), 2);
for ev in &events {
assert_eq!(ev.result, EventResult::Drop);
@@ -1142,7 +1188,7 @@ mod tests {
illegal_event.distinct_id = id.to_string();
let legal_event = valid_event();
let batch = valid_batch(vec![illegal_event, legal_event]);
- let events = validate_events(&ctx, batch).unwrap();
+ let events = validate_events(&ctx, batch, false).unwrap();
assert_eq!(events.len(), 2, "id={id:?}");
let flagged = &events[0];
@@ -1167,7 +1213,7 @@ mod tests {
let ctx = test_utils::test_context();
let event = deserialized_event(&Uuid::new_v4().to_string(), " NULL ");
let batch = valid_batch(vec![event]);
- let events = validate_events(&ctx, batch).unwrap();
+ let events = validate_events(&ctx, batch, false).unwrap();
assert_eq!(events[0].result, EventResult::Ok);
assert!(events[0].force_disable_person_processing);
assert_eq!(events[0].details, Some(DETAIL_PERSON_PROCESSING_DISABLED));
@@ -1180,7 +1226,7 @@ mod tests {
let mut illegal_event = valid_event();
illegal_event.distinct_id = id.to_string();
let batch = valid_batch(vec![illegal_event]);
- let events = validate_events(&ctx, batch).unwrap();
+ let events = validate_events(&ctx, batch, false).unwrap();
assert_eq!(events.len(), 1, "id={id:?}");
assert!(events[0].should_publish(), "id={id:?}");
}
@@ -1207,7 +1253,7 @@ mod tests {
},
],
};
- let err = validate_events(&ctx, batch).unwrap_err();
+ let err = validate_events(&ctx, batch, false).unwrap_err();
assert!(matches!(err, Error::DuplicateEventUuid(_)));
}
@@ -1223,7 +1269,7 @@ mod tests {
..valid_event()
}],
};
- let err = validate_events(&ctx, batch).unwrap_err();
+ let err = validate_events(&ctx, batch, false).unwrap_err();
assert!(matches!(err, Error::InvalidEventUuid(_)));
}
@@ -1239,7 +1285,7 @@ mod tests {
..valid_event()
}],
};
- let err = validate_events(&ctx, batch).unwrap_err();
+ let err = validate_events(&ctx, batch, false).unwrap_err();
assert!(matches!(err, Error::MissingEventUuid));
}
@@ -1271,7 +1317,7 @@ mod tests {
let count = dropped_count("duplicate_event_uuid", "validation_abort", || {
assert!(matches!(
- validate_events(&ctx, batch).unwrap_err(),
+ validate_events(&ctx, batch, false).unwrap_err(),
Error::DuplicateEventUuid(_)
));
});
@@ -1293,7 +1339,7 @@ mod tests {
let count = dropped_count("invalid_event_uuid", "validation_abort", || {
assert!(matches!(
- validate_events(&ctx, batch).unwrap_err(),
+ validate_events(&ctx, batch, false).unwrap_err(),
Error::InvalidEventUuid(_)
));
});
@@ -1313,7 +1359,7 @@ mod tests {
let count = dropped_count("missing_event_uuid", "validation_abort", || {
assert!(matches!(
- validate_events(&ctx, batch).unwrap_err(),
+ validate_events(&ctx, batch, false).unwrap_err(),
Error::MissingEventUuid
));
});
@@ -1361,7 +1407,7 @@ mod tests {
let event = deserialized_event(&padded_uuid, "user-42");
assert_eq!(event.uuid, inner_uuid.to_string());
let batch = valid_batch(vec![event]);
- let events = validate_events(&ctx, batch).unwrap();
+ let events = validate_events(&ctx, batch, false).unwrap();
assert_eq!(events.len(), 1);
assert_eq!(events[0].uuid, inner_uuid);
}
@@ -1380,7 +1426,7 @@ mod tests {
capture_internal: None,
batch: vec![bad_event],
};
- let events = validate_events(&ctx, batch).unwrap();
+ let events = validate_events(&ctx, batch, false).unwrap();
assert_eq!(events.len(), 1);
let event = &events[0];
assert_eq!(event.uuid, uuid);
@@ -1406,7 +1452,7 @@ mod tests {
capture_internal: None,
batch: vec![good, bad],
};
- let events = validate_events(&ctx, batch).unwrap();
+ let events = validate_events(&ctx, batch, false).unwrap();
assert_eq!(events.len(), 2);
assert_eq!(events[0].result, EventResult::Ok);
@@ -1435,7 +1481,7 @@ mod tests {
capture_internal: None,
batch: vec![ev1, ev2],
};
- let result = validate_events(&ctx, batch);
+ let result = validate_events(&ctx, batch, false);
assert!(result.is_ok());
let events = result.unwrap();
assert_eq!(events[0].result, EventResult::Drop);
@@ -1457,7 +1503,7 @@ mod tests {
capture_internal: None,
batch: vec![ev],
};
- let events = validate_events(&ctx, batch).unwrap();
+ let events = validate_events(&ctx, batch, false).unwrap();
assert_eq!(events[0].result, EventResult::Ok);
assert_eq!(events[0].options.disable_skew_correction, Some(true));
}
@@ -1481,7 +1527,7 @@ mod tests {
capture_internal: None,
batch: vec![ev],
};
- let events = validate_events(&ctx, batch).unwrap();
+ let events = validate_events(&ctx, batch, false).unwrap();
assert_eq!(events[0].result, EventResult::Drop);
assert_eq!(events[0].details, Some("missing_event_name"));
}
@@ -1608,7 +1654,7 @@ mod tests {
let mut events = vec![wrapped_event("$pageview", "user-1")];
let now_ts = Utc::now().timestamp();
- apply_restrictions(&service, "phc_token", now_ts, &mut events).await;
+ apply_restrictions(&service, "phc_token", now_ts, false, &mut events).await;
let ev = find_by_did(&events, "user-1");
assert_eq!(ev.result, EventResult::Ok);
@@ -1634,7 +1680,7 @@ mod tests {
];
let now_ts = Utc::now().timestamp();
- apply_restrictions(&service, "phc_token", now_ts, &mut events).await;
+ apply_restrictions(&service, "phc_token", now_ts, false, &mut events).await;
for ev in &events {
assert_eq!(ev.result, EventResult::Drop);
@@ -1659,7 +1705,7 @@ mod tests {
let mut events = vec![malformed, wrapped_event("$pageview", "user-valid")];
let now_ts = Utc::now().timestamp();
- apply_restrictions(&service, "phc_token", now_ts, &mut events).await;
+ apply_restrictions(&service, "phc_token", now_ts, false, &mut events).await;
// malformed event stays Drop with original destination, not re-evaluated
let mal = find_by_did(&events, &malformed_did);
@@ -1686,13 +1732,56 @@ mod tests {
let mut events = vec![wrapped_event("$pageview", "user-1")];
let now_ts = Utc::now().timestamp();
- apply_restrictions(&service, "phc_token", now_ts, &mut events).await;
+ apply_restrictions(&service, "phc_token", now_ts, false, &mut events).await;
let ev = find_by_did(&events, "user-1");
assert_eq!(ev.result, EventResult::Ok);
assert_eq!(ev.destination, Destination::Overflow);
}
+ /// A diverted AI event consults ai-scoped restrictions: an ai-scoped
+ /// ForceOverflow reroutes it to the AI overflow destination when the
+ /// valve is armed and leaves it untouched when not, while an
+ /// analytics-scoped ForceOverflow never crosses into the AI lane.
+ #[rstest::rstest]
+ #[case::armed(Pipeline::Ai, true, Destination::AiEventsOverflow)]
+ #[case::unarmed(Pipeline::Ai, false, Destination::AiEvents)]
+ #[case::analytics_scoped_does_not_cross(Pipeline::Analytics, true, Destination::AiEvents)]
+ #[tokio::test]
+ async fn restrictions_force_overflow_ai_events_gated_on_valve(
+ #[case] restriction_pipeline: Pipeline,
+ #[case] ai_events_overflow_enabled: bool,
+ #[case] expected_destination: Destination,
+ ) {
+ let service = restriction_service_for_pipeline(
+ restriction_pipeline,
+ "phc_token",
+ vec![Restriction {
+ restriction_type: RestrictionType::ForceOverflow,
+ scope: RestrictionScope::AllEvents,
+ args: None,
+ }],
+ )
+ .await;
+
+ let mut events = vec![wrapped_event("$ai_generation", "user-1")];
+ events[0].destination = Destination::AiEvents;
+ let now_ts = Utc::now().timestamp();
+
+ apply_restrictions(
+ &service,
+ "phc_token",
+ now_ts,
+ ai_events_overflow_enabled,
+ &mut events,
+ )
+ .await;
+
+ let ev = find_by_did(&events, "user-1");
+ assert_eq!(ev.result, EventResult::Ok);
+ assert_eq!(ev.destination, expected_destination);
+ }
+
#[tokio::test]
async fn restrictions_redirect_to_dlq() {
let service = restriction_service(
@@ -1708,7 +1797,7 @@ mod tests {
let mut events = vec![wrapped_event("$pageview", "user-1")];
let now_ts = Utc::now().timestamp();
- apply_restrictions(&service, "phc_token", now_ts, &mut events).await;
+ apply_restrictions(&service, "phc_token", now_ts, false, &mut events).await;
let ev = find_by_did(&events, "user-1");
assert_eq!(ev.result, EventResult::Ok);
@@ -1730,7 +1819,7 @@ mod tests {
let mut events = vec![wrapped_event("$pageview", "user-1")];
let now_ts = Utc::now().timestamp();
- apply_restrictions(&service, "phc_token", now_ts, &mut events).await;
+ apply_restrictions(&service, "phc_token", now_ts, false, &mut events).await;
let ev = find_by_did(&events, "user-1");
assert_eq!(ev.result, EventResult::Ok);
@@ -1755,7 +1844,7 @@ mod tests {
let mut events = vec![wrapped_event("$pageview", "user-1")];
let now_ts = Utc::now().timestamp();
- apply_restrictions(&service, "phc_token", now_ts, &mut events).await;
+ apply_restrictions(&service, "phc_token", now_ts, false, &mut events).await;
let ev = find_by_did(&events, "user-1");
assert_eq!(ev.result, EventResult::Ok);
@@ -1790,7 +1879,7 @@ mod tests {
let mut events = vec![wrapped_event("$pageview", "user-1")];
let now_ts = Utc::now().timestamp();
- apply_restrictions(&service, "phc_token", now_ts, &mut events).await;
+ apply_restrictions(&service, "phc_token", now_ts, false, &mut events).await;
let ev = find_by_did(&events, "user-1");
assert_eq!(ev.result, EventResult::Ok);
@@ -1812,7 +1901,7 @@ mod tests {
let mut events = vec![wrapped_event("$pageview", "user-1")];
let now_ts = Utc::now().timestamp();
- apply_restrictions(&service, "phc_token", now_ts, &mut events).await;
+ apply_restrictions(&service, "phc_token", now_ts, false, &mut events).await;
let ev = find_by_did(&events, "user-1");
assert_eq!(ev.result, EventResult::Ok);
@@ -1822,14 +1911,39 @@ mod tests {
// --- destination_for_event_name ---
#[rstest::rstest]
- #[case("$exception", Destination::ExceptionErrorTracking)]
- #[case("$$heatmap", Destination::HeatmapMain)]
- #[case("$$client_ingestion_warning", Destination::ClientIngestionWarning)]
- #[case("$pageview", Destination::AnalyticsMain)]
- #[case("custom_event", Destination::AnalyticsMain)]
- #[case("$autocapture", Destination::AnalyticsMain)]
- fn destination_for_event_name_mapping(#[case] event_name: &str, #[case] expected: Destination) {
- assert_eq!(destination_for_event_name(event_name), expected);
+ // Non-AI mappings are identical regardless of the AI routing flag.
+ #[case("$exception", false, Destination::ExceptionErrorTracking)]
+ #[case("$exception", true, Destination::ExceptionErrorTracking)]
+ #[case("$$heatmap", false, Destination::HeatmapMain)]
+ #[case("$$heatmap", true, Destination::HeatmapMain)]
+ #[case(
+ "$$client_ingestion_warning",
+ false,
+ Destination::ClientIngestionWarning
+ )]
+ #[case(
+ "$$client_ingestion_warning",
+ true,
+ Destination::ClientIngestionWarning
+ )]
+ #[case("$pageview", false, Destination::AnalyticsMain)]
+ #[case("$pageview", true, Destination::AnalyticsMain)]
+ #[case("custom_event", false, Destination::AnalyticsMain)]
+ #[case("$autocapture", false, Destination::AnalyticsMain)]
+ // $ai_* diverts only when AI routing is enabled; otherwise stays on Main.
+ #[case("$ai_generation", true, Destination::AiEvents)]
+ #[case("$ai_span", true, Destination::AiEvents)]
+ #[case("$ai_trace", true, Destination::AiEvents)]
+ #[case("$ai_generation", false, Destination::AnalyticsMain)]
+ fn destination_for_event_name_mapping(
+ #[case] event_name: &str,
+ #[case] route_ai_events: bool,
+ #[case] expected: Destination,
+ ) {
+ assert_eq!(
+ destination_for_event_name(event_name, route_ai_events),
+ expected
+ );
}
// --- restrictions bypass pipeline-less events ---
@@ -1860,7 +1974,7 @@ mod tests {
let mut events = vec![ev];
let now_ts = Utc::now().timestamp();
- apply_restrictions(&service, "phc_token", now_ts, &mut events).await;
+ apply_restrictions(&service, "phc_token", now_ts, false, &mut events).await;
assert_eq!(events[0].result, EventResult::Ok);
assert_eq!(events[0].destination, expected_dest);
@@ -1887,7 +2001,7 @@ mod tests {
events[1].destination = Destination::ExceptionErrorTracking;
let now_ts = Utc::now().timestamp();
- apply_restrictions(&service, "phc_token", now_ts, &mut events).await;
+ apply_restrictions(&service, "phc_token", now_ts, false, &mut events).await;
// Analytics event gets dropped by analytics-pipeline restriction
assert_eq!(events[0].result, EventResult::Drop);
@@ -1922,7 +2036,7 @@ mod tests {
events[0].destination = Destination::ExceptionErrorTracking;
let now_ts = Utc::now().timestamp();
- apply_restrictions(&service, "phc_token", now_ts, &mut events).await;
+ apply_restrictions(&service, "phc_token", now_ts, false, &mut events).await;
assert_eq!(
events[0].result,
@@ -1951,7 +2065,7 @@ mod tests {
events[0].destination = Destination::ExceptionErrorTracking;
let now_ts = Utc::now().timestamp();
- apply_restrictions(&service, "phc_token", now_ts, &mut events).await;
+ apply_restrictions(&service, "phc_token", now_ts, false, &mut events).await;
assert_eq!(events[0].result, EventResult::Ok);
assert_eq!(
@@ -1978,7 +2092,7 @@ mod tests {
events[0].destination = Destination::ExceptionErrorTracking;
let now_ts = Utc::now().timestamp();
- apply_restrictions(&service, "phc_token", now_ts, &mut events).await;
+ apply_restrictions(&service, "phc_token", now_ts, false, &mut events).await;
assert_eq!(events[0].result, EventResult::Ok);
assert_eq!(events[0].destination, Destination::ExceptionErrorTracking);
@@ -2002,7 +2116,7 @@ mod tests {
events[0].destination = Destination::ExceptionErrorTracking;
let now_ts = Utc::now().timestamp();
- apply_restrictions(&service, "phc_token", now_ts, &mut events).await;
+ apply_restrictions(&service, "phc_token", now_ts, false, &mut events).await;
assert_eq!(events[0].result, EventResult::Ok);
assert_eq!(events[0].destination, Destination::Dlq);
@@ -2025,7 +2139,7 @@ mod tests {
events[0].destination = Destination::ExceptionErrorTracking;
let now_ts = Utc::now().timestamp();
- apply_restrictions(&service, "phc_token", now_ts, &mut events).await;
+ apply_restrictions(&service, "phc_token", now_ts, false, &mut events).await;
assert_eq!(events[0].result, EventResult::Ok);
assert_eq!(
@@ -2058,7 +2172,7 @@ mod tests {
events[0].destination = Destination::ExceptionErrorTracking;
let now_ts = Utc::now().timestamp();
- apply_restrictions(&service, "phc_token", now_ts, &mut events).await;
+ apply_restrictions(&service, "phc_token", now_ts, false, &mut events).await;
assert_eq!(events[0].result, EventResult::Ok);
assert_eq!(events[0].destination, Destination::Dlq);
@@ -2478,7 +2592,7 @@ mod tests {
};
let batch = valid_batch(vec![normal_a, perf, normal_b, normal_c]);
- let events = validate_events(&ctx, batch).unwrap();
+ let events = validate_events(&ctx, batch, false).unwrap();
assert_eq!(
distinct_id_sequence(&events),
@@ -2492,7 +2606,7 @@ mod tests {
let ctx = test_utils::test_context();
let (first, second) = test_utils::realistic_dup_uuid_pair();
let batch = valid_batch(vec![first, second]);
- let err = validate_events(&ctx, batch).unwrap_err();
+ let err = validate_events(&ctx, batch, false).unwrap_err();
assert!(matches!(err, Error::DuplicateEventUuid(_)));
}
@@ -2543,7 +2657,7 @@ mod tests {
];
let now_ts = Utc::now().timestamp();
- apply_restrictions(&service, "phc_token", now_ts, &mut events).await;
+ apply_restrictions(&service, "phc_token", now_ts, false, &mut events).await;
assert_eq!(
distinct_id_sequence(&events),
@@ -2627,7 +2741,7 @@ mod tests {
EventRestrictionService::new(vec![Pipeline::Analytics], StdDuration::from_secs(300));
service.update(RestrictionManager::new()).await;
let now_ts = Utc::now().timestamp();
- apply_restrictions(&service, "phc_token", now_ts, &mut events).await;
+ apply_restrictions(&service, "phc_token", now_ts, false, &mut events).await;
assert_eq!(
distinct_id_sequence(&events),
expected,
@@ -2648,24 +2762,28 @@ mod tests {
// --- apply_overflow_stamping ---
- fn overflow_limiter(per_second: u32, burst: u32, force_keys: Option<&str>) -> OverflowLimiter {
+ fn overflow_limiter(
+ per_second: u32,
+ burst: u32,
+ force_keys: Option<&str>,
+ ) -> Arc<OverflowLimiter> {
use std::num::NonZeroU32;
- OverflowLimiter::new(
+ Arc::new(OverflowLimiter::new(
NonZeroU32::new(per_second).unwrap(),
NonZeroU32::new(burst).unwrap(),
force_keys.map(String::from),
false,
- )
+ ))
}
- fn overflow_limiter_preserving(per_second: u32, burst: u32) -> OverflowLimiter {
+ fn overflow_limiter_preserving(per_second: u32, burst: u32) -> Arc<OverflowLimiter> {
use std::num::NonZeroU32;
- OverflowLimiter::new(
+ Arc::new(OverflowLimiter::new(
NonZeroU32::new(per_second).unwrap(),
NonZeroU32::new(burst).unwrap(),
None,
true,
- )
+ ))
}
#[test]
@@ -2674,7 +2792,7 @@ mod tests {
let mut events = vec![wrapped_event("$pageview", "user-1")];
let limiter = overflow_limiter(100, 100, None);
- apply_overflow_stamping(&limiter, &ctx, &mut events);
+ apply_overflow_stamping(Some(&limiter), None, &ctx, &mut events);
assert_eq!(events[0].destination, Destination::AnalyticsMain);
assert!(!events[0].force_disable_person_processing);
@@ -2687,7 +2805,7 @@ mod tests {
let mut events = vec![wrapped_event("$pageview", "user-1")];
let limiter = overflow_limiter(100, 100, Some("phc_tok:user-1"));
- apply_overflow_stamping(&limiter, &ctx, &mut events);
+ apply_overflow_stamping(Some(&limiter), None, &ctx, &mut events);
assert_eq!(events[0].destination, Destination::Overflow);
assert!(events[0].force_disable_person_processing);
@@ -2700,7 +2818,7 @@ mod tests {
let mut events = vec![wrapped_event("$pageview", "user-1")];
let limiter = overflow_limiter(100, 100, Some("phc_tok"));
- apply_overflow_stamping(&limiter, &ctx, &mut events);
+ apply_overflow_stamping(Some(&limiter), None, &ctx, &mut events);
assert_eq!(events[0].destination, Destination::Overflow);
assert!(events[0].force_disable_person_processing);
@@ -2717,7 +2835,7 @@ mod tests {
wrapped_event("$pageview", "user-1"),
];
- apply_overflow_stamping(&limiter, &ctx, &mut events);
+ apply_overflow_stamping(Some(&limiter), None, &ctx, &mut events);
assert_eq!(events[0].destination, Destination::AnalyticsMain);
assert!(!events[0].force_disable_person_processing);
@@ -2735,7 +2853,7 @@ mod tests {
wrapped_event("$pageview", "user-1"),
];
- apply_overflow_stamping(&limiter, &ctx, &mut events);
+ apply_overflow_stamping(Some(&limiter), None, &ctx, &mut events);
assert_eq!(events[1].destination, Destination::Overflow);
assert!(
@@ -2751,7 +2869,7 @@ mod tests {
let mut events = vec![wrapped_event("$pageview", "user-1")];
events[0].destination = Destination::AnalyticsHistorical;
- apply_overflow_stamping(&limiter, &ctx, &mut events);
+ apply_overflow_stamping(Some(&limiter), None, &ctx, &mut events);
assert_eq!(
events[0].destination,
@@ -2767,10 +2885,103 @@ mod tests {
let mut events = vec![wrapped_event("$pageview", "user-1")];
events[0].result = EventResult::Drop;
- apply_overflow_stamping(&limiter, &ctx, &mut events);
+ apply_overflow_stamping(Some(&limiter), None, &ctx, &mut events);
assert_eq!(events[0].destination, Destination::AnalyticsMain);
}
+
+ /// The AI lane converts to its own overflow destination under the same
+ /// conditions as AnalyticsMain, but only when its limiter is present
+ /// (setup builds it exactly when the AI overflow valve is armed); absent
+ /// it is never touched.
+ #[rstest::rstest]
+ #[case::limiter_present(true, Destination::AiEventsOverflow, true)]
+ #[case::limiter_absent(false, Destination::AiEvents, false)]
+ fn overflow_ai_events_gated_on_limiter_presence(
+ #[case] ai_limiter_present: bool,
+ #[case] expected_destination: Destination,
+ #[case] expected_force_disable: bool,
+ ) {
+ let mut ctx = test_utils::test_context();
+ ctx.api_token = "phc_tok".to_string();
+ let limiter = overflow_limiter(100, 100, Some("phc_tok:user-1"));
+ let ai_limiter = ai_limiter_present.then_some(&limiter);
+ let mut events = vec![wrapped_event("$ai_generation", "user-1")];
+ events[0].destination = Destination::AiEvents;
+
+ apply_overflow_stamping(None, ai_limiter, &ctx, &mut events);
+
+ assert_eq!(events[0].destination, expected_destination);
+ assert_eq!(
+ events[0].force_disable_person_processing,
+ expected_force_disable
+ );
+ }
+
+ #[test]
+ fn overflow_ai_events_rate_limited_preserves_locality_when_configured() {
+ let mut ctx = test_utils::test_context();
+ ctx.api_token = "phc_tok".to_string();
+ let limiter = overflow_limiter_preserving(1, 1);
+ let mut events = vec![
+ wrapped_event("$ai_generation", "user-1"),
+ wrapped_event("$ai_generation", "user-1"),
+ ];
+ events[0].destination = Destination::AiEvents;
+ events[1].destination = Destination::AiEvents;
+
+ apply_overflow_stamping(None, Some(&limiter), &ctx, &mut events);
+
+ assert_eq!(events[0].destination, Destination::AiEvents);
+ assert_eq!(events[1].destination, Destination::AiEventsOverflow);
+ assert!(
+ !events[1].force_disable_person_processing,
+ "preserve_locality=true means person processing stays enabled"
+ );
+ }
+
+ /// The two lanes consult separate limiter instances: a key the analytics
+ /// limiter force-routes must not drag the same key's AI event into AI
+ /// overflow, and vice versa.
+ #[rstest::rstest]
+ #[case::analytics_force_key_leaves_ai_untouched(
+ Some("phc_tok:user-1"),
+ None,
+ Destination::Overflow,
+ Destination::AiEvents
+ )]
+ #[case::ai_force_key_leaves_analytics_untouched(
+ None,
+ Some("phc_tok:user-1"),
+ Destination::AnalyticsMain,
+ Destination::AiEventsOverflow
+ )]
+ fn overflow_lane_budgets_are_isolated_per_key(
+ #[case] analytics_force_keys: Option<&str>,
+ #[case] ai_force_keys: Option<&str>,
+ #[case] expected_analytics_destination: Destination,
+ #[case] expected_ai_destination: Destination,
+ ) {
+ let mut ctx = test_utils::test_context();
+ ctx.api_token = "phc_tok".to_string();
+ let analytics_limiter = overflow_limiter(100, 100, analytics_force_keys);
+ let ai_limiter = overflow_limiter(100, 100, ai_force_keys);
+ let mut events = vec![
+ wrapped_event("$pageview", "user-1"),
+ wrapped_event("$ai_generation", "user-1"),
+ ];
+ events[1].destination = Destination::AiEvents;
+
+ apply_overflow_stamping(
+ Some(&analytics_limiter),
+ Some(&ai_limiter),
+ &ctx,
+ &mut events,
+ );
+
+ assert_eq!(events[0].destination, expected_analytics_destination);
+ assert_eq!(events[1].destination, expected_ai_destination);
+ }
// =========================================================================
// apply_gateway_provenance tests — the verify→billing wiring
// =========================================================================
@@ -3064,6 +3275,74 @@ mod tests {
});
}
+ /// process_batch wiring: the AI routing decision is derived once per batch
+ /// from the request token, so with a `SecondaryAllowlist` policy the same
+ /// `$ai_*` event lands on the AI topic only when the batch token is listed.
+ #[rstest::rstest]
+ #[case("phc_allowlisted", "ai_events")]
+ #[case("phc_other", "events_main")]
+ #[tokio::test]
+ async fn process_batch_gates_ai_topic_on_batch_token(
+ #[case] token: &str,
+ #[case] expected_topic: &str,
+ ) {
+ let allowlist: HashSet<String> = ["phc_allowlisted".to_string()].into_iter().collect();
+ let ts = TestStateBuilder::new()
+ .with_ai_routing(crate::config::AiRouting::SecondaryAllowlist(allowlist))
+ .build();
+ let mut ctx = gateway_context(token, Utc::now(), None);
+ let batch = valid_batch(vec![Event {
+ event: "$ai_generation".to_string(),
+ ..valid_event()
+ }]);
+
+ process_batch(&ts.state, &mut ctx, batch).await.unwrap();
+
+ ts.mock_producer.with_records(|records| {
+ assert_eq!(records.len(), 1, "the event must be published");
+ assert_eq!(records[0].topic, expected_topic);
+ });
+ }
+
+ /// process_batch wiring: overflow stamping must run when only the AI-lane
+ /// limiter is armed (analytics limiter unset), with the state's AI limiter
+ /// governing the AI lane — a bursting key's second `$ai_*` event lands on
+ /// the AI overflow topic while an analytics event on the same key stays on
+ /// the main topic (it would overflow instead if the limiter arguments were
+ /// ever swapped).
+ #[tokio::test]
+ async fn process_batch_routes_ai_overflow_with_only_ai_limiter_armed() {
+ let ts = TestStateBuilder::new()
+ .with_ai_routing(crate::config::AiRouting::Secondary)
+ .with_ai_events_overflow_limiter(1, 1)
+ .build();
+ let mut ctx = test_utils::test_analytics_context();
+ // All three events share the token:distinct_id overflow key; burst=1
+ // lets the first AI event through and overflows the second.
+ let batch = valid_batch(vec![
+ Event {
+ event: "$ai_generation".to_string(),
+ ..valid_event()
+ },
+ Event {
+ event: "$ai_generation".to_string(),
+ ..valid_event()
+ },
+ valid_event(),
+ ]);
+
+ process_batch(&ts.state, &mut ctx, batch).await.unwrap();
+
+ ts.mock_producer.with_records(|records| {
+ let mut topics: Vec<&str> = records.iter().map(|r| r.topic.as_str()).collect();
+ topics.sort_unstable();
+ assert_eq!(
+ topics,
+ vec!["ai_events", "ai_events_overflow", "events_main"]
+ );
+ });
+ }
+
// =========================================================================
// merge_sink_results tests
// =========================================================================
diff --git a/rust/capture/src/v1/quota_limiter_shim.rs b/rust/capture/src/v1/quota_limiter_shim.rs
index 1ec79b7eda75..7254d3fe794c 100644
--- a/rust/capture/src/v1/quota_limiter_shim.rs
+++ b/rust/capture/src/v1/quota_limiter_shim.rs
@@ -171,6 +171,8 @@ mod tests {
kafka_heatmaps_topic: "events_plugin_ingestion".to_string(),
kafka_replay_overflow_topic: "session_recording_snapshot_item_overflow".to_string(),
kafka_dlq_topic: "events_plugin_ingestion_dlq".to_string(),
+ capture_analytics_ai_events_topic: None,
+ capture_analytics_ai_events_overflow_topic: None,
kafka_traces_topic: "ingestion_traces".to_string(),
kafka_metrics_topic: "ingestion_metrics".to_string(),
kafka_tls: false,
@@ -242,6 +244,8 @@ mod tests {
ai_secondary_kafka_topic: None,
ai_secondary_kafka_tls: false,
ai_secondary_kafka_client_id: String::new(),
+ capture_analytics_ai_events_mode: crate::config::AiSinkMode::Primary,
+ capture_analytics_ai_events_allowlist_tokens: None,
http1_header_read_timeout_ms: Some(5000),
body_chunk_read_timeout_ms: None,
body_read_chunk_size_kb: 256,
diff --git a/rust/capture/src/v1/sinks/kafka/config.rs b/rust/capture/src/v1/sinks/kafka/config.rs
index 4b1ed71d3597..acfd1d027a32 100644
--- a/rust/capture/src/v1/sinks/kafka/config.rs
+++ b/rust/capture/src/v1/sinks/kafka/config.rs
@@ -104,6 +104,16 @@ pub struct Config {
pub topic_exception: String,
pub topic_heatmap: String,
pub topic_client_ingestion_warning: String,
+
+ /// Optional dedicated topic for `$ai_*` events. Not meant to be set via
+ /// per-sink env: setup injects the deployment-level `CAPTURE_ANALYTICS_AI_EVENTS_TOPIC` into
+ /// every sink config, overwriting whatever the env parse produced.
+ pub topic_ai: Option<String>,
+
+ /// Optional overflow topic for the AI lane. Like `topic_ai`, injected at
+ /// setup from the deployment-level `CAPTURE_ANALYTICS_AI_EVENTS_OVERFLOW_TOPIC`; unset
+ /// means the pipeline never produces `Destination::AiEventsOverflow`.
+ pub topic_ai_overflow: Option<String>,
}
const VALID_ACKS: &[&str] = &["0", "1", "-1", "all"];
@@ -158,6 +168,8 @@ impl Config {
Destination::ExceptionErrorTracking => Some(&self.topic_exception),
Destination::HeatmapMain => Some(&self.topic_heatmap),
Destination::ClientIngestionWarning => Some(&self.topic_client_ingestion_warning),
+ Destination::AiEvents => self.topic_ai.as_deref(),
+ Destination::AiEventsOverflow => self.topic_ai_overflow.as_deref(),
Destination::Custom(t) => Some(t.as_str()),
Destination::Drop => None,
}
@@ -387,4 +399,34 @@ mod tests {
let cfg = Config::init_from_hashmap(&required_kafka_env()).unwrap();
assert_eq!(cfg.topic_for(&dest), expected);
}
+
+ #[test]
+ fn topic_ai_absent_defaults_to_none() {
+ let cfg = Config::init_from_hashmap(&required_kafka_env()).unwrap();
+ assert_eq!(cfg.topic_ai, None);
+ assert_eq!(cfg.topic_for(&Destination::AiEvents), None);
+ assert_eq!(cfg.topic_ai_overflow, None);
+ assert_eq!(cfg.topic_for(&Destination::AiEventsOverflow), None);
+ }
+
+ #[test]
+ fn topic_ai_overflow_present_resolves_destination() {
+ // Set the field directly, mirroring how setup injects
+ // CAPTURE_ANALYTICS_AI_EVENTS_OVERFLOW_TOPIC into sink configs after env loading.
+ let mut cfg = Config::init_from_hashmap(&required_kafka_env()).unwrap();
+ cfg.topic_ai_overflow = Some("ai_events_overflow".to_string());
+ assert_eq!(
+ cfg.topic_for(&Destination::AiEventsOverflow),
+ Some("ai_events_overflow")
+ );
+ }
+
+ #[test]
+ fn topic_ai_present_resolves_destination() {
+ // Set the field directly, mirroring how setup injects CAPTURE_ANALYTICS_AI_EVENTS_TOPIC
+ // into sink configs after env loading.
+ let mut cfg = Config::init_from_hashmap(&required_kafka_env()).unwrap();
+ cfg.topic_ai = Some("ai_events".to_string());
+ assert_eq!(cfg.topic_for(&Destination::AiEvents), Some("ai_events"));
+ }
}
diff --git a/rust/capture/src/v1/sinks/kafka/sink.rs b/rust/capture/src/v1/sinks/kafka/sink.rs
index d4405df44b15..20c6bba9bd58 100644
--- a/rust/capture/src/v1/sinks/kafka/sink.rs
+++ b/rust/capture/src/v1/sinks/kafka/sink.rs
@@ -24,8 +24,9 @@ use super::types::{KafkaResult, KafkaSinkError};
use super::KafkaProducerTrait;
/// Returns true when the partition key should be nulled — i.e. when person
-/// processing is force-disabled for Main/Overflow destinations, spreading
-/// load across partitions instead of hotspotting on a single key.
+/// processing is force-disabled for Main/Overflow-shaped destinations
+/// (including the AI lane's own overflow), spreading load across partitions
+/// instead of hotspotting on a single key.
fn should_null_partition_key(
force_disable_person_processing: bool,
destination: &Destination,
@@ -33,7 +34,7 @@ fn should_null_partition_key(
force_disable_person_processing
&& matches!(
destination,
- Destination::AnalyticsMain | Destination::Overflow
+ Destination::AnalyticsMain | Destination::Overflow | Destination::AiEventsOverflow
)
}
@@ -460,10 +461,13 @@ mod should_null_partition_key_tests {
#[rstest]
#[case::main_disabled(true, Destination::AnalyticsMain, true)]
#[case::overflow_disabled(true, Destination::Overflow, true)]
+ #[case::ai_overflow_disabled(true, Destination::AiEventsOverflow, true)]
+ #[case::ai_disabled(true, Destination::AiEvents, false)]
#[case::dlq_disabled(true, Destination::Dlq, false)]
#[case::historical_disabled(true, Destination::AnalyticsHistorical, false)]
#[case::custom_disabled(true, Destination::Custom("t".into()), false)]
#[case::main_not_disabled(false, Destination::AnalyticsMain, false)]
+ #[case::ai_overflow_not_disabled(false, Destination::AiEventsOverflow, false)]
fn policy(#[case] force_disable: bool, #[case] dest: Destination, #[case] expected: bool) {
assert_eq!(should_null_partition_key(force_disable, &dest), expected);
}
diff --git a/rust/capture/src/v1/sinks/types.rs b/rust/capture/src/v1/sinks/types.rs
index 33216b418206..36581674364f 100644
--- a/rust/capture/src/v1/sinks/types.rs
+++ b/rust/capture/src/v1/sinks/types.rs
@@ -5,6 +5,8 @@ use std::fmt;
use common_types::CapturedEventHeaders;
use uuid::Uuid;
+use crate::event_restrictions::Pipeline;
+
/// Kafka topic routing for a processed event.
/// `Drop` means the event should not be produced at all.
#[derive(Debug, Default, Clone, PartialEq, Eq)]
@@ -19,16 +21,42 @@ pub enum Destination {
ExceptionErrorTracking,
HeatmapMain,
ClientIngestionWarning,
+ AiEvents,
+ /// Overflow lane for `AiEvents`. Only produced when the AI overflow
+ /// valve (`CAPTURE_ANALYTICS_AI_EVENTS_OVERFLOW_TOPIC`) is armed; overflow on the AI lane
+ /// lands here, never on the analytics `Overflow` destination.
+ AiEventsOverflow,
}
impl Destination {
/// Returns true for destinations that flow through the analytics ingestion
/// pipeline (and are therefore subject to analytics-scoped restrictions,
/// overflow routing, etc). Mirrors legacy `DataType::is_analytics_pipeline`.
+ ///
+ /// `AiEvents` is false: `$ai_*` events are diverted out of the analytics
+ /// pipeline into a dedicated AI lane, just like heatmaps/exceptions.
pub fn is_analytics_pipeline(&self) -> bool {
matches!(self, Self::AnalyticsMain | Self::AnalyticsHistorical)
}
+ /// Restriction pipeline this destination is governed by, if any. Mirrors
+ /// legacy `DataType::pipeline`: the AI lane (including its overflow arm)
+ /// consults ai-scoped restrictions, the analytics lanes consult analytics
+ /// ones. `None` destinations flow through unrestricted — either they have
+ /// no shared restriction config (heatmaps, ingestion warnings) or they are
+ /// themselves restriction/terminal outcomes (Dlq, Custom, Drop).
+ pub fn pipeline(&self) -> Option<Pipeline> {
+ match self {
+ Self::AnalyticsMain | Self::AnalyticsHistorical | Self::Overflow => {
+ Some(Pipeline::Analytics)
+ }
+ Self::AiEvents | Self::AiEventsOverflow => Some(Pipeline::Ai),
+ Self::ExceptionErrorTracking => Some(Pipeline::ErrorTracking),
+ Self::HeatmapMain | Self::ClientIngestionWarning | Self::Dlq | Self::Custom(_) => None,
+ Self::Drop => None,
+ }
+ }
+
/// Stable, low-cardinality metric tag. `Custom(_)` collapses to "custom"
/// so admin-configured topic names never become label values.
pub fn as_tag(&self) -> &'static str {
@@ -42,6 +70,8 @@ impl Destination {
Self::ExceptionErrorTracking => "exception_error_tracking",
Self::HeatmapMain => "heatmap_main",
Self::ClientIngestionWarning => "client_ingestion_warning",
+ Self::AiEvents => "ai_events",
+ Self::AiEventsOverflow => "ai_events_overflow",
}
}
}
@@ -61,6 +91,8 @@ mod destination_tests {
assert!(!Destination::ExceptionErrorTracking.is_analytics_pipeline());
assert!(!Destination::HeatmapMain.is_analytics_pipeline());
assert!(!Destination::ClientIngestionWarning.is_analytics_pipeline());
+ assert!(!Destination::AiEvents.is_analytics_pipeline());
+ assert!(!Destination::AiEventsOverflow.is_analytics_pipeline());
assert!(!Destination::Overflow.is_analytics_pipeline());
assert!(!Destination::Dlq.is_analytics_pipeline());
assert!(!Destination::Drop.is_analytics_pipeline());
@@ -91,6 +123,8 @@ mod destination_tests {
Destination::ClientIngestionWarning,
"client_ingestion_warning",
),
+ (Destination::AiEvents, "ai_events"),
+ (Destination::AiEventsOverflow, "ai_events_overflow"),
];
let mut seen = std::collections::HashSet::new();
diff --git a/rust/capture/src/v1/test_utils.rs b/rust/capture/src/v1/test_utils.rs
index 8274fa4f1266..36b0988c940e 100644
--- a/rust/capture/src/v1/test_utils.rs
+++ b/rust/capture/src/v1/test_utils.rs
@@ -177,7 +177,14 @@ pub fn test_kafka_config() -> crate::v1::sinks::kafka::config::Config {
.into_iter()
.map(|(k, v)| (k.to_string(), v.to_string()))
.collect();
- envconfig::Envconfig::init_from_hashmap(&env).unwrap()
+ let mut cfg: crate::v1::sinks::kafka::config::Config =
+ envconfig::Envconfig::init_from_hashmap(&env).unwrap();
+ // Mirrors production, where setup injects the deployment-level
+ // CAPTURE_ANALYTICS_AI_EVENTS_TOPIC and CAPTURE_ANALYTICS_AI_EVENTS_OVERFLOW_TOPIC into every sink config
+ // after env loading.
+ cfg.topic_ai = Some("ai_events".to_string());
+ cfg.topic_ai_overflow = Some("ai_events_overflow".to_string());
+ cfg
}
// ---------------------------------------------------------------------------
@@ -671,11 +678,13 @@ pub struct TestState {
pub struct TestStateBuilder {
quota_limited: bool,
overflow_limiter: Option<(NonZeroU32, NonZeroU32)>,
+ ai_events_overflow_limiter: Option<(NonZeroU32, NonZeroU32)>,
historical_threshold_days: Option<i64>,
restriction_service: Option<EventRestrictionService>,
global_rate_limiter: Option<Arc<GlobalRateLimiter>>,
mock_producer: Option<Arc<MockProducer>>,
ai_gateway_signing_secret: Option<String>,
+ ai_routing: crate::config::AiRouting,
ingestion_warning_emitter: Option<Arc<dyn common_ingestion_warnings::WarningEmitter>>,
}
@@ -690,15 +699,23 @@ impl TestStateBuilder {
Self {
quota_limited: false,
overflow_limiter: None,
+ ai_events_overflow_limiter: None,
historical_threshold_days: None,
restriction_service: None,
global_rate_limiter: None,
mock_producer: None,
ai_gateway_signing_secret: None,
+ ai_routing: crate::config::AiRouting::Primary,
ingestion_warning_emitter: None,
}
}
+ /// Set the `$ai_*` topic routing policy (defaults to `Primary`: no diversion).
+ pub fn with_ai_routing(mut self, routing: crate::config::AiRouting) -> Self {
+ self.ai_routing = routing;
+ self
+ }
+
/// Configure quota limiter to reject all events for any token.
pub fn with_quota_limited(mut self) -> Self {
self.quota_limited = true;
@@ -720,6 +737,17 @@ impl TestStateBuilder {
self
}
+ /// Arm the AI overflow valve: a dedicated AI-lane limiter with the given
+ /// rate and burst. Also sets `ai_events_overflow_enabled`, mirroring
+ /// production where both derive from the same overflow-topic config.
+ pub fn with_ai_events_overflow_limiter(mut self, per_second: u32, burst: u32) -> Self {
+ self.ai_events_overflow_limiter = Some((
+ NonZeroU32::new(per_second).expect("per_second must be > 0"),
+ NonZeroU32::new(burst).expect("burst must be > 0"),
+ ));
+ self
+ }
+
/// Enable historical rerouting with the given threshold in days.
pub fn with_historical_rerouting(mut self, threshold_days: i64) -> Self {
self.historical_threshold_days = Some(threshold_days);
@@ -804,6 +832,11 @@ impl TestStateBuilder {
.overflow_limiter
.map(|(per_sec, burst)| Arc::new(OverflowLimiter::new(per_sec, burst, None, false)));
+ let ai_events_overflow_limiter = self
+ .ai_events_overflow_limiter
+ .map(|(per_sec, burst)| Arc::new(OverflowLimiter::new(per_sec, burst, None, false)));
+ let ai_events_overflow_enabled = ai_events_overflow_limiter.is_some();
+
// Build the v1 sink router with a MockProducer-backed KafkaSink
let mock_producer = self
.mock_producer
@@ -853,10 +886,13 @@ impl TestStateBuilder {
capture_v1_max_compressed_body_bytes: 2 * 1024 * 1024,
capture_v1_max_decompressed_body_bytes: 20 * 1024 * 1024,
overflow_limiter,
+ ai_events_overflow_limiter,
replay_overflow_limiter: None,
v1_sink_router: Some(Arc::new(v1_router)),
capture_v1_scatter_gather_min_batch: 8,
ai_gateway_signing_secret: self.ai_gateway_signing_secret,
+ ai_routing: self.ai_routing,
+ ai_events_overflow_enabled,
ingestion_warning_emitter: self.ingestion_warning_emitter,
};
diff --git a/rust/capture/tests/common/integration_utils.rs b/rust/capture/tests/common/integration_utils.rs
index 0a08aa035ccc..72fabffca9cf 100644
--- a/rust/capture/tests/common/integration_utils.rs
+++ b/rust/capture/tests/common/integration_utils.rs
@@ -7,7 +7,7 @@ use std::time::Duration;
use capture::{
api::{CaptureError, CaptureResponse, CaptureResponseCode},
- config::CaptureMode,
+ config::{AiRouting, CaptureMode},
quota_limiters::CaptureQuotaLimiter,
router::router,
sinks::Event,
@@ -1100,18 +1100,21 @@ fn setup_capture_router(unit: &TestCase) -> (Router, MemorySink) {
historical_rerouting_threshold_days,
is_mirror_deploy,
verbose_sample_percent,
- 26_214_400, // 25MB default for AI endpoint
- None, // ai_blob_storage
- None, // body_chunk_read_timeout_ms
- 256, // body_read_chunk_size_kb
- 10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
- 50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytes
- None, // overflow_limiter
- None, // replay_overflow_limiter
- None, // v1_sink_router
- 8, // capture_v1_scatter_gather_min_batch
- None, // ai_gateway_signing_secret
- None, // ingestion_warning_emitter
+ 26_214_400, // 25MB default for AI endpoint
+ None, // ai_blob_storage
+ None, // body_chunk_read_timeout_ms
+ 256, // body_read_chunk_size_kb
+ 10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
+ 50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytes
+ None, // overflow_limiter
+ None, // ai_events_overflow_limiter
+ None, // replay_overflow_limiter
+ None, // v1_sink_router
+ 8, // capture_v1_scatter_gather_min_batch
+ None, // ai_gateway_signing_secret
+ AiRouting::Primary, // ai_routing
+ false, // ai_events_overflow_enabled
+ None, // ingestion_warning_emitter
),
sink,
)
diff --git a/rust/capture/tests/common/utils.rs b/rust/capture/tests/common/utils.rs
index 7f68cf0d2322..da18b787da56 100644
--- a/rust/capture/tests/common/utils.rs
+++ b/rust/capture/tests/common/utils.rs
@@ -87,6 +87,8 @@ pub static DEFAULT_CONFIG: Lazy<Config> = Lazy::new(|| Config {
kafka_heatmaps_topic: "events_plugin_ingestion".to_string(),
kafka_replay_overflow_topic: "session_recording_snapshot_item_overflow".to_string(),
kafka_dlq_topic: "events_plugin_ingestion_dlq".to_string(),
+ capture_analytics_ai_events_topic: None,
+ capture_analytics_ai_events_overflow_topic: None,
kafka_traces_topic: "ingestion_traces".to_string(),
kafka_metrics_topic: "ingestion_metrics".to_string(),
kafka_tls: false,
@@ -158,6 +160,8 @@ pub static DEFAULT_CONFIG: Lazy<Config> = Lazy::new(|| Config {
ai_secondary_kafka_topic: None,
ai_secondary_kafka_tls: false,
ai_secondary_kafka_client_id: String::new(),
+ capture_analytics_ai_events_mode: capture::config::AiSinkMode::Primary,
+ capture_analytics_ai_events_allowlist_tokens: None,
http1_header_read_timeout_ms: Some(5000), // 5 seconds default
body_chunk_read_timeout_ms: None, // disabled by default in tests
body_read_chunk_size_kb: 256, // 256KB default
diff --git a/rust/capture/tests/integration_ai_endpoint.rs b/rust/capture/tests/integration_ai_endpoint.rs
index 009088880fd7..e97a912499ea 100644
--- a/rust/capture/tests/integration_ai_endpoint.rs
+++ b/rust/capture/tests/integration_ai_endpoint.rs
@@ -7,7 +7,7 @@ use axum::Router;
use axum_test_helper::TestClient;
use capture::ai_s3::{BlobStorage, MockBlobStorage};
use capture::api::CaptureError;
-use capture::config::CaptureMode;
+use capture::config::{AiRouting, CaptureMode};
use capture::quota_limiters::CaptureQuotaLimiter;
use capture::router::router;
use capture::sinks::Event;
@@ -193,10 +193,13 @@ fn setup_ai_test_router() -> Router {
10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytes
None, // overflow_limiter
+ None, // ai_events_overflow_limiter
None, // replay_overflow_limiter
None, // v1_sink_router
8, // capture_v1_scatter_gather_min_batch
None, // ai_gateway_signing_secret
+ AiRouting::Primary, // ai_routing
+ false, // ai_events_overflow_enabled
None, // ingestion_warning_emitter
)
}
@@ -1657,10 +1660,13 @@ fn setup_ai_test_router_with_capturing_sink() -> (Router, CapturingSink) {
10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytes
None, // overflow_limiter
+ None, // ai_events_overflow_limiter
None, // replay_overflow_limiter
None, // v1_sink_router
8, // capture_v1_scatter_gather_min_batch
None, // ai_gateway_signing_secret
+ AiRouting::Primary, // ai_routing
+ false, // ai_events_overflow_enabled
None, // ingestion_warning_emitter
);
@@ -2573,10 +2579,13 @@ fn setup_ai_test_router_with_token_dropper(token_dropper: TokenDropper) -> (Rout
10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytes
None, // overflow_limiter
+ None, // ai_events_overflow_limiter
None, // replay_overflow_limiter
None, // v1_sink_router
8, // capture_v1_scatter_gather_min_batch
None, // ai_gateway_signing_secret
+ AiRouting::Primary, // ai_routing
+ false, // ai_events_overflow_enabled
None, // ingestion_warning_emitter
);
@@ -2784,10 +2793,13 @@ fn setup_ai_test_router_with_llm_quota_limited(token: &str) -> (Router, Capturin
10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytes
None, // overflow_limiter
+ None, // ai_events_overflow_limiter
None, // replay_overflow_limiter
None, // v1_sink_router
8, // capture_v1_scatter_gather_min_batch
None, // ai_gateway_signing_secret
+ AiRouting::Primary, // ai_routing
+ false, // ai_events_overflow_enabled
None, // ingestion_warning_emitter
);
@@ -2937,14 +2949,17 @@ fn setup_ai_test_router_with_overflow_limiter(
Some(create_mock_blob_storage()),
None,
256,
- 10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
- 50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytes
- Some(overflow_limiter), // overflow_limiter
- None, // replay_overflow_limiter
- None, // v1_sink_router
- 8, // capture_v1_scatter_gather_min_batch
- None, // ai_gateway_signing_secret
- None, // ingestion_warning_emitter
+ 10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
+ 50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytes
+ Some(overflow_limiter),
+ None, // ai_events_overflow_limiter
+ None, // replay_overflow_limiter
+ None, // v1_sink_router
+ 8, // capture_v1_scatter_gather_min_batch
+ None, // ai_gateway_signing_secret
+ AiRouting::Primary, // ai_routing
+ false, // ai_events_overflow_enabled
+ None, // ingestion_warning_emitter
);
(router, sink_clone)
@@ -3080,11 +3095,14 @@ fn ai_router(
10 * 1024 * 1024,
50 * 1024 * 1024,
None,
+ None, // ai_events_overflow_limiter
None,
None,
8,
Some(GW_SECRET.to_string()),
- None,
+ AiRouting::Primary, // ai_routing
+ false, // ai_events_overflow_enabled
+ None, // ingestion_warning_emitter
);
(router, sink_clone)
}
diff --git a/rust/capture/tests/integration_ai_restrictions.rs b/rust/capture/tests/integration_ai_restrictions.rs
index 99bcad77a093..0cb576fde5e6 100644
--- a/rust/capture/tests/integration_ai_restrictions.rs
+++ b/rust/capture/tests/integration_ai_restrictions.rs
@@ -7,7 +7,7 @@ use axum::Router;
use axum_test_helper::TestClient;
use capture::ai_s3::{BlobStorage, MockBlobStorage};
use capture::api::CaptureError;
-use capture::config::CaptureMode;
+use capture::config::{AiRouting, CaptureMode};
use capture::event_restrictions::{
EventRestrictionService, Pipeline, Restriction, RestrictionManager, RestrictionScope,
RestrictionType,
@@ -16,7 +16,7 @@ use capture::quota_limiters::CaptureQuotaLimiter;
use capture::router::router;
use capture::sinks::Event;
use capture::time::TimeSource;
-use capture::v0_request::{DataType, ProcessedEvent};
+use capture::v0_request::{DataType, OverflowReason, ProcessedEvent};
use chrono::{DateTime, Utc};
use common_redis::MockRedisClient;
use futures::StreamExt;
@@ -187,15 +187,18 @@ async fn setup_ai_router_with_restriction(
26_214_400,
Some(create_mock_blob_storage()),
None,
- 256, // body_read_chunk_size_kb
- 10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
- 50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytes
- None, // overflow_limiter
- None, // replay_overflow_limiter
- None, // v1_sink_router
- 8, // capture_v1_scatter_gather_min_batch
- None, // ai_gateway_signing_secret
- None, // ingestion_warning_emitter
+ 256, // body_read_chunk_size_kb
+ 10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
+ 50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytes
+ None, // overflow_limiter
+ None, // ai_events_overflow_limiter
+ None, // replay_overflow_limiter
+ None, // v1_sink_router
+ 8, // capture_v1_scatter_gather_min_batch
+ None, // ai_gateway_signing_secret
+ AiRouting::Primary, // ai_routing
+ false, // ai_events_overflow_enabled
+ None, // ingestion_warning_emitter
);
(router, sink_clone)
@@ -507,15 +510,18 @@ async fn setup_ai_router_with_redirect_to_topic(
26_214_400,
Some(create_mock_blob_storage()),
None,
- 256, // body_read_chunk_size_kb
- 10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
- 50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytes
- None, // overflow_limiter
- None, // replay_overflow_limiter
- None, // v1_sink_router
- 8, // capture_v1_scatter_gather_min_batch
- None, // ai_gateway_signing_secret
- None, // ingestion_warning_emitter
+ 256, // body_read_chunk_size_kb
+ 10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
+ 50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytes
+ None, // overflow_limiter
+ None, // ai_events_overflow_limiter
+ None, // replay_overflow_limiter
+ None, // v1_sink_router
+ 8, // capture_v1_scatter_gather_min_batch
+ None, // ai_gateway_signing_secret
+ AiRouting::Primary, // ai_routing
+ false, // ai_events_overflow_enabled
+ None, // ingestion_warning_emitter
);
(router, sink_clone)
@@ -530,6 +536,8 @@ async fn setup_ai_router_with_redirect_to_topic(
async fn setup_ai_router_with_force_overflow_and_limiter(
token: &str,
overflow_limiter: Arc<OverflowLimiter>,
+ ai_routing: AiRouting,
+ ai_events_overflow_enabled: bool,
) -> (Router, CapturingSink) {
let (readiness, liveness, _monitor) = test_lifecycle_handlers();
@@ -588,11 +596,14 @@ async fn setup_ai_router_with_force_overflow_and_limiter(
10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytes
Some(overflow_limiter), // overflow_limiter
+ None, // ai_events_overflow_limiter
None, // replay_overflow_limiter
None, // v1_sink_router
8, // capture_v1_scatter_gather_min_batch
None, // ai_gateway_signing_secret
- None, // ingestion_warning_emitter
+ ai_routing,
+ ai_events_overflow_enabled,
+ None, // ingestion_warning_emitter
);
(router, sink_clone)
@@ -617,8 +628,13 @@ async fn test_ai_force_overflow_restriction_wins_over_overflow_limiter() {
true, // preserve_locality
));
- let (router, sink) =
- setup_ai_router_with_force_overflow_and_limiter(restricted_token, overflow_limiter).await;
+ let (router, sink) = setup_ai_router_with_force_overflow_and_limiter(
+ restricted_token,
+ overflow_limiter,
+ AiRouting::Primary,
+ false,
+ )
+ .await;
let test_client = TestClient::new(router);
let properties = json!({"$ai_model": "gpt-4"});
@@ -652,6 +668,56 @@ async fn test_ai_force_overflow_restriction_wins_over_overflow_limiter() {
);
}
+#[tokio::test]
+async fn test_ai_endpoint_ignores_analytics_ai_routing_config() {
+ // Deployment-config cross-contamination guard: the CAPTURE_ANALYTICS_AI_EVENTS_*
+ // family configures $ai_* routing on capture-analytics deployments. If it
+ // leaks onto a capture-ai deployment (whose main topic already IS the AI
+ // topic), the AI endpoint must behave exactly as without it: events stay
+ // on the AnalyticsMain lane and the OverflowLimiter applies by analytics
+ // rules. Catches a regression that types AI-endpoint events as
+ // DataType::AiEvents or gates their overflow on the analytics valve.
+ let token = "phc_ai_endpoint_routing_leak_token";
+ let distinct_id = "test_user";
+ let hot_key = format!("{token}:{distinct_id}");
+
+ let overflow_limiter = Arc::new(OverflowLimiter::new(
+ NonZeroU32::new(1_000).unwrap(),
+ NonZeroU32::new(1_000).unwrap(),
+ Some(hot_key),
+ false, // preserve_locality
+ ));
+
+ // Restriction is registered for a different token, so only the limiter acts.
+ let (router, sink) = setup_ai_router_with_force_overflow_and_limiter(
+ "phc_some_other_token",
+ overflow_limiter,
+ AiRouting::Secondary,
+ true,
+ )
+ .await;
+ let test_client = TestClient::new(router);
+
+ let properties = json!({"$ai_model": "gpt-4"});
+ let form = create_ai_event_form("$ai_generation", distinct_id, properties);
+
+ let response = send_multipart_request(&test_client, form, Some(token)).await;
+ assert_eq!(response.status(), StatusCode::OK);
+
+ let events = sink.get_events().await;
+ assert_eq!(events.len(), 1);
+ assert_eq!(
+ events[0].metadata.data_type,
+ DataType::AnalyticsMain,
+ "analytics-deployment routing config must not divert AI-endpoint events"
+ );
+ assert_eq!(
+ events[0].metadata.overflow_reason,
+ Some(OverflowReason::ForceLimited),
+ "the limiter must keep applying by AnalyticsMain rules, valve or not"
+ );
+}
+
#[tokio::test]
async fn test_ai_redirect_to_topic_restriction() {
let restricted_token = "phc_restricted_redirect_topic_token";
diff --git a/rust/capture/tests/integration_analytics_ai_routing.rs b/rust/capture/tests/integration_analytics_ai_routing.rs
new file mode 100644
index 000000000000..c0708510b080
--- /dev/null
+++ b/rust/capture/tests/integration_analytics_ai_routing.rs
@@ -0,0 +1,316 @@
+//! Endpoint-level coverage for `$ai_*` routing on analytics deployments:
+//! HTTP request -> router state -> `process_events` -> sink. The pipeline
+//! tests in `events::analytics` exercise `process_events` directly, so they
+//! cannot catch a regression in the router wiring (`ai_routing` /
+//! `ai_events_overflow_enabled` not reaching the pipeline) or in the
+//! endpoint-level batch handling of mixed `$ai_*` / non-AI payloads.
+
+#[path = "common/integration_utils.rs"]
+mod integration_utils;
+
+use async_trait::async_trait;
+use axum::http::StatusCode;
+use axum::Router;
+use axum_test_helper::TestClient;
+use capture::api::CaptureError;
+use capture::config::{AiRouting, CaptureMode};
+use capture::quota_limiters::CaptureQuotaLimiter;
+use capture::router::router;
+use capture::sinks::Event;
+use capture::time::TimeSource;
+use capture::v0_request::{DataType, OverflowReason, ProcessedEvent};
+use chrono::{DateTime, Utc};
+use common_redis::MockRedisClient;
+use integration_utils::{test_lifecycle_handlers, DEFAULT_CONFIG, DEFAULT_TEST_TIME};
+use limiters::overflow::OverflowLimiter;
+use limiters::token_dropper::TokenDropper;
+use rstest::rstest;
+use serde_json::json;
+use std::collections::HashSet;
+use std::num::NonZeroU32;
+use std::sync::Arc;
+use std::time::Duration;
+
+const TOKEN: &str = "phc_ai_routing_test_token";
+const DISTINCT_ID: &str = "test_user";
+
+struct FixedTime {
+ pub time: DateTime<Utc>,
+}
+
+impl TimeSource for FixedTime {
+ fn current_time(&self) -> DateTime<Utc> {
+ self.time
+ }
+}
+
+#[derive(Clone)]
+struct CapturingSink {
+ events: Arc<tokio::sync::Mutex<Vec<ProcessedEvent>>>,
+}
+
+impl CapturingSink {
+ fn new() -> Self {
+ Self {
+ events: Arc::new(tokio::sync::Mutex::new(Vec::new())),
+ }
+ }
+
+ async fn get_events(&self) -> Vec<ProcessedEvent> {
+ self.events.lock().await.clone()
+ }
+}
+
+#[async_trait]
+impl Event for CapturingSink {
+ async fn send(&self, event: ProcessedEvent) -> Result<(), CaptureError> {
+ self.events.lock().await.push(event);
+ Ok(())
+ }
+
+ async fn send_batch(&self, events: Vec<ProcessedEvent>) -> Result<(), CaptureError> {
+ self.events.lock().await.extend(events);
+ Ok(())
+ }
+}
+
+fn setup_analytics_router(
+ ai_routing: AiRouting,
+ ai_events_overflow_enabled: bool,
+ overflow_limiter: Option<Arc<OverflowLimiter>>,
+ ai_events_overflow_limiter: Option<Arc<OverflowLimiter>>,
+) -> (Router, CapturingSink) {
+ let (readiness, liveness, _monitor) = test_lifecycle_handlers();
+
+ let sink = CapturingSink::new();
+ let sink_clone = sink.clone();
+ let timesource = FixedTime {
+ time: DateTime::parse_from_rfc3339(DEFAULT_TEST_TIME)
+ .expect("Invalid fixed time format")
+ .with_timezone(&Utc),
+ };
+ let redis = Arc::new(MockRedisClient::new());
+
+ let mut cfg = DEFAULT_CONFIG.clone();
+ cfg.capture_mode = CaptureMode::Events;
+
+ let quota_limiter =
+ CaptureQuotaLimiter::new(&cfg, redis.clone(), Duration::from_secs(60 * 60 * 24 * 7));
+
+ let router = router(
+ timesource,
+ readiness,
+ liveness,
+ Arc::new(sink),
+ redis,
+ None, // global_rate_limiter_token_distinctid
+ quota_limiter,
+ TokenDropper::default(),
+ None, // event_restriction_service
+ false,
+ CaptureMode::Events,
+ String::from("capture-analytics"),
+ None,
+ 25 * 1024 * 1024,
+ false,
+ 1_i64,
+ false,
+ 0.0_f32,
+ 26_214_400,
+ None, // no blob storage for analytics
+ None,
+ 256, // body_read_chunk_size_kb
+ 10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
+ 50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytes
+ overflow_limiter,
+ ai_events_overflow_limiter,
+ None, // replay_overflow_limiter
+ None, // v1_sink_router
+ 8, // capture_v1_scatter_gather_min_batch
+ None, // ai_gateway_signing_secret
+ ai_routing,
+ ai_events_overflow_enabled,
+ None, // ingestion_warning_emitter
+ );
+
+ (router, sink_clone)
+}
+
+fn mixed_batch_payload() -> String {
+ json!({
+ "api_key": TOKEN,
+ "batch": [
+ {
+ "event": "$ai_generation",
+ "distinct_id": DISTINCT_ID,
+ "properties": {"$ai_model": "gpt-4"}
+ },
+ {
+ "event": "$pageview",
+ "distinct_id": DISTINCT_ID,
+ "properties": {}
+ }
+ ]
+ })
+ .to_string()
+}
+
+async fn post_batch(client: &TestClient, payload: String) {
+ let response = client
+ .post("/batch")
+ .header("Content-Type", "application/json")
+ .header("X-Forwarded-For", "127.0.0.1")
+ .body(payload)
+ .send()
+ .await;
+ assert_eq!(response.status(), StatusCode::OK);
+}
+
+fn allowlist(tokens: &[&str]) -> AiRouting {
+ AiRouting::SecondaryAllowlist(tokens.iter().map(|t| t.to_string()).collect::<HashSet<_>>())
+}
+
+/// A mixed batch must split lanes per the deployment's routing mode: only
+/// `$ai_*` events divert, only when the mode says so, and the `$pageview`
+/// stays on the analytics lane in every mode. The `primary` case runs with
+/// the overflow valve armed, pinning down that topic/valve config alone
+/// (mode left at `primary`) diverts nothing.
+#[rstest]
+#[case::secondary(AiRouting::Secondary, false, DataType::AiEvents)]
+#[case::allowlisted_token(allowlist(&[TOKEN]), false, DataType::AiEvents)]
+#[case::unlisted_token(allowlist(&["phc_other"]), false, DataType::AnalyticsMain)]
+#[case::primary_with_valve_armed(AiRouting::Primary, true, DataType::AnalyticsMain)]
+#[tokio::test]
+async fn mixed_batch_diverts_only_ai_events_per_routing_mode(
+ #[case] ai_routing: AiRouting,
+ #[case] ai_events_overflow_enabled: bool,
+ #[case] expected_ai_data_type: DataType,
+) {
+ let (router, sink) = setup_analytics_router(ai_routing, ai_events_overflow_enabled, None, None);
+ let client = TestClient::new(router);
+
+ post_batch(&client, mixed_batch_payload()).await;
+
+ let events = sink.get_events().await;
+ assert_eq!(events.len(), 2);
+
+ let ai_event = events
+ .iter()
+ .find(|e| e.metadata.event_name == "$ai_generation")
+ .expect("$ai_generation must reach the sink");
+ assert_eq!(ai_event.metadata.data_type, expected_ai_data_type);
+ assert_eq!(
+ ai_event.metadata.overflow_reason, None,
+ "no limiter is configured, so nothing may stamp overflow"
+ );
+
+ let pageview = events
+ .iter()
+ .find(|e| e.metadata.event_name == "$pageview")
+ .expect("$pageview must reach the sink");
+ assert_eq!(pageview.metadata.data_type, DataType::AnalyticsMain);
+}
+
+fn force_keyed_limiter() -> Arc<OverflowLimiter> {
+ let hot_key = format!("{TOKEN}:{DISTINCT_ID}");
+ Arc::new(OverflowLimiter::new(
+ NonZeroU32::new(1_000).unwrap(),
+ NonZeroU32::new(1_000).unwrap(),
+ Some(hot_key),
+ false, // preserve_locality
+ ))
+}
+
+/// With `secondary` routing, a force-limited key on the AI limiter
+/// overflow-stamps the diverted `$ai_*` event only when the AI overflow
+/// valve is armed (setup wires the AI limiter exactly then, so the test
+/// mirrors that coupling), while the `$pageview` on the same hot key
+/// (force-limited on the analytics limiter) stamps in both cases (the
+/// analytics lane is valve-independent). Catches the router failing to
+/// thread the AI limiter into the pipeline, which the process-level tests
+/// cannot see.
+#[rstest]
+#[case::valve_armed(true, Some(OverflowReason::ForceLimited))]
+#[case::valve_unarmed(false, None)]
+#[tokio::test]
+async fn ai_lane_overflow_stamping_gated_on_valve(
+ #[case] ai_events_overflow_enabled: bool,
+ #[case] expected_ai_reason: Option<OverflowReason>,
+) {
+ let (router, sink) = setup_analytics_router(
+ AiRouting::Secondary,
+ ai_events_overflow_enabled,
+ Some(force_keyed_limiter()),
+ ai_events_overflow_enabled.then(force_keyed_limiter),
+ );
+ let client = TestClient::new(router);
+
+ post_batch(&client, mixed_batch_payload()).await;
+
+ let events = sink.get_events().await;
+ assert_eq!(events.len(), 2);
+
+ let ai_event = events
+ .iter()
+ .find(|e| e.metadata.event_name == "$ai_generation")
+ .expect("$ai_generation must reach the sink");
+ assert_eq!(ai_event.metadata.data_type, DataType::AiEvents);
+ assert_eq!(ai_event.metadata.overflow_reason, expected_ai_reason);
+
+ let pageview = events
+ .iter()
+ .find(|e| e.metadata.event_name == "$pageview")
+ .expect("$pageview must reach the sink");
+ assert_eq!(pageview.metadata.data_type, DataType::AnalyticsMain);
+ assert_eq!(
+ pageview.metadata.overflow_reason,
+ Some(OverflowReason::ForceLimited),
+ "the analytics lane must keep overflowing regardless of the AI valve"
+ );
+}
+
+/// The two lanes consult separate limiter instances end-to-end: a key that
+/// the analytics limiter force-routes must not drag the same key's diverted
+/// `$ai_*` event into AI overflow (and the pageview must still stamp).
+/// Catches the router wiring one limiter instance into both slots.
+#[tokio::test]
+async fn ai_lane_overflow_isolated_from_analytics_limiter() {
+ let clean_ai_limiter = Arc::new(OverflowLimiter::new(
+ NonZeroU32::new(1_000).unwrap(),
+ NonZeroU32::new(1_000).unwrap(),
+ None,
+ false, // preserve_locality
+ ));
+
+ let (router, sink) = setup_analytics_router(
+ AiRouting::Secondary,
+ true, // valve armed
+ Some(force_keyed_limiter()),
+ Some(clean_ai_limiter),
+ );
+ let client = TestClient::new(router);
+
+ post_batch(&client, mixed_batch_payload()).await;
+
+ let events = sink.get_events().await;
+ assert_eq!(events.len(), 2);
+
+ let ai_event = events
+ .iter()
+ .find(|e| e.metadata.event_name == "$ai_generation")
+ .expect("$ai_generation must reach the sink");
+ assert_eq!(ai_event.metadata.data_type, DataType::AiEvents);
+ assert_eq!(
+ ai_event.metadata.overflow_reason, None,
+ "the analytics limiter's force-routed key must not stamp the AI lane"
+ );
+
+ let pageview = events
+ .iter()
+ .find(|e| e.metadata.event_name == "$pageview")
+ .expect("$pageview must reach the sink");
+ assert_eq!(
+ pageview.metadata.overflow_reason,
+ Some(OverflowReason::ForceLimited)
+ );
+}
diff --git a/rust/capture/tests/integration_analytics_restrictions.rs b/rust/capture/tests/integration_analytics_restrictions.rs
index 3b453a5d338a..255de067afe9 100644
--- a/rust/capture/tests/integration_analytics_restrictions.rs
+++ b/rust/capture/tests/integration_analytics_restrictions.rs
@@ -6,7 +6,7 @@ use axum::http::StatusCode;
use axum::Router;
use axum_test_helper::TestClient;
use capture::api::CaptureError;
-use capture::config::CaptureMode;
+use capture::config::{AiRouting, CaptureMode};
use capture::event_restrictions::{
EventRestrictionService, Pipeline, Restriction, RestrictionManager, RestrictionScope,
RestrictionType,
@@ -66,7 +66,10 @@ impl Event for CapturingSink {
async fn setup_analytics_router_with_restriction(
restriction_type: RestrictionType,
+ restriction_pipeline: Pipeline,
token: &str,
+ ai_routing: AiRouting,
+ ai_events_overflow_enabled: bool,
) -> (Router, CapturingSink) {
let (readiness, liveness, _monitor) = test_lifecycle_handlers();
@@ -85,11 +88,14 @@ async fn setup_analytics_router_with_restriction(
let quota_limiter =
CaptureQuotaLimiter::new(&cfg, redis.clone(), Duration::from_secs(60 * 60 * 24 * 7));
- let service = EventRestrictionService::new(vec![Pipeline::Analytics], Duration::from_secs(300));
+ let service = EventRestrictionService::new(
+ Pipeline::for_capture_mode(CaptureMode::Events),
+ Duration::from_secs(300),
+ );
let mut manager = RestrictionManager::new();
manager.insert_restrictions(
- Pipeline::Analytics,
+ restriction_pipeline,
token,
vec![Restriction {
restriction_type,
@@ -125,11 +131,14 @@ async fn setup_analytics_router_with_restriction(
10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytes
None, // overflow_limiter
+ None, // ai_events_overflow_limiter
None, // replay_overflow_limiter
None, // v1_sink_router
8, // capture_v1_scatter_gather_min_batch
None, // ai_gateway_signing_secret
- None, // ingestion_warning_emitter
+ ai_routing,
+ ai_events_overflow_enabled,
+ None, // ingestion_warning_emitter
);
(router, sink_clone)
@@ -208,8 +217,14 @@ fn assert_event(event: &ProcessedEvent, expected: &ExpectedEvent) {
#[tokio::test]
async fn test_analytics_drop_event_restriction() {
let restricted_token = "phc_restricted_drop_token";
- let (router, sink) =
- setup_analytics_router_with_restriction(RestrictionType::DropEvent, restricted_token).await;
+ let (router, sink) = setup_analytics_router_with_restriction(
+ RestrictionType::DropEvent,
+ Pipeline::Analytics,
+ restricted_token,
+ AiRouting::Primary,
+ false,
+ )
+ .await;
let test_client = TestClient::new(router);
let payload = json!({
@@ -239,9 +254,14 @@ async fn test_analytics_drop_event_restriction() {
#[tokio::test]
async fn test_analytics_redirect_to_dlq_restriction() {
let restricted_token = "phc_restricted_dlq_token";
- let (router, sink) =
- setup_analytics_router_with_restriction(RestrictionType::RedirectToDlq, restricted_token)
- .await;
+ let (router, sink) = setup_analytics_router_with_restriction(
+ RestrictionType::RedirectToDlq,
+ Pipeline::Analytics,
+ restricted_token,
+ AiRouting::Primary,
+ false,
+ )
+ .await;
let test_client = TestClient::new(router);
let payload = json!({
@@ -281,9 +301,14 @@ async fn test_analytics_redirect_to_dlq_restriction() {
#[tokio::test]
async fn test_analytics_force_overflow_restriction() {
let restricted_token = "phc_restricted_overflow_token";
- let (router, sink) =
- setup_analytics_router_with_restriction(RestrictionType::ForceOverflow, restricted_token)
- .await;
+ let (router, sink) = setup_analytics_router_with_restriction(
+ RestrictionType::ForceOverflow,
+ Pipeline::Analytics,
+ restricted_token,
+ AiRouting::Primary,
+ false,
+ )
+ .await;
let test_client = TestClient::new(router);
let payload = json!({
@@ -320,12 +345,76 @@ async fn test_analytics_force_overflow_restriction() {
);
}
+#[tokio::test]
+async fn test_analytics_force_overflow_restriction_applies_to_diverted_ai_event() {
+ // A $ai_* event diverted onto the AI lane is governed by ai-scoped
+ // restrictions — the same Pipeline::Ai slice the dedicated AI endpoints
+ // consult — so this test inserts its ForceOverflow under Pipeline::Ai.
+ //
+ // The restriction must follow the event onto the lane: with secondary
+ // routing and the overflow valve armed, the event keeps
+ // DataType::AiEvents and carries force_overflow (the sink maps that pair
+ // to the AI overflow topic, never the analytics one). Catches the
+ // restriction pipeline or the router dropping restrictions for diverted
+ // events, which the process-level tests can't see end-to-end.
+ let restricted_token = "phc_restricted_overflow_ai_token";
+ let (router, sink) = setup_analytics_router_with_restriction(
+ RestrictionType::ForceOverflow,
+ Pipeline::Ai,
+ restricted_token,
+ AiRouting::Secondary,
+ true,
+ )
+ .await;
+ let test_client = TestClient::new(router);
+
+ let payload = json!({
+ "token": restricted_token,
+ "event": "$ai_generation",
+ "distinct_id": "test_user"
+ });
+
+ let response = test_client
+ .post("/capture")
+ .header("Content-Type", "application/json")
+ .header("X-Forwarded-For", "127.0.0.1")
+ .body(payload.to_string())
+ .send()
+ .await;
+
+ assert_eq!(response.status(), StatusCode::OK);
+
+ let events = sink.get_events().await;
+ assert_eq!(events.len(), 1);
+ assert_event(
+ &events[0],
+ &ExpectedEvent {
+ token: restricted_token,
+ distinct_id: "test_user",
+ event_name: "$ai_generation",
+ data_type: DataType::AiEvents,
+ force_overflow: true,
+ skip_person_processing: false,
+ redirect_to_dlq: false,
+ redirect_to_topic: None,
+ expected_properties: None,
+ },
+ );
+ assert_eq!(
+ events[0].metadata.overflow_reason, None,
+ "force_overflow short-circuits stamping on the AI lane exactly like analytics"
+ );
+}
+
#[tokio::test]
async fn test_analytics_skip_person_processing_restriction() {
let restricted_token = "phc_restricted_skip_person_token";
let (router, sink) = setup_analytics_router_with_restriction(
RestrictionType::SkipPersonProcessing,
+ Pipeline::Analytics,
restricted_token,
+ AiRouting::Primary,
+ false,
)
.await;
let test_client = TestClient::new(router);
@@ -367,8 +456,14 @@ async fn test_analytics_skip_person_processing_restriction() {
#[tokio::test]
async fn test_analytics_restriction_does_not_apply_to_other_tokens() {
let restricted_token = "phc_restricted_token";
- let (router, sink) =
- setup_analytics_router_with_restriction(RestrictionType::DropEvent, restricted_token).await;
+ let (router, sink) = setup_analytics_router_with_restriction(
+ RestrictionType::DropEvent,
+ Pipeline::Analytics,
+ restricted_token,
+ AiRouting::Primary,
+ false,
+ )
+ .await;
let test_client = TestClient::new(router);
let payload = json!({
@@ -466,15 +561,18 @@ async fn setup_analytics_router_with_redirect_to_topic(
26_214_400,
None,
None,
- 256, // body_read_chunk_size_kb
- 10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
- 50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytes
- None, // overflow_limiter
- None, // replay_overflow_limiter
- None, // v1_sink_router
- 8, // capture_v1_scatter_gather_min_batch
- None, // ai_gateway_signing_secret
- None, // ingestion_warning_emitter
+ 256, // body_read_chunk_size_kb
+ 10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
+ 50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytes
+ None, // overflow_limiter
+ None, // ai_events_overflow_limiter
+ None, // replay_overflow_limiter
+ None, // v1_sink_router
+ 8, // capture_v1_scatter_gather_min_batch
+ None, // ai_gateway_signing_secret
+ AiRouting::Primary, // ai_routing
+ false, // ai_events_overflow_enabled
+ None, // ingestion_warning_emitter
);
(router, sink_clone)
diff --git a/rust/capture/tests/integration_otel_endpoint.rs b/rust/capture/tests/integration_otel_endpoint.rs
index fa75fa33f56b..b8231ca00098 100644
--- a/rust/capture/tests/integration_otel_endpoint.rs
+++ b/rust/capture/tests/integration_otel_endpoint.rs
@@ -5,7 +5,7 @@ use async_trait::async_trait;
use axum_test_helper::TestClient;
use capture::ai_s3::MockBlobStorage;
use capture::api::CaptureError;
-use capture::config::CaptureMode;
+use capture::config::{AiRouting, CaptureMode};
use capture::event_restrictions::{
EventRestrictionService, Pipeline, Restriction, RestrictionFilters, RestrictionManager,
RestrictionScope, RestrictionType,
@@ -183,10 +183,13 @@ fn make_test_client_with_options(sink: &CapturingSink, options: TestClientOption
10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytes
options.overflow_limiter, // overflow_limiter
+ None, // ai_events_overflow_limiter
None, // replay_overflow_limiter
None, // v1_sink_router
8, // capture_v1_scatter_gather_min_batch
None, // ai_gateway_signing_secret
+ AiRouting::Primary, // ai_routing
+ false, // ai_events_overflow_enabled
None, // ingestion_warning_emitter
);
diff --git a/rust/capture/tests/integration_replay_restrictions.rs b/rust/capture/tests/integration_replay_restrictions.rs
index ad6c56cbc56b..d32755e19ce5 100644
--- a/rust/capture/tests/integration_replay_restrictions.rs
+++ b/rust/capture/tests/integration_replay_restrictions.rs
@@ -6,7 +6,7 @@ use axum::http::StatusCode;
use axum::Router;
use axum_test_helper::TestClient;
use capture::api::CaptureError;
-use capture::config::CaptureMode;
+use capture::config::{AiRouting, CaptureMode};
use capture::event_restrictions::{
EventRestrictionService, Pipeline, Restriction, RestrictionManager, RestrictionScope,
RestrictionType,
@@ -123,15 +123,18 @@ async fn setup_recordings_router_with_restriction(
26_214_400,
None, // no blob storage for recordings
None,
- 256, // body_read_chunk_size_kb
- 10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
- 50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytes
- None, // overflow_limiter
- None, // replay_overflow_limiter
- None, // v1_sink_router
- 8, // capture_v1_scatter_gather_min_batch
- None, // ai_gateway_signing_secret
- None, // ingestion_warning_emitter
+ 256, // body_read_chunk_size_kb
+ 10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
+ 50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytes
+ None, // overflow_limiter
+ None, // ai_events_overflow_limiter
+ None, // replay_overflow_limiter
+ None, // v1_sink_router
+ 8, // capture_v1_scatter_gather_min_batch
+ None, // ai_gateway_signing_secret
+ AiRouting::Primary, // ai_routing
+ false, // ai_events_overflow_enabled
+ None, // ingestion_warning_emitter
);
(router, sink_clone)
@@ -494,15 +497,18 @@ async fn setup_recordings_router_with_redirect_to_topic(
26_214_400,
None, // no blob storage for recordings
None,
- 256, // body_read_chunk_size_kb
- 10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
- 50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytes
- None, // overflow_limiter
- None, // replay_overflow_limiter
- None, // v1_sink_router
- 8, // capture_v1_scatter_gather_min_batch
- None, // ai_gateway_signing_secret
- None, // ingestion_warning_emitter
+ 256, // body_read_chunk_size_kb
+ 10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
+ 50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytes
+ None, // overflow_limiter
+ None, // ai_events_overflow_limiter
+ None, // replay_overflow_limiter
+ None, // v1_sink_router
+ 8, // capture_v1_scatter_gather_min_batch
+ None, // ai_gateway_signing_secret
+ AiRouting::Primary, // ai_routing
+ false, // ai_events_overflow_enabled
+ None, // ingestion_warning_emitter
);
(router, sink_clone)
diff --git a/rust/capture/tests/quota_limiters.rs b/rust/capture/tests/quota_limiters.rs
index 2cae179075a7..9519d0b0e6d4 100644
--- a/rust/capture/tests/quota_limiters.rs
+++ b/rust/capture/tests/quota_limiters.rs
@@ -15,7 +15,7 @@ use limiters::token_dropper::TokenDropper;
use serde_json::Value;
use capture::api::CaptureError;
-use capture::config::CaptureMode;
+use capture::config::{AiRouting, CaptureMode};
use capture::quota_limiters::{
is_exception_event, is_llm_event, is_survey_event, CaptureQuotaLimiter, EventInfo,
};
@@ -136,24 +136,27 @@ async fn setup_router_with_limits(
false, // metrics
CaptureMode::Events,
String::from("capture"),
- None, // concurrency_limit
- 1024 * 1024, // event_payload_size_limit
- false, // enable_historical_rerouting
- 1, // historical_rerouting_threshold_days
- false, // is_mirror_deploy
- 0.0, // verbose_sample_percent
- 26_214_400, // ai_max_sum_of_parts_bytes (25MB)
- None, // ai_blob_storage
- None, // body_chunk_read_timeout_ms
- 256, // body_read_chunk_size_kb
- 10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
- 50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytes
- None, // overflow_limiter
- None, // replay_overflow_limiter
- None, // v1_sink_router
- 8, // capture_v1_scatter_gather_min_batch
- None, // ai_gateway_signing_secret
- None, // ingestion_warning_emitter
+ None, // concurrency_limit
+ 1024 * 1024, // event_payload_size_limit
+ false, // enable_historical_rerouting
+ 1, // historical_rerouting_threshold_days
+ false, // is_mirror_deploy
+ 0.0, // verbose_sample_percent
+ 26_214_400, // ai_max_sum_of_parts_bytes (25MB)
+ None, // ai_blob_storage
+ None, // body_chunk_read_timeout_ms
+ 256, // body_read_chunk_size_kb
+ 10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
+ 50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytes
+ None, // overflow_limiter
+ None, // ai_events_overflow_limiter
+ None, // replay_overflow_limiter
+ None, // v1_sink_router
+ 8, // capture_v1_scatter_gather_min_batch
+ None, // ai_gateway_signing_secret
+ AiRouting::Primary, // ai_routing
+ false, // ai_events_overflow_enabled
+ None, // ingestion_warning_emitter
);
(app, sink)
@@ -1196,17 +1199,20 @@ async fn test_survey_quota_cross_batch_first_submission_allowed() {
false,
0.0,
26_214_400,
- None, // ai_blob_storage
- None, // body_chunk_read_timeout_ms
- 256, // body_read_chunk_size_kb
- 10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
- 50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytes
- None, // overflow_limiter
- None, // replay_overflow_limiter
- None, // v1_sink_router
- 8, // capture_v1_scatter_gather_min_batch
- None, // ai_gateway_signing_secret
- None, // ingestion_warning_emitter
+ None, // ai_blob_storage
+ None, // body_chunk_read_timeout_ms
+ 256, // body_read_chunk_size_kb
+ 10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
+ 50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytes
+ None, // overflow_limiter
+ None, // ai_events_overflow_limiter
+ None, // replay_overflow_limiter
+ None, // v1_sink_router
+ 8, // capture_v1_scatter_gather_min_batch
+ None, // ai_gateway_signing_secret
+ AiRouting::Primary, // ai_routing
+ false, // ai_events_overflow_enabled
+ None, // ingestion_warning_emitter
);
let client = TestClient::new(app);
@@ -1287,17 +1293,20 @@ async fn test_survey_quota_cross_batch_duplicate_submission_dropped() {
false,
0.0,
26_214_400,
- None, // ai_blob_storage
- None, // body_chunk_read_timeout_ms
- 256, // body_read_chunk_size_kb
- 10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
- 50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytes
- None, // overflow_limiter
- None, // replay_overflow_limiter
- None, // v1_sink_router
- 8, // capture_v1_scatter_gather_min_batch
- None, // ai_gateway_signing_secret
- None, // ingestion_warning_emitter
+ None, // ai_blob_storage
+ None, // body_chunk_read_timeout_ms
+ 256, // body_read_chunk_size_kb
+ 10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
+ 50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytes
+ None, // overflow_limiter
+ None, // ai_events_overflow_limiter
+ None, // replay_overflow_limiter
+ None, // v1_sink_router
+ 8, // capture_v1_scatter_gather_min_batch
+ None, // ai_gateway_signing_secret
+ AiRouting::Primary, // ai_routing
+ false, // ai_events_overflow_enabled
+ None, // ingestion_warning_emitter
);
let client = TestClient::new(app);
@@ -1382,17 +1391,20 @@ async fn test_survey_quota_cross_batch_redis_error_fail_open() {
false,
0.0,
26_214_400,
- None, // ai_blob_storage
- None, // body_chunk_read_timeout_ms
- 256, // body_read_chunk_size_kb
- 10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
- 50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytes
- None, // overflow_limiter
- None, // replay_overflow_limiter
- None, // v1_sink_router
- 8, // capture_v1_scatter_gather_min_batch
- None, // ai_gateway_signing_secret
- None, // ingestion_warning_emitter
+ None, // ai_blob_storage
+ None, // body_chunk_read_timeout_ms
+ 256, // body_read_chunk_size_kb
+ 10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
+ 50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytes
+ None, // overflow_limiter
+ None, // ai_events_overflow_limiter
+ None, // replay_overflow_limiter
+ None, // v1_sink_router
+ 8, // capture_v1_scatter_gather_min_batch
+ None, // ai_gateway_signing_secret
+ AiRouting::Primary, // ai_routing
+ false, // ai_events_overflow_enabled
+ None, // ingestion_warning_emitter
);
let client = TestClient::new(app);
@@ -1814,17 +1826,20 @@ async fn test_ai_quota_cross_batch_redis_error_fail_open() {
false,
0.0,
26_214_400,
- None, // ai_blob_storage
- None, // body_chunk_read_timeout_ms
- 256, // body_read_chunk_size_kb
- 10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
- 50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytes
- None, // overflow_limiter
- None, // replay_overflow_limiter
- None, // v1_sink_router
- 8, // capture_v1_scatter_gather_min_batch
- None, // ai_gateway_signing_secret
- None, // ingestion_warning_emitter
+ None, // ai_blob_storage
+ None, // body_chunk_read_timeout_ms
+ 256, // body_read_chunk_size_kb
+ 10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
+ 50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytes
+ None, // overflow_limiter
+ None, // ai_events_overflow_limiter
+ None, // replay_overflow_limiter
+ None, // v1_sink_router
+ 8, // capture_v1_scatter_gather_min_batch
+ None, // ai_gateway_signing_secret
+ AiRouting::Primary, // ai_routing
+ false, // ai_events_overflow_enabled
+ None, // ingestion_warning_emitter
);
let client = TestClient::new(app);
diff --git a/rust/common/limiters/src/overflow.rs b/rust/common/limiters/src/overflow.rs
index 7861f40a35d9..2e8c9679378c 100644
--- a/rust/common/limiters/src/overflow.rs
+++ b/rust/common/limiters/src/overflow.rs
@@ -95,12 +95,14 @@ impl OverflowLimiter {
}
/// Reports the number of tracked keys to prometheus every 10 seconds,
- /// needs to be spawned in a separate task.
- pub async fn report_metrics(&self) {
+ /// needs to be spawned in a separate task. `lane` labels the series so
+ /// deployments running several limiter instances (e.g. capture's
+ /// analytics and AI lanes) don't overwrite each other's gauge.
+ pub async fn report_metrics(&self, lane: &'static str) {
let mut interval = tokio::time::interval(tokio::time::Duration::from_secs(10));
loop {
interval.tick().await;
- gauge!("partition_limits_key_count").set(self.limiter.len() as f64);
+ gauge!("partition_limits_key_count", "lane" => lane).set(self.limiter.len() as f64);
}
}