:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(capture): apply event restrictions to errortracking pipeline (#58006)
Paweł Ledwoń46a162073390
diff --git a/rust/capture/src/ai_endpoint.rs b/rust/capture/src/ai_endpoint.rsindex 77f0ed6cf4bd..8e5f8ddd2663 100644--- a/rust/capture/src/ai_endpoint.rs+++ b/rust/capture/src/ai_endpoint.rs@@ -23,7 +23,9 @@ const AI_BLOB_TOTAL_BYTES_PER_EVENT: &str = "capture_ai_blob_total_bytes_per_eveconst AI_BLOB_EVENTS_TOTAL: &str = "capture_ai_blob_events_total";use crate::api::{CaptureError, CaptureResponse, CaptureResponseCode};-use crate::event_restrictions::{AppliedRestrictions, EventContext as RestrictionEventContext};+use crate::event_restrictions::{+ AppliedRestrictions, EventContext as RestrictionEventContext, Pipeline,+};use crate::events::overflow_stamping::stamp_overflow_reason;use crate::extractors::extract_body_with_timeout;use crate::payload::decompression::decompress_gzip_to_bytes;@@ -217,7 +219,9 @@ pub async fn ai_handler(now_ts: state.timesource.current_time().timestamp(),};- let applied = service.get_restrictions(token, &event_ctx).await;+ let applied = service+ .get_restrictions(token, &event_ctx, Pipeline::Ai)+ .await;if applied.should_drop() {report_dropped_events("event_restriction_drop", 1);diff --git a/rust/capture/src/config.rs b/rust/capture/src/config.rsindex 80243d725fba..7225322a540f 100644--- a/rust/capture/src/config.rs+++ b/rust/capture/src/config.rs@@ -19,25 +19,6 @@ impl CaptureMode {CaptureMode::Ai => "ai",}}-- /// Returns the pipeline name used in Redis restriction configs.- /// These must match the values in Django's EventIngestionRestrictionConfig.pipelines.- pub fn as_pipeline_name(&self) -> &'static str {- match self {- CaptureMode::Events => "analytics",- CaptureMode::Recordings => "session_recordings",- CaptureMode::Ai => "ai",- }- }-- pub fn parse_pipeline_name(s: &str) -> Option<Self> {- match s {- "analytics" => Some(Self::Events),- "session_recordings" => Some(Self::Recordings),- "ai" => Some(Self::Ai),- _ => None,- }- }}impl std::str::FromStr for CaptureMode {diff --git a/rust/capture/src/event_restrictions/manager.rs b/rust/capture/src/event_restrictions/manager.rsindex 412b9d585af0..d25743b863ba 100644--- a/rust/capture/src/event_restrictions/manager.rs+++ b/rust/capture/src/event_restrictions/manager.rs@@ -10,17 +10,20 @@ use tokio::sync::RwLock;use tokio::time::interval;use tracing::{error, info, warn};-use crate::config::CaptureMode;-use super::repository::EventRestrictionsRepository;use super::types::{- AppliedRestrictions, EventContext, Restriction, RestrictionSet, RestrictionType,+ AppliedRestrictions, EventContext, Pipeline, Restriction, RestrictionSet, RestrictionType,};-/// Manages restrictions by token.+/// Manages restrictions by pipeline and token.+///+/// A single `RestrictionManager` can serve multiple pipelines (e.g. the events+/// capture deployment serves both `Analytics` and `ErrorTracking`). An entry+/// that applies to multiple pipelines is indexed under each — lookup is+/// pipeline-then-token, not token-then-pipeline.#[derive(Debug, Clone, Default)]pub struct RestrictionManager {- pub restrictions: HashMap<String, Vec<Restriction>>,+ pub restrictions: HashMap<Pipeline, HashMap<String, Vec<Restriction>>>,}impl RestrictionManager {@@ -28,9 +31,18 @@ impl RestrictionManager {Self::default()}- /// Get all restriction types that apply to an event.- pub fn get_restrictions(&self, token: &str, event: &EventContext) -> RestrictionSet {- let Some(restrictions) = self.restrictions.get(token) else {+ /// Get all restriction types that apply to an event for a given pipeline.+ pub fn get_restrictions(+ &self,+ token: &str,+ event: &EventContext,+ pipeline: Pipeline,+ ) -> RestrictionSet {+ let Some(restrictions) = self+ .restrictions+ .get(&pipeline)+ .and_then(|by_token| by_token.get(token))+ else {return RestrictionSet::new();};@@ -57,18 +69,36 @@ impl RestrictionManager {result}- /// Build a RestrictionManager from repository data for a specific pipeline.+ /// Test/setup helper: insert restrictions for a single (pipeline, token) pair.+ pub fn insert_restrictions(+ &mut self,+ pipeline: Pipeline,+ token: impl Into<String>,+ restrictions: Vec<Restriction>,+ ) {+ self.restrictions+ .entry(pipeline)+ .or_default()+ .insert(token.into(), restrictions);+ }++ /// Build a RestrictionManager from repository data for the given allowlist+ /// of pipelines. Entries that don't apply to any allowed pipeline are+ /// dropped at fetch time; entries applying to multiple allowed pipelines+ /// are indexed under each.////// Returns an error if any restriction type fails to fetch, which signals/// a likely dead Redis connection and triggers a reconnect.pub async fn from_repository(repository: &dyn EventRestrictionsRepository,- pipeline: CaptureMode,+ allowed_pipelines: &[Pipeline],) -> Result<Self, CustomRedisError> {- info!(pipeline = %pipeline.as_pipeline_name(), "Fetching event restrictions");+ info!(+ pipelines = ?allowed_pipelines,+ "Fetching event restrictions"+ );let mut manager = Self::new();- let pipeline_str = pipeline.as_pipeline_name();// Fetch all restriction types in parallellet fetch_futures = RestrictionType::all()@@ -98,13 +128,19 @@ impl RestrictionManager {entries.sort_by_key(|e| e.index.unwrap_or(0));for entry in entries {- // Skip if this entry doesn't apply to our pipeline- if !entry.pipelines.contains(&pipeline_str.to_string()) {+ // Skip old format entries (version must be 2)+ if entry.version != Some(2) {continue;}- // Skip old format entries (version must be 2)- if entry.version != Some(2) {+ // Resolve which allowed pipelines this entry applies to.+ let entry_pipelines: Vec<Pipeline> = entry+ .pipelines+ .iter()+ .filter_map(|s| Pipeline::parse(s))+ .filter(|p| allowed_pipelines.contains(p))+ .collect();+ if entry_pipelines.is_empty() {continue;}@@ -128,11 +164,15 @@ impl RestrictionManager {let token = entry.token.clone();let restriction = entry.into_restriction(restriction_type);- manager- .restrictions- .entry(token)- .or_default()- .push(restriction);+ for pipeline in entry_pipelines {+ manager+ .restrictions+ .entry(pipeline)+ .or_default()+ .entry(token.clone())+ .or_default()+ .push(restriction.clone());+ }}}@@ -140,37 +180,46 @@ impl RestrictionManager {return Err(e);}- let total_restrictions: usize = manager.restrictions.values().map(|v| v.len()).sum();- let total_tokens = manager.restrictions.len();-- info!(- pipeline = %pipeline_str,- total_restrictions = total_restrictions,- total_tokens = total_tokens,- "Fetched event restrictions"- );+ for pipeline in allowed_pipelines {+ let by_token = manager.restrictions.get(pipeline);+ let restriction_count: usize = by_token+ .map(|m| m.values().map(|v| v.len()).sum())+ .unwrap_or(0);+ let token_count: usize = by_token.map(|m| m.len()).unwrap_or(0);+ info!(+ pipeline = %pipeline.as_str(),+ total_restrictions = restriction_count,+ total_tokens = token_count,+ "Fetched event restrictions"+ );+ }Ok(manager)}}/// Service that manages event restrictions with background refresh and fail-open behavior.+///+/// One service serves all pipelines its host capture deployment produces to —+/// the events deployment uses `[Analytics, ErrorTracking]`, replay uses+/// `[SessionRecordings]`, ai uses `[Ai]`. Callers select the right pipeline+/// per event when calling [`Self::get_restrictions`].#[derive(Clone)]pub struct EventRestrictionService {manager: Arc<RwLock<RestrictionManager>>,last_successful_refresh: Arc<AtomicI64>,fail_open_after: Duration,- pipeline: CaptureMode,+ pipelines: Vec<Pipeline>,}impl EventRestrictionService {/// Create a new service. Call `start_refresh_task` to begin background updates.- pub fn new(pipeline: CaptureMode, fail_open_after: Duration) -> Self {+ pub fn new(pipelines: Vec<Pipeline>, fail_open_after: Duration) -> Self {Self {manager: Arc::new(RwLock::new(RestrictionManager::new())),last_successful_refresh: Arc::new(AtomicI64::new(0)),fail_open_after,- pipeline,+ pipelines,}}@@ -191,26 +240,25 @@ impl EventRestrictionService {Output = Result<Arc<dyn EventRestrictionsRepository>, common_redis::CustomRedisError>,>,{- let pipeline_str = self.pipeline.as_pipeline_name();let mut interval = interval(refresh_interval);let mut repository: Option<Arc<dyn EventRestrictionsRepository>> = None;loop {tokio::select! {_ = shutdown_handle.shutdown_recv() => {- info!(pipeline = %pipeline_str, "Event restrictions refresh task shutting down");+ info!(pipelines = ?self.pipelines, "Event restrictions refresh task shutting down");break;}_ = interval.tick() => {if repository.is_none() {match create_repository().await {Ok(repo) => {- info!(pipeline = %pipeline_str, "Event restrictions connected to Redis");+ info!(pipelines = ?self.pipelines, "Event restrictions connected to Redis");repository = Some(repo);}Err(e) => {error!(- pipeline = %pipeline_str,+ pipelines = ?self.pipelines,error = %e,"Failed to connect to event restrictions Redis, will retry");@@ -231,45 +279,57 @@ impl EventRestrictionService {/// Fetch restrictions from repository and update the local cache./// Returns `true` on success, `false` if all fetches failed (dead connection).async fn refresh_from_repository(&self, repository: &dyn EventRestrictionsRepository) -> bool {- let pipeline_str = self.pipeline.as_pipeline_name();-- match RestrictionManager::from_repository(repository, self.pipeline).await {+ match RestrictionManager::from_repository(repository, &self.pipelines).await {Ok(new_manager) => {- let total_restrictions: usize =- new_manager.restrictions.values().map(|v| v.len()).sum();- let total_tokens = new_manager.restrictions.len();+ // Count per-pipeline before handing the manager off to update().+ let counts: Vec<(Pipeline, usize, usize)> = self+ .pipelines+ .iter()+ .map(|pipeline| {+ let by_token = new_manager.restrictions.get(pipeline);+ let restriction_count: usize = by_token+ .map(|m| m.values().map(|v| v.len()).sum())+ .unwrap_or(0);+ let token_count: usize = by_token.map(|m| m.len()).unwrap_or(0);+ (*pipeline, restriction_count, token_count)+ })+ .collect();let now = self.update(new_manager).await;- gauge!(- "capture_event_restrictions_last_refresh_timestamp",- "pipeline" => pipeline_str.to_string()- )- .set(now as f64);-- gauge!(- "capture_event_restrictions_loaded_count",- "pipeline" => pipeline_str.to_string()- )- .set(total_restrictions as f64);-- gauge!(- "capture_event_restrictions_tokens_count",- "pipeline" => pipeline_str.to_string()- )- .set(total_tokens as f64);-- gauge!(- "capture_event_restrictions_stale",- "pipeline" => pipeline_str.to_string()- )- .set(0.0);+ for (pipeline, restriction_count, token_count) in counts {+ let pipeline_str = pipeline.as_str();++ gauge!(+ "capture_event_restrictions_last_refresh_timestamp",+ "pipeline" => pipeline_str.to_string()+ )+ .set(now as f64);++ gauge!(+ "capture_event_restrictions_loaded_count",+ "pipeline" => pipeline_str.to_string()+ )+ .set(restriction_count as f64);++ gauge!(+ "capture_event_restrictions_tokens_count",+ "pipeline" => pipeline_str.to_string()+ )+ .set(token_count as f64);++ gauge!(+ "capture_event_restrictions_stale",+ "pipeline" => pipeline_str.to_string()+ )+ .set(0.0);+ }true}Err(e) => {error!(- pipeline = %pipeline_str,+ pipelines = ?self.pipelines,error = %e,"Failed to refresh event restrictions, will reconnect");@@ -299,24 +359,27 @@ impl EventRestrictionService {Duration::from_secs(age_secs) > self.fail_open_after}- /// Get applied restrictions for an event. Returns empty if fail-open is active.+ /// Get applied restrictions for an event under the given pipeline. Returns+ /// empty if fail-open is active or if the pipeline isn't in the service's+ /// allowlist (no entries are indexed for it).pub async fn get_restrictions(&self,token: &str,event: &EventContext<'_>,+ pipeline: Pipeline,) -> AppliedRestrictions {if self.is_stale_at(event.now_ts) {gauge!("capture_event_restrictions_stale",- "pipeline" => self.pipeline.as_pipeline_name().to_string()+ "pipeline" => pipeline.as_str().to_string()).set(1.0);return AppliedRestrictions::default();}let guard = self.manager.read().await;- let set = guard.get_restrictions(token, event);- AppliedRestrictions::from_restrictions(set, self.pipeline)+ let set = guard.get_restrictions(token, event, pipeline);+ AppliedRestrictions::from_restrictions(set, pipeline)}}@@ -400,31 +463,32 @@ mod tests {).await;- let manager = RestrictionManager::from_repository(&repo, CaptureMode::Events)+ let manager = RestrictionManager::from_repository(&repo, &[Pipeline::Analytics]).await.unwrap();let event = EventContext::default();// Each token should have exactly its restriction type- let drop_restrictions = manager.get_restrictions("token_drop", &event);+ let drop_restrictions = manager.get_restrictions("token_drop", &event, Pipeline::Analytics);assert_eq!(drop_restrictions.len(), 1);assert!(drop_restrictions.contains(RestrictionType::DropEvent));- let overflow_restrictions = manager.get_restrictions("token_overflow", &event);+ let overflow_restrictions =+ manager.get_restrictions("token_overflow", &event, Pipeline::Analytics);assert_eq!(overflow_restrictions.len(), 1);assert!(overflow_restrictions.contains(RestrictionType::ForceOverflow));- let dlq_restrictions = manager.get_restrictions("token_dlq", &event);+ let dlq_restrictions = manager.get_restrictions("token_dlq", &event, Pipeline::Analytics);assert_eq!(dlq_restrictions.len(), 1);assert!(dlq_restrictions.contains(RestrictionType::RedirectToDlq));- let skip_restrictions = manager.get_restrictions("token_skip", &event);+ let skip_restrictions = manager.get_restrictions("token_skip", &event, Pipeline::Analytics);assert_eq!(skip_restrictions.len(), 1);assert!(skip_restrictions.contains(RestrictionType::SkipPersonProcessing));// Unknown token should have no restrictions- let unknown = manager.get_restrictions("unknown_token", &event);+ let unknown = manager.get_restrictions("unknown_token", &event, Pipeline::Analytics);assert!(unknown.is_empty());}@@ -443,7 +507,7 @@ mod tests {).await;- let manager = RestrictionManager::from_repository(&repo, CaptureMode::Events)+ let manager = RestrictionManager::from_repository(&repo, &[Pipeline::Analytics]).await.unwrap();@@ -453,7 +517,7 @@ mod tests {event_name: Some("$pageview"),..Default::default()};- let restrictions = manager.get_restrictions("token1", &event_match);+ let restrictions = manager.get_restrictions("token1", &event_match, Pipeline::Analytics);assert!(restrictions.contains(RestrictionType::DropEvent));// Should NOT match when event_name doesn't match (AND logic)@@ -462,7 +526,8 @@ mod tests {event_name: Some("$identify"),..Default::default()};- let restrictions = manager.get_restrictions("token1", &event_wrong_name);+ let restrictions =+ manager.get_restrictions("token1", &event_wrong_name, Pipeline::Analytics);assert!(restrictions.is_empty());// Should NOT match when distinct_id doesn't match@@ -471,7 +536,8 @@ mod tests {event_name: Some("$pageview"),..Default::default()};- let restrictions = manager.get_restrictions("token1", &event_wrong_user);+ let restrictions =+ manager.get_restrictions("token1", &event_wrong_user, Pipeline::Analytics);assert!(restrictions.is_empty());}@@ -490,7 +556,7 @@ mod tests {.await;// Fetch for analytics pipeline- let manager = RestrictionManager::from_repository(&repo, CaptureMode::Events)+ let manager = RestrictionManager::from_repository(&repo, &[Pipeline::Analytics]).await.unwrap();@@ -498,16 +564,20 @@ mod tests {// analytics token should be presentassert!(!manager- .get_restrictions("token_analytics", &event)+ .get_restrictions("token_analytics", &event, Pipeline::Analytics).is_empty());- // recordings token should NOT be present+ // recordings token should NOT be present (entry not indexed under+ // Analytics, even though it exists under SessionRecordings — and+ // SessionRecordings isn't in the allowlist).assert!(manager- .get_restrictions("token_recordings", &event)+ .get_restrictions("token_recordings", &event, Pipeline::Analytics).is_empty());// both token should be present- assert!(!manager.get_restrictions("token_both", &event).is_empty());+ assert!(!manager+ .get_restrictions("token_both", &event, Pipeline::Analytics)+ .is_empty());}#[tokio::test]@@ -522,17 +592,21 @@ mod tests {repo.set_entries(RestrictionType::DropEvent, Some(vec![old_entry, new_entry])).await;- let manager = RestrictionManager::from_repository(&repo, CaptureMode::Events)+ let manager = RestrictionManager::from_repository(&repo, &[Pipeline::Analytics]).await.unwrap();let event = EventContext::default();// Old version should be skipped- assert!(manager.get_restrictions("token_old", &event).is_empty());+ assert!(manager+ .get_restrictions("token_old", &event, Pipeline::Analytics)+ .is_empty());// New version should be present- assert!(!manager.get_restrictions("token_new", &event).is_empty());+ assert!(!manager+ .get_restrictions("token_new", &event, Pipeline::Analytics)+ .is_empty());}#[tokio::test]@@ -547,7 +621,7 @@ mod tests {).await;- let result = RestrictionManager::from_repository(&repo, CaptureMode::Events).await;+ let result = RestrictionManager::from_repository(&repo, &[Pipeline::Analytics]).await;assert!(result.is_err());}@@ -556,7 +630,7 @@ mod tests {let repo = MockRestrictionsRepository::new();// Don't set any entries- let manager = RestrictionManager::from_repository(&repo, CaptureMode::Events)+ let manager = RestrictionManager::from_repository(&repo, &[Pipeline::Analytics]).await.unwrap();@@ -579,11 +653,12 @@ mod tests {).await;- let manager = RestrictionManager::from_repository(&repo, CaptureMode::Events)+ let manager = RestrictionManager::from_repository(&repo, &[Pipeline::Analytics]).await.unwrap();- let restrictions = manager.get_restrictions("token1", &EventContext::default());+ let restrictions =+ manager.get_restrictions("token1", &EventContext::default(), Pipeline::Analytics);assert_eq!(restrictions.len(), 2);assert!(restrictions.contains(RestrictionType::ForceOverflow));assert!(restrictions.contains(RestrictionType::SkipPersonProcessing));@@ -602,19 +677,24 @@ mod tests {#[tokio::test]async fn test_service_is_stale_when_never_refreshed() {- let service = EventRestrictionService::new(CaptureMode::Events, Duration::from_secs(300));+ let service =+ EventRestrictionService::new(vec![Pipeline::Analytics], Duration::from_secs(300));// last_successful_refresh is 0, so should be stale (fail-open)- let applied = service.get_restrictions("token", &event_ctx_now()).await;+ let applied = service+ .get_restrictions("token", &event_ctx_now(), Pipeline::Analytics)+ .await;assert!(applied.is_empty());}#[tokio::test]async fn test_service_returns_restrictions_after_update() {- let service = EventRestrictionService::new(CaptureMode::Events, Duration::from_secs(300));+ let service =+ EventRestrictionService::new(vec![Pipeline::Analytics], Duration::from_secs(300));let mut manager = RestrictionManager::new();- manager.restrictions.insert(- "token1".to_string(),+ manager.insert_restrictions(+ Pipeline::Analytics,+ "token1",vec![Restriction {restriction_type: RestrictionType::DropEvent,scope: RestrictionScope::AllEvents,@@ -623,20 +703,23 @@ mod tests {);service.update(manager).await;- let applied = service.get_restrictions("token1", &event_ctx_now()).await;+ let applied = service+ .get_restrictions("token1", &event_ctx_now(), Pipeline::Analytics)+ .await;assert!(applied.should_drop());}#[tokio::test]async fn test_service_fail_open_after_timeout() {let service = EventRestrictionService::new(- CaptureMode::Events,+ vec![Pipeline::Analytics],Duration::from_secs(1), // 1 second timeout);let mut manager = RestrictionManager::new();- manager.restrictions.insert(- "token1".to_string(),+ manager.insert_restrictions(+ Pipeline::Analytics,+ "token1",vec![Restriction {restriction_type: RestrictionType::DropEvent,scope: RestrictionScope::AllEvents,@@ -646,7 +729,9 @@ mod tests {service.update(manager).await;// Immediately after update, should return restrictions- let applied = service.get_restrictions("token1", &event_ctx_now()).await;+ let applied = service+ .get_restrictions("token1", &event_ctx_now(), Pipeline::Analytics)+ .await;assert!(applied.should_drop());// Manually set last_successful_refresh to 10 seconds ago@@ -656,7 +741,9 @@ mod tests {.store(old_timestamp, Ordering::SeqCst);// Now should be stale (fail-open)- let applied_after = service.get_restrictions("token1", &event_ctx_now()).await;+ let applied_after = service+ .get_restrictions("token1", &event_ctx_now(), Pipeline::Analytics)+ .await;assert!(applied_after.is_empty());}@@ -669,7 +756,8 @@ mod tests {let (shutdown_token, lifecycle_handle) = test_lifecycle();let shutdown_token_clone = shutdown_token.clone();- let service = EventRestrictionService::new(CaptureMode::Events, Duration::from_secs(300));+ let service =+ EventRestrictionService::new(vec![Pipeline::Analytics], Duration::from_secs(300));let service_clone = service.clone();let handle = tokio::spawn(async move {@@ -697,16 +785,21 @@ mod tests {handle.await.unwrap();- let applied = service.get_restrictions("token1", &event_ctx_now()).await;+ let applied = service+ .get_restrictions("token1", &event_ctx_now(), Pipeline::Analytics)+ .await;assert!(applied.should_drop());- let unknown = service.get_restrictions("unknown", &event_ctx_now()).await;+ let unknown = service+ .get_restrictions("unknown", &event_ctx_now(), Pipeline::Analytics)+ .await;assert!(unknown.is_empty());}#[tokio::test]async fn test_refresh_task_retries_connection_while_fail_open() {- let service = EventRestrictionService::new(CaptureMode::Events, Duration::from_secs(300));+ let service =+ EventRestrictionService::new(vec![Pipeline::Analytics], Duration::from_secs(300));let (shutdown_token, lifecycle_handle) = test_lifecycle();let shutdown_token_clone = shutdown_token.clone();let attempt_count = Arc::new(std::sync::atomic::AtomicU32::new(0));@@ -734,7 +827,9 @@ mod tests {handle.await.unwrap();- let applied = service.get_restrictions("token", &event_ctx_now()).await;+ let applied = service+ .get_restrictions("token", &event_ctx_now(), Pipeline::Analytics)+ .await;assert!(applied.is_empty());assert!(attempt_count.load(Ordering::SeqCst) >= 2,@@ -749,7 +844,8 @@ mod tests {let connect_count = Arc::new(std::sync::atomic::AtomicU32::new(0));let count_clone = connect_count.clone();- let service = EventRestrictionService::new(CaptureMode::Events, Duration::from_secs(300));+ let service =+ EventRestrictionService::new(vec![Pipeline::Analytics], Duration::from_secs(300));let service_clone = service.clone();let handle = tokio::spawn(async move {@@ -785,7 +881,9 @@ mod tests {"should have reconnected after refresh failure");// Service never got a successful refresh, so it stays fail-open- let applied = service.get_restrictions("token", &event_ctx_now()).await;+ let applied = service+ .get_restrictions("token", &event_ctx_now(), Pipeline::Analytics)+ .await;assert!(applied.is_empty());}@@ -796,7 +894,8 @@ mod tests {let attempt_count = Arc::new(std::sync::atomic::AtomicU32::new(0));let count_clone = attempt_count.clone();- let service = EventRestrictionService::new(CaptureMode::Events, Duration::from_secs(300));+ let service =+ EventRestrictionService::new(vec![Pipeline::Analytics], Duration::from_secs(300));let service_clone = service.clone();let handle = tokio::spawn(async move {@@ -835,7 +934,9 @@ mod tests {"should have attempted at least 3 times");// After recovery, restrictions should be active- let applied = service.get_restrictions("token1", &event_ctx_now()).await;+ let applied = service+ .get_restrictions("token1", &event_ctx_now(), Pipeline::Analytics)+ .await;assert!(applied.force_overflow(),"restrictions should be active after recovery"diff --git a/rust/capture/src/event_restrictions/mod.rs b/rust/capture/src/event_restrictions/mod.rsindex d3a933eaabaa..6546653da54e 100644--- a/rust/capture/src/event_restrictions/mod.rs+++ b/rust/capture/src/event_restrictions/mod.rs@@ -6,7 +6,7 @@ mod types;pub use manager::{EventRestrictionService, RestrictionManager};pub use repository::{EventRestrictionsRepository, RedisRestrictionsRepository, RestrictionEntry};pub use types::{- AppliedRestrictions, EventContext, Restriction, RestrictionFilters, RestrictionScope,+ AppliedRestrictions, EventContext, Pipeline, Restriction, RestrictionFilters, RestrictionScope,RestrictionType,};diff --git a/rust/capture/src/event_restrictions/types.rs b/rust/capture/src/event_restrictions/types.rsindex 44e748814d50..eb4743eb74a7 100644--- a/rust/capture/src/event_restrictions/types.rs+++ b/rust/capture/src/event_restrictions/types.rs@@ -4,6 +4,58 @@ use metrics::counter;use crate::config::CaptureMode;+/// Logical ingestion pipeline a restriction is scoped to. Distinct from+/// [`CaptureMode`] — a single capture deployment (e.g. `CaptureMode::Events`)+/// produces events to multiple pipelines (`Analytics` for normal events,+/// `ErrorTracking` for `$exception` events). Each pipeline owns its own+/// restriction config in Redis and its own [`EventRestrictionService`].+///+/// String values must match Django's `EventIngestionRestrictionConfig.pipelines`+/// — the Redis JSON entries are filtered against [`Pipeline::as_str`].+#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)]+pub enum Pipeline {+ Analytics,+ SessionRecordings,+ Ai,+ ErrorTracking,+}++impl Pipeline {+ pub fn as_str(&self) -> &'static str {+ match self {+ Self::Analytics => "analytics",+ Self::SessionRecordings => "session_recordings",+ Self::Ai => "ai",+ Self::ErrorTracking => "errortracking",+ }+ }++ pub fn parse(s: &str) -> Option<Self> {+ match s {+ "analytics" => Some(Self::Analytics),+ "session_recordings" => Some(Self::SessionRecordings),+ "ai" => Some(Self::Ai),+ "errortracking" => Some(Self::ErrorTracking),+ _ => None,+ }+ }+}++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.+ /// 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::Recordings => vec![Self::SessionRecordings],+ CaptureMode::Ai => vec![Self::Ai],+ }+ }+}+/// Restriction types that can be applied to events in capture.#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]pub enum RestrictionType {@@ -129,9 +181,9 @@ pub struct AppliedRestrictions {impl AppliedRestrictions {/// Build from a RestrictionSet and emit per-type metrics.- pub(crate) fn from_restrictions(restrictions: RestrictionSet, pipeline: CaptureMode) -> Self {+ pub(crate) fn from_restrictions(restrictions: RestrictionSet, pipeline: Pipeline) -> Self {let mut result = Self::default();- let pipeline_str = pipeline.as_pipeline_name();+ let pipeline_str = pipeline.as_str();for restriction_type in RestrictionType::all() {if restrictions.contains(restriction_type) {@@ -299,20 +351,46 @@ mod tests {}#[test]- fn test_ingestion_pipeline_parse() {+ fn test_pipeline_parse() {+ assert_eq!(Pipeline::parse("analytics"), Some(Pipeline::Analytics));+ assert_eq!(+ Pipeline::parse("session_recordings"),+ Some(Pipeline::SessionRecordings)+ );+ assert_eq!(Pipeline::parse("ai"), Some(Pipeline::Ai));+ assert_eq!(+ Pipeline::parse("errortracking"),+ Some(Pipeline::ErrorTracking)+ );+ assert_eq!(Pipeline::parse("unknown"), None);+ }++ #[test]+ fn test_pipeline_as_str_roundtrip() {+ for pipeline in [+ Pipeline::Analytics,+ Pipeline::SessionRecordings,+ Pipeline::Ai,+ Pipeline::ErrorTracking,+ ] {+ assert_eq!(Pipeline::parse(pipeline.as_str()), Some(pipeline));+ }+ }++ #[test]+ fn test_pipeline_for_capture_mode() {assert_eq!(- CaptureMode::parse_pipeline_name("analytics"),- Some(CaptureMode::Events)+ Pipeline::for_capture_mode(CaptureMode::Events),+ vec![Pipeline::Analytics, Pipeline::ErrorTracking]);assert_eq!(- CaptureMode::parse_pipeline_name("session_recordings"),- Some(CaptureMode::Recordings)+ Pipeline::for_capture_mode(CaptureMode::Recordings),+ vec![Pipeline::SessionRecordings]);assert_eq!(- CaptureMode::parse_pipeline_name("ai"),- Some(CaptureMode::Ai)+ Pipeline::for_capture_mode(CaptureMode::Ai),+ vec![Pipeline::Ai]);- assert_eq!(CaptureMode::parse_pipeline_name("unknown"), None);}#[test]diff --git a/rust/capture/src/events/analytics.rs b/rust/capture/src/events/analytics.rsindex 3a3b519c65b6..4eceffa654e6 100644--- a/rust/capture/src/events/analytics.rs+++ b/rust/capture/src/events/analytics.rs@@ -41,13 +41,7 @@ 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 = match (event.event.as_str(), context.historical_migration) {- ("$$client_ingestion_warning", _) => DataType::ClientIngestionWarning,- ("$exception", _) => DataType::ExceptionErrorTracking,- ("$$heatmap", _) => DataType::HeatmapMain,- (_, true) => DataType::AnalyticsHistorical,- (_, false) => DataType::AnalyticsMain,- };+ let data_type = DataType::from_event_name(&event.event, context.historical_migration);// Redact the IP address of internally-generated events when tagged as suchlet resolved_ip = if event.properties.contains_key("capture_internal") {@@ -177,25 +171,23 @@ pub async fn process_events<'a>(debug_or_info!(chatty_debug_enabled, context=?context, event_count=?events.len(), "filtered by token_dropper");- // Apply event restrictions if service is configured.- //- // The service is scoped to the analytics pipeline (loaded for- // `CaptureMode::Events` → pipeline name `"analytics"`), so restrictions- // only apply to events routed to the analytics pipeline. Non-analytics- // data types (exceptions, heatmaps, client ingestion warnings) flow to- // separate topics and separate consumers that own their own restriction- // scope — applying analytics restrictions here would cross pipelines- // (e.g. a DropEvent restriction would silently drop exception events- // before they reach the error tracking topic).+ // Apply event restrictions, looking each event up under its `DataType`'s+ // pipeline. The single restriction service holds entries for all+ // pipelines its host capture deployment serves; the pipeline argument+ // selects which slice of restrictions applies to each event. A DropEvent+ // 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.if let Some(ref service) = restriction_service {let mut filtered_events = Vec::with_capacity(events.len());let now_ts = context.now.timestamp();for e in events {- if !e.metadata.data_type.is_analytics_pipeline() {+ let Some(pipeline) = e.metadata.data_type.pipeline() else {filtered_events.push(e);continue;- }+ };let uuid_str = e.event.uuid.to_string();let event_ctx = RestrictionEventContext {@@ -206,7 +198,9 @@ pub async fn process_events<'a>(now_ts,};- let applied = service.get_restrictions(&e.event.token, &event_ctx).await;+ let applied = service+ .get_restrictions(&e.event.token, &event_ctx, pipeline)+ .await;if applied.should_drop() {report_dropped_events("event_restriction_drop", 1);@@ -464,9 +458,8 @@ mod tests {}// Mock sink for testing process_events with restrictions- use crate::config::CaptureMode;use crate::event_restrictions::{- EventRestrictionService, Restriction, RestrictionFilters, RestrictionManager,+ EventRestrictionService, Pipeline, Restriction, RestrictionFilters, RestrictionManager,RestrictionScope, RestrictionType,};use crate::sinks::test_sink::MockSink;@@ -490,10 +483,12 @@ mod tests {let historical_cfg = router::HistoricalConfig::new(false, 1);// Create restriction service with DropEvent- let service = EventRestrictionService::new(CaptureMode::Events, Duration::from_secs(300));+ let service =+ EventRestrictionService::new(vec![Pipeline::Analytics], Duration::from_secs(300));let mut manager = RestrictionManager::new();- manager.restrictions.insert(- "test_token".to_string(),+ manager.insert_restrictions(+ Pipeline::Analytics,+ "test_token",vec![Restriction {restriction_type: RestrictionType::DropEvent,scope: RestrictionScope::AllEvents,@@ -536,10 +531,12 @@ mod tests {let historical_cfg = router::HistoricalConfig::new(false, 1);// Create restriction service with ForceOverflow- let service = EventRestrictionService::new(CaptureMode::Events, Duration::from_secs(300));+ let service =+ EventRestrictionService::new(vec![Pipeline::Analytics], Duration::from_secs(300));let mut manager = RestrictionManager::new();- manager.restrictions.insert(- "test_token".to_string(),+ manager.insert_restrictions(+ Pipeline::Analytics,+ "test_token",vec![Restriction {restriction_type: RestrictionType::ForceOverflow,scope: RestrictionScope::AllEvents,@@ -583,10 +580,12 @@ mod tests {let historical_cfg = router::HistoricalConfig::new(false, 1);// Create restriction service with SkipPersonProcessing- let service = EventRestrictionService::new(CaptureMode::Events, Duration::from_secs(300));+ let service =+ EventRestrictionService::new(vec![Pipeline::Analytics], Duration::from_secs(300));let mut manager = RestrictionManager::new();- manager.restrictions.insert(- "test_token".to_string(),+ manager.insert_restrictions(+ Pipeline::Analytics,+ "test_token",vec![Restriction {restriction_type: RestrictionType::SkipPersonProcessing,scope: RestrictionScope::AllEvents,@@ -630,10 +629,12 @@ mod tests {let historical_cfg = router::HistoricalConfig::new(false, 1);// Create restriction service with RedirectToDlq- let service = EventRestrictionService::new(CaptureMode::Events, Duration::from_secs(300));+ let service =+ EventRestrictionService::new(vec![Pipeline::Analytics], Duration::from_secs(300));let mut manager = RestrictionManager::new();- manager.restrictions.insert(- "test_token".to_string(),+ manager.insert_restrictions(+ Pipeline::Analytics,+ "test_token",vec![Restriction {restriction_type: RestrictionType::RedirectToDlq,scope: RestrictionScope::AllEvents,@@ -677,10 +678,12 @@ mod tests {let historical_cfg = router::HistoricalConfig::new(false, 1);// Create restriction service with multiple restrictions- let service = EventRestrictionService::new(CaptureMode::Events, Duration::from_secs(300));+ let service =+ EventRestrictionService::new(vec![Pipeline::Analytics], Duration::from_secs(300));let mut manager = RestrictionManager::new();- manager.restrictions.insert(- "test_token".to_string(),+ manager.insert_restrictions(+ Pipeline::Analytics,+ "test_token",vec![Restriction {restriction_type: RestrictionType::ForceOverflow,@@ -770,12 +773,14 @@ mod tests {let historical_cfg = router::HistoricalConfig::new(false, 1);// Create restriction that only applies to different event name- let service = EventRestrictionService::new(CaptureMode::Events, Duration::from_secs(300));+ let service =+ EventRestrictionService::new(vec![Pipeline::Analytics], Duration::from_secs(300));let mut manager = RestrictionManager::new();let mut filters = RestrictionFilters::default();filters.event_names.insert("$pageview".to_string()); // our event is "test_event"- manager.restrictions.insert(- "test_token".to_string(),+ manager.insert_restrictions(+ Pipeline::Analytics,+ "test_token",vec![Restriction {restriction_type: RestrictionType::DropEvent,scope: RestrictionScope::Filtered(filters),@@ -818,10 +823,12 @@ mod tests {let dropper = Arc::new(limiters::token_dropper::TokenDropper::default());let historical_cfg = router::HistoricalConfig::new(false, 1);- let service = EventRestrictionService::new(CaptureMode::Events, Duration::from_secs(300));+ let service =+ EventRestrictionService::new(vec![Pipeline::Analytics], Duration::from_secs(300));let mut manager = RestrictionManager::new();- manager.restrictions.insert(- "test_token".to_string(),+ manager.insert_restrictions(+ Pipeline::Analytics,+ "test_token",vec![Restriction {restriction_type: RestrictionType::RedirectToTopic,scope: RestrictionScope::AllEvents,@@ -874,10 +881,12 @@ mod tests {let dropper = Arc::new(limiters::token_dropper::TokenDropper::default());let historical_cfg = router::HistoricalConfig::new(false, 1);- let service = EventRestrictionService::new(CaptureMode::Events, Duration::from_secs(300));+ let service =+ EventRestrictionService::new(vec![Pipeline::Analytics], Duration::from_secs(300));let mut manager = RestrictionManager::new();- manager.restrictions.insert(- "test_token".to_string(),+ manager.insert_restrictions(+ Pipeline::Analytics,+ "test_token",vec![Restriction {restriction_type: RestrictionType::DropEvent,scope: RestrictionScope::AllEvents,@@ -933,10 +942,12 @@ mod tests {let dropper = Arc::new(limiters::token_dropper::TokenDropper::default());let historical_cfg = router::HistoricalConfig::new(false, 1);- let service = EventRestrictionService::new(CaptureMode::Events, Duration::from_secs(300));+ let service =+ EventRestrictionService::new(vec![Pipeline::Analytics], Duration::from_secs(300));let mut manager = RestrictionManager::new();- manager.restrictions.insert(- "test_token".to_string(),+ manager.insert_restrictions(+ Pipeline::Analytics,+ "test_token",vec![Restriction {restriction_type: RestrictionType::ForceOverflow,@@ -982,6 +993,146 @@ mod tests {assert!(captured[0].metadata.redirect_to_topic.is_none());}+ /// With an errortracking service configured, `$exception` events should be+ /// matched against errortracking-pipeline restrictions and dropped if so+ /// configured. Co-located analytics events must remain unaffected because+ /// they're matched against the (separate) analytics service.+ #[tokio::test]+ async fn test_process_events_errortracking_drop_only_affects_exceptions() {+ 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(+ "$exception",+ 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);++ // Single service serving both pipelines, with a DropEvent restriction+ // attached only to the errortracking pipeline.+ let service = EventRestrictionService::new(+ vec![Pipeline::Analytics, Pipeline::ErrorTracking],+ Duration::from_secs(300),+ );+ let mut manager = RestrictionManager::new();+ manager.insert_restrictions(+ Pipeline::ErrorTracking,+ "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,+ &events,+ &context,+ )+ .await+ .unwrap();++ let captured = sink.get_events();+ assert_eq!(+ captured.len(),+ 1,+ "exception should be dropped, pageview kept"+ );+ assert_eq!(captured[0].metadata.data_type, DataType::AnalyticsMain);+ assert_eq!(captured[0].event.event, "$pageview");+ }++ /// Mirror image: an analytics-scoped DropEvent must drop analytics events+ /// while leaving `$exception` events untouched even though the same+ /// service is responsible for the errortracking pipeline (no entry there).+ #[tokio::test]+ async fn test_process_events_analytics_drop_does_not_cross_into_errortracking() {+ 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(+ "$exception",+ 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);++ let service = EventRestrictionService::new(+ vec![Pipeline::Analytics, Pipeline::ErrorTracking],+ Duration::from_secs(300),+ );+ let mut manager = RestrictionManager::new();+ manager.insert_restrictions(+ Pipeline::Analytics,+ "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,+ &events,+ &context,+ )+ .await+ .unwrap();++ let captured = sink.get_events();+ assert_eq!(+ captured.len(),+ 1,+ "pageview should be dropped, exception kept"+ );+ assert_eq!(+ captured[0].metadata.data_type,+ DataType::ExceptionErrorTracking+ );+ assert_eq!(captured[0].event.event, "$exception");+ }+#[tokio::test]async fn test_process_events_analytics_historical_still_gets_restrictions() {// AnalyticsHistorical is part of the analytics pipeline, so restrictions@@ -1001,10 +1152,12 @@ mod tests {let dropper = Arc::new(limiters::token_dropper::TokenDropper::default());let historical_cfg = router::HistoricalConfig::new(false, 1);- let service = EventRestrictionService::new(CaptureMode::Events, Duration::from_secs(300));+ let service =+ EventRestrictionService::new(vec![Pipeline::Analytics], Duration::from_secs(300));let mut manager = RestrictionManager::new();- manager.restrictions.insert(- "test_token".to_string(),+ manager.insert_restrictions(+ Pipeline::Analytics,+ "test_token",vec![Restriction {restriction_type: RestrictionType::DropEvent,scope: RestrictionScope::AllEvents,@@ -1223,10 +1376,12 @@ mod tests {// Even with a limiter that would flag this token, force_overflow wins.let limiter = build_limiter(10, 10, Some("test_token".to_string()), false);- let service = EventRestrictionService::new(CaptureMode::Events, Duration::from_secs(300));+ let service =+ EventRestrictionService::new(vec![Pipeline::Analytics], Duration::from_secs(300));let mut manager = RestrictionManager::new();- manager.restrictions.insert(- "test_token".to_string(),+ manager.insert_restrictions(+ Pipeline::Analytics,+ "test_token",vec![Restriction {restriction_type: RestrictionType::ForceOverflow,scope: RestrictionScope::AllEvents,diff --git a/rust/capture/src/events/recordings.rs b/rust/capture/src/events/recordings.rsindex df958dc5006a..b469b6d7eb41 100644--- a/rust/capture/src/events/recordings.rs+++ b/rust/capture/src/events/recordings.rs@@ -27,6 +27,7 @@ use crate::{debug_or_info,event_restrictions::{AppliedRestrictions, EventContext as RestrictionEventContext, EventRestrictionService,+ Pipeline,},prometheus::report_dropped_events,sinks,@@ -245,7 +246,9 @@ pub async fn process_replay_events(now_ts: context.now.timestamp(),};- let applied = service.get_restrictions(&context.token, &event_ctx).await;+ let applied = service+ .get_restrictions(&context.token, &event_ctx, Pipeline::SessionRecordings)+ .await;if applied.should_drop() {report_dropped_events("event_restriction_drop", 1);@@ -527,7 +530,7 @@ mod tests {// ============ Restriction tests ============- use crate::config::CaptureMode;+ use crate::event_restrictions::Pipeline;use crate::event_restrictions::{EventRestrictionService, Restriction, RestrictionManager, RestrictionScope,};@@ -575,12 +578,15 @@ mod tests {events: events_captured.clone(),});- let service =- EventRestrictionService::new(CaptureMode::Recordings, Duration::from_secs(300));+ let service = EventRestrictionService::new(+ vec![Pipeline::SessionRecordings],+ Duration::from_secs(300),+ );let mut manager = RestrictionManager::new();- manager.restrictions.insert(- "test_token".to_string(),+ manager.insert_restrictions(+ Pipeline::SessionRecordings,+ "test_token",vec![Restriction {restriction_type: RestrictionType::DropEvent,scope: RestrictionScope::AllEvents,@@ -606,12 +612,15 @@ mod tests {events: events_captured.clone(),});- let service =- EventRestrictionService::new(CaptureMode::Recordings, Duration::from_secs(300));+ let service = EventRestrictionService::new(+ vec![Pipeline::SessionRecordings],+ Duration::from_secs(300),+ );let mut manager = RestrictionManager::new();- manager.restrictions.insert(- "test_token".to_string(),+ manager.insert_restrictions(+ Pipeline::SessionRecordings,+ "test_token",vec![Restriction {restriction_type: RestrictionType::RedirectToDlq,scope: RestrictionScope::AllEvents,@@ -639,12 +648,15 @@ mod tests {events: events_captured.clone(),});- let service =- EventRestrictionService::new(CaptureMode::Recordings, Duration::from_secs(300));+ let service = EventRestrictionService::new(+ vec![Pipeline::SessionRecordings],+ Duration::from_secs(300),+ );let mut manager = RestrictionManager::new();- manager.restrictions.insert(- "test_token".to_string(),+ manager.insert_restrictions(+ Pipeline::SessionRecordings,+ "test_token",vec![Restriction {restriction_type: RestrictionType::ForceOverflow,scope: RestrictionScope::AllEvents,@@ -672,12 +684,15 @@ mod tests {events: events_captured.clone(),});- let service =- EventRestrictionService::new(CaptureMode::Recordings, Duration::from_secs(300));+ let service = EventRestrictionService::new(+ vec![Pipeline::SessionRecordings],+ Duration::from_secs(300),+ );let mut manager = RestrictionManager::new();- manager.restrictions.insert(- "test_token".to_string(),+ manager.insert_restrictions(+ Pipeline::SessionRecordings,+ "test_token",vec![Restriction {restriction_type: RestrictionType::SkipPersonProcessing,scope: RestrictionScope::AllEvents,@@ -725,15 +740,18 @@ mod tests {events: events_captured.clone(),});- let service =- EventRestrictionService::new(CaptureMode::Recordings, Duration::from_secs(300));+ let service = EventRestrictionService::new(+ vec![Pipeline::SessionRecordings],+ Duration::from_secs(300),+ );// Create a restriction that only applies to a different sessionlet mut manager = RestrictionManager::new();let mut filters = crate::event_restrictions::RestrictionFilters::default();filters.session_ids.insert("other-session".to_string());- manager.restrictions.insert(- "test_token".to_string(),+ manager.insert_restrictions(+ Pipeline::SessionRecordings,+ "test_token",vec![Restriction {restriction_type: RestrictionType::DropEvent,scope: RestrictionScope::Filtered(filters),@@ -851,11 +869,14 @@ mod tests {events: events_captured.clone(),});- let service =- EventRestrictionService::new(CaptureMode::Recordings, Duration::from_secs(300));+ let service = EventRestrictionService::new(+ vec![Pipeline::SessionRecordings],+ Duration::from_secs(300),+ );let mut manager = RestrictionManager::new();- manager.restrictions.insert(- "test_token".to_string(),+ manager.insert_restrictions(+ Pipeline::SessionRecordings,+ "test_token",vec![Restriction {restriction_type: RestrictionType::ForceOverflow,scope: RestrictionScope::AllEvents,@@ -1013,11 +1034,14 @@ mod tests {// force_overflow short-circuits the limiter branch; the pipeline// must skip the redis call AND the histogram record.- let service =- EventRestrictionService::new(CaptureMode::Recordings, Duration::from_secs(300));+ let service = EventRestrictionService::new(+ vec![Pipeline::SessionRecordings],+ Duration::from_secs(300),+ );let mut manager = RestrictionManager::new();- manager.restrictions.insert(- "test_token".to_string(),+ manager.insert_restrictions(+ Pipeline::SessionRecordings,+ "test_token",vec![Restriction {restriction_type: RestrictionType::ForceOverflow,scope: RestrictionScope::AllEvents,diff --git a/rust/capture/src/otel/filtering.rs b/rust/capture/src/otel/filtering.rsindex 64421a442716..a1c5fdc2ae99 100644--- a/rust/capture/src/otel/filtering.rs+++ b/rust/capture/src/otel/filtering.rs@@ -5,7 +5,9 @@ use tracing::warn;use uuid::Uuid;use crate::api::CaptureError;-use crate::event_restrictions::{AppliedRestrictions, EventContext, EventRestrictionService};+use crate::event_restrictions::{+ AppliedRestrictions, EventContext, EventRestrictionService, Pipeline,+};use crate::prometheus::report_dropped_events;use crate::quota_limiters::CaptureQuotaLimiter;use crate::v0_request::{DataType, ProcessedEvent, ProcessedEventMetadata};@@ -62,7 +64,7 @@ pub async fn check_restrictions(now_ts,..Default::default()};- let applied = service.get_restrictions(token, &ctx).await;+ let applied = service.get_restrictions(token, &ctx, Pipeline::Ai).await;merged = merged.merge(applied);}diff --git a/rust/capture/src/router.rs b/rust/capture/src/router.rsindex 883a98063ff6..87d61ab4fb70 100644--- a/rust/capture/src/router.rs+++ b/rust/capture/src/router.rs@@ -43,6 +43,10 @@ pub struct State {pub global_rate_limiter_token_distinctid: Option<Arc<GlobalRateLimiter>>,pub quota_limiter: Arc<CaptureQuotaLimiter>,pub token_dropper: Arc<TokenDropper>,+ /// Restriction service scoped to all pipelines this capture deployment+ /// produces to (e.g. `[Analytics, ErrorTracking]` for the events+ /// deployment). Callers select the pipeline per event when looking up+ /// restrictions — see `events::analytics::process_events`.pub event_restriction_service: Option<EventRestrictionService>,pub event_payload_size_limit: usize,pub historical_cfg: HistoricalConfig,diff --git a/rust/capture/src/setup.rs b/rust/capture/src/setup.rsindex b45b510825c6..9dd4fcbc6e93 100644--- a/rust/capture/src/setup.rs+++ b/rust/capture/src/setup.rs@@ -7,7 +7,7 @@ use tracing::{info, warn};use crate::ai_s3::AiBlobStorage;use crate::config::{CaptureMode, Config};-use crate::event_restrictions::{EventRestrictionService, RedisRestrictionsRepository};+use crate::event_restrictions::{EventRestrictionService, Pipeline, RedisRestrictionsRepository};use crate::global_rate_limiter::GlobalRateLimiter;use crate::quota_limiters::{is_exception_event, is_llm_event, is_survey_event, CaptureQuotaLimiter,@@ -246,7 +246,11 @@ pub async fn build_components(config: Config, handles: LifecycleHandles) -> Capt};let event_restriction_service = if let Some(handle) = event_restrictions_handle {- create_event_restriction_service(&config, handle)+ create_event_restriction_service(+ &config,+ handle,+ Pipeline::for_capture_mode(config.capture_mode),+ )} else {None};@@ -346,6 +350,7 @@ async fn create_sink(fn create_event_restriction_service(config: &Config,handle: lifecycle::Handle,+ pipelines: Vec<Pipeline>,) -> Option<EventRestrictionService> {if !config.event_restrictions_enabled {return None;@@ -356,8 +361,9 @@ fn create_event_restriction_service(return None;};+ let pipelines_for_log = pipelines.clone();let service = EventRestrictionService::new(- config.capture_mode,+ pipelines,Duration::from_secs(config.event_restrictions_fail_open_after_secs),);@@ -401,7 +407,7 @@ fn create_event_restriction_service(});info!(- pipeline = %config.capture_mode.as_pipeline_name(),+ pipelines = ?pipelines_for_log,refresh_interval_secs = config.event_restrictions_refresh_interval_secs,fail_open_after_secs = config.event_restrictions_fail_open_after_secs,"Event restrictions enabled"diff --git a/rust/capture/src/v0_request.rs b/rust/capture/src/v0_request.rsindex 7050e5cb0757..351ccdbd91c3 100644--- a/rust/capture/src/v0_request.rs+++ b/rust/capture/src/v0_request.rs@@ -8,6 +8,7 @@ use tracing::{error, instrument, warn, Span};use crate::{api::CaptureError,+ event_restrictions::Pipeline,payload::{decompress_payload, Compression},};@@ -169,8 +170,33 @@ pub enum DataType {}impl DataType {- pub fn is_analytics_pipeline(self) -> bool {- matches!(self, Self::AnalyticsMain | Self::AnalyticsHistorical)+ /// Classify an event by its name (and historical-migration flag) into a+ /// `DataType`. Used by both v0's `process_single_event` and v1's+ /// `apply_restrictions` so the analytics → exception → heatmap →+ /// ingestion-warning split stays in one place.+ ///+ /// `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,+ }+ }++ /// Pipeline this event flows to, if any. Heatmaps, ingestion warnings,+ /// 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.+ pub fn pipeline(self) -> Option<Pipeline> {+ match self {+ Self::AnalyticsMain | Self::AnalyticsHistorical => Some(Pipeline::Analytics),+ Self::ExceptionErrorTracking => Some(Pipeline::ErrorTracking),+ Self::ClientIngestionWarning | Self::HeatmapMain | Self::SnapshotMain => None,+ }}}diff --git a/rust/capture/src/v1/analytics/process.rs b/rust/capture/src/v1/analytics/process.rsindex a5dd55c60cc8..1aacd4fbb2ae 100644--- a/rust/capture/src/v1/analytics/process.rs+++ b/rust/capture/src/v1/analytics/process.rs@@ -13,6 +13,7 @@ use super::response::Response;use super::types::{Batch, Event, EventResult, WrappedEvent};use crate::event_restrictions::{EventContext, EventRestrictionService};use crate::global_rate_limiter::{GlobalRateLimitKey, GlobalRateLimiter};+use crate::v0_request::DataType;use tracing::Level;use crate::router;@@ -269,6 +270,14 @@ async fn apply_restrictions(continue;}+ // v1 hasn't classified events into `DataType` yet, so derive the+ // pipeline directly from the event name. `historical_migration` is+ // irrelevant for pipeline lookup — `AnalyticsMain` and+ // `AnalyticsHistorical` both map to `Pipeline::Analytics`.+ let Some(pipeline) = DataType::from_event_name(&event.event.event, false).pipeline() else {+ continue;+ };+let event_ctx = EventContext {distinct_id: Some(&event.event.distinct_id),session_id: event.event.session_id.as_deref(),@@ -277,7 +286,7 @@ async fn apply_restrictions(now_ts,};- let applied = service.get_restrictions(token, &event_ctx).await;+ let applied = service.get_restrictions(token, &event_ctx, pipeline).await;if applied.should_drop() {event.result = EventResult::Drop;@@ -371,9 +380,8 @@ mod tests {use uuid::Uuid;use super::*;- use crate::config::CaptureMode;use crate::event_restrictions::{- Restriction, RestrictionManager, RestrictionScope, RestrictionType,+ Pipeline, Restriction, RestrictionManager, RestrictionScope, RestrictionType,};use crate::v1::analytics::types::{Batch, Event, Options};use crate::v1::sinks::Destination;@@ -823,9 +831,9 @@ mod tests {restrictions: Vec<Restriction>,) -> EventRestrictionService {let service =- EventRestrictionService::new(CaptureMode::Events, StdDuration::from_secs(300));+ EventRestrictionService::new(vec![Pipeline::Analytics], StdDuration::from_secs(300));let mut manager = RestrictionManager::new();- manager.restrictions.insert(token.to_string(), restrictions);+ manager.insert_restrictions(Pipeline::Analytics, token, restrictions);service.update(manager).await;service}@@ -833,7 +841,7 @@ mod tests {#[tokio::test]async fn restrictions_no_restrictions_passthrough() {let service =- EventRestrictionService::new(CaptureMode::Events, StdDuration::from_secs(300));+ EventRestrictionService::new(vec![Pipeline::Analytics], StdDuration::from_secs(300));service.update(RestrictionManager::new()).await;let mut events = vec![wrapped_event("$pageview", "user-1")];@@ -1629,7 +1637,7 @@ mod tests {// Stage 2: restrictions (no rules → passthrough, still iterates).let service =- EventRestrictionService::new(CaptureMode::Events, StdDuration::from_secs(300));+ 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;diff --git a/rust/capture/tests/integration_ai_restrictions.rs b/rust/capture/tests/integration_ai_restrictions.rsindex 8664e54e643a..e6107e882645 100644--- a/rust/capture/tests/integration_ai_restrictions.rs+++ b/rust/capture/tests/integration_ai_restrictions.rs@@ -9,7 +9,8 @@ use capture::ai_s3::{BlobStorage, MockBlobStorage};use capture::api::CaptureError;use capture::config::CaptureMode;use capture::event_restrictions::{- EventRestrictionService, Restriction, RestrictionManager, RestrictionScope, RestrictionType,+ EventRestrictionService, Pipeline, Restriction, RestrictionManager, RestrictionScope,+ RestrictionType,};use capture::quota_limiters::CaptureQuotaLimiter;use capture::router::router;@@ -150,11 +151,12 @@ async fn setup_ai_router_with_restriction(let quota_limiter =CaptureQuotaLimiter::new(&cfg, redis.clone(), Duration::from_secs(60 * 60 * 24 * 7));- let service = EventRestrictionService::new(CaptureMode::Ai, Duration::from_secs(300));+ let service = EventRestrictionService::new(vec![Pipeline::Ai], Duration::from_secs(300));let mut manager = RestrictionManager::new();- manager.restrictions.insert(- token.to_string(),+ manager.insert_restrictions(+ Pipeline::Ai,+ token,vec![Restriction {restriction_type,scope: RestrictionScope::AllEvents,@@ -466,11 +468,12 @@ async fn setup_ai_router_with_redirect_to_topic(let quota_limiter =CaptureQuotaLimiter::new(&cfg, redis.clone(), Duration::from_secs(60 * 60 * 24 * 7));- let service = EventRestrictionService::new(CaptureMode::Ai, Duration::from_secs(300));+ let service = EventRestrictionService::new(vec![Pipeline::Ai], Duration::from_secs(300));let mut manager = RestrictionManager::new();- manager.restrictions.insert(- token.to_string(),+ manager.insert_restrictions(+ Pipeline::Ai,+ token,vec![Restriction {restriction_type: RestrictionType::RedirectToTopic,scope: RestrictionScope::AllEvents,@@ -539,11 +542,12 @@ async fn setup_ai_router_with_force_overflow_and_limiter(let quota_limiter =CaptureQuotaLimiter::new(&cfg, redis.clone(), Duration::from_secs(60 * 60 * 24 * 7));- let service = EventRestrictionService::new(CaptureMode::Ai, Duration::from_secs(300));+ let service = EventRestrictionService::new(vec![Pipeline::Ai], Duration::from_secs(300));let mut manager = RestrictionManager::new();- manager.restrictions.insert(- token.to_string(),+ manager.insert_restrictions(+ Pipeline::Ai,+ token,vec![Restriction {restriction_type: RestrictionType::ForceOverflow,scope: RestrictionScope::AllEvents,diff --git a/rust/capture/tests/integration_analytics_restrictions.rs b/rust/capture/tests/integration_analytics_restrictions.rsindex ab62e167ae14..42238a2ba7ea 100644--- a/rust/capture/tests/integration_analytics_restrictions.rs+++ b/rust/capture/tests/integration_analytics_restrictions.rs@@ -8,7 +8,8 @@ use axum_test_helper::TestClient;use capture::api::CaptureError;use capture::config::CaptureMode;use capture::event_restrictions::{- EventRestrictionService, Restriction, RestrictionManager, RestrictionScope, RestrictionType,+ EventRestrictionService, Pipeline, Restriction, RestrictionManager, RestrictionScope,+ RestrictionType,};use capture::quota_limiters::CaptureQuotaLimiter;use capture::router::router;@@ -84,11 +85,12 @@ 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(CaptureMode::Events, Duration::from_secs(300));+ let service = EventRestrictionService::new(vec![Pipeline::Analytics], Duration::from_secs(300));let mut manager = RestrictionManager::new();- manager.restrictions.insert(- token.to_string(),+ manager.insert_restrictions(+ Pipeline::Analytics,+ token,vec![Restriction {restriction_type,scope: RestrictionScope::AllEvents,@@ -425,11 +427,12 @@ async fn setup_analytics_router_with_redirect_to_topic(let quota_limiter =CaptureQuotaLimiter::new(&cfg, redis.clone(), Duration::from_secs(60 * 60 * 24 * 7));- let service = EventRestrictionService::new(CaptureMode::Events, Duration::from_secs(300));+ let service = EventRestrictionService::new(vec![Pipeline::Analytics], Duration::from_secs(300));let mut manager = RestrictionManager::new();- manager.restrictions.insert(- token.to_string(),+ manager.insert_restrictions(+ Pipeline::Analytics,+ token,vec![Restriction {restriction_type: RestrictionType::RedirectToTopic,scope: RestrictionScope::AllEvents,diff --git a/rust/capture/tests/integration_otel_endpoint.rs b/rust/capture/tests/integration_otel_endpoint.rsindex c8d25e2620fc..1c1ce0514d2f 100644--- a/rust/capture/tests/integration_otel_endpoint.rs+++ b/rust/capture/tests/integration_otel_endpoint.rs@@ -7,8 +7,8 @@ use capture::ai_s3::MockBlobStorage;use capture::api::CaptureError;use capture::config::CaptureMode;use capture::event_restrictions::{- EventRestrictionService, Restriction, RestrictionFilters, RestrictionManager, RestrictionScope,- RestrictionType,+ EventRestrictionService, Pipeline, Restriction, RestrictionFilters, RestrictionManager,+ RestrictionScope, RestrictionType,};use capture::quota_limiters::{is_llm_event, CaptureQuotaLimiter, EventInfo};use capture::router::router;@@ -296,9 +296,12 @@ fn make_two_span_request() -> ExportTraceServiceRequest {}async fn make_restriction_service(restrictions: Vec<Restriction>) -> EventRestrictionService {- let service = EventRestrictionService::new(CaptureMode::Events, Duration::from_secs(300));+ // OTel runs in the AI capture deployment, so restrictions must be indexed+ // under Pipeline::Ai — that's the pipeline `otel/filtering.rs` looks up+ // with for every span.+ let service = EventRestrictionService::new(vec![Pipeline::Ai], Duration::from_secs(300));let mut manager = RestrictionManager::new();- manager.restrictions.insert(TOKEN.to_string(), restrictions);+ manager.insert_restrictions(Pipeline::Ai, TOKEN, restrictions);service.update(manager).await;service}diff --git a/rust/capture/tests/integration_replay_restrictions.rs b/rust/capture/tests/integration_replay_restrictions.rsindex 7809b0b58f5e..54e87424b5e2 100644--- a/rust/capture/tests/integration_replay_restrictions.rs+++ b/rust/capture/tests/integration_replay_restrictions.rs@@ -8,7 +8,8 @@ use axum_test_helper::TestClient;use capture::api::CaptureError;use capture::config::CaptureMode;use capture::event_restrictions::{- EventRestrictionService, Restriction, RestrictionManager, RestrictionScope, RestrictionType,+ EventRestrictionService, Pipeline, Restriction, RestrictionManager, RestrictionScope,+ RestrictionType,};use capture::quota_limiters::CaptureQuotaLimiter;use capture::router::router;@@ -85,11 +86,13 @@ async fn setup_recordings_router_with_restriction(let quota_limiter =CaptureQuotaLimiter::new(&cfg, redis.clone(), Duration::from_secs(60 * 60 * 24 * 7));- let service = EventRestrictionService::new(CaptureMode::Recordings, Duration::from_secs(300));+ let service =+ EventRestrictionService::new(vec![Pipeline::SessionRecordings], Duration::from_secs(300));let mut manager = RestrictionManager::new();- manager.restrictions.insert(- token.to_string(),+ manager.insert_restrictions(+ Pipeline::SessionRecordings,+ token,vec![Restriction {restriction_type,scope: RestrictionScope::AllEvents,@@ -451,11 +454,13 @@ async fn setup_recordings_router_with_redirect_to_topic(let quota_limiter =CaptureQuotaLimiter::new(&cfg, redis.clone(), Duration::from_secs(60 * 60 * 24 * 7));- let service = EventRestrictionService::new(CaptureMode::Recordings, Duration::from_secs(300));+ let service =+ EventRestrictionService::new(vec![Pipeline::SessionRecordings], Duration::from_secs(300));let mut manager = RestrictionManager::new();- manager.restrictions.insert(- token.to_string(),+ manager.insert_restrictions(+ Pipeline::SessionRecordings,+ token,vec![Restriction {restriction_type: RestrictionType::RedirectToTopic,scope: RestrictionScope::AllEvents,