: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): add Import capture mode for historical backfills (#71800)
Eli Reisman3ccee865b114
diff --git a/rust/capture/docs/ai-endpoint-parity.md b/rust/capture/docs/ai-endpoint-parity.mdindex 45ef9b817507..4099c0aa6e44 100644--- a/rust/capture/docs/ai-endpoint-parity.md+++ b/rust/capture/docs/ai-endpoint-parity.md@@ -92,6 +92,19 @@ AI endpoint hardcodes `historical_migration: false`. This is intentional because- Historical rerouting adds complexity without clear benefit for AI use case- Can be added later if backfill support is needed+**Interaction with `CaptureMode::Import`:** the `historical_migration: false`+hardcode is no longer the only thing keeping the AI and OTEL handlers out of an+import-only deployment. Import mode's router arm does not register `ai_router`+or `otel_router` at all (see `router.rs`), so `/i/v0/ai` and `/i/v0/ai/otel`+return 404 there. This matters because those handlers build their own+`ProcessingContext` with `historical_migration: false`, which would sidestep+Import's historical-only drop gate and its GRL bypass and return a false 200 for+traffic the deployment silently discards. Dropping the routes is the structural+guarantee; the hardcode is defense in depth. `/i/v0/ai/batch` stays reachable in+Import mode because it lives on `batch_router` and dispatches to the gated+`v0_endpoint::event` handler, which honors the batch's `historical_migration`+flag.+## Notes- The AI endpoint's unique features (multipart parsing, blob handling, etc.) are intentional and should be preserveddiff --git a/rust/capture/src/config.rs b/rust/capture/src/config.rsindex 4ba453e8be58..aefad9e8a714 100644--- a/rust/capture/src/config.rs+++ b/rust/capture/src/config.rs@@ -11,6 +11,14 @@ pub enum CaptureMode {Events,Recordings,Ai,+ /// Analytics ingestion dedicated to historical backfills (the+ /// batch-import-worker). Like `Events` for the batch/event paths, but with+ /// three differences: it never applies the global rate limiter, it drops any+ /// batch not flagged `historical_migration: true`, and it does not register+ /// the AI or OTEL routes (those handlers hardcode `historical_migration:+ /// false` and would bypass both gates). See `applies_global_rate_limit`,+ /// `requires_historical_migration`, and the router's per-mode arm.+ Import,}impl CaptureMode {@@ -19,8 +27,27 @@ impl CaptureMode {CaptureMode::Events => "events",CaptureMode::Recordings => "recordings",CaptureMode::Ai => "ai",+ CaptureMode::Import => "import",}}++ /// Whether this mode subjects incoming events to the per-(token,+ /// distinct_id) global rate limiter. `Import` opts out: historical+ /// backfills are internal traffic that must not be throttled.+ ///+ /// Note this is necessary but not sufficient: only the analytics processing+ /// paths (legacy `events::analytics` and `v1::analytics`) actually consult+ /// the limiter, so `Recordings` never rate-limits despite returning `true`+ /// here. The predicate gates the two analytics paths; other paths ignore it.+ pub fn applies_global_rate_limit(&self) -> bool {+ !matches!(self, CaptureMode::Import)+ }++ /// Whether this mode drops any batch not marked `historical_migration:+ /// true`. Only `Import` does — it exclusively ingests historical data.+ pub fn requires_historical_migration(&self) -> bool {+ matches!(self, CaptureMode::Import)+ }}impl std::str::FromStr for CaptureMode {@@ -31,6 +58,7 @@ impl std::str::FromStr for CaptureMode {"events" => Ok(CaptureMode::Events),"recordings" => Ok(CaptureMode::Recordings),"ai" => Ok(CaptureMode::Ai),+ "import" => Ok(CaptureMode::Import),_ => Err(format!("Unknown Capture Type: {s}")),}}@@ -556,7 +584,7 @@ pub struct KafkaConfig {#[cfg(test)]mod tests {- use super::{AiRouting, AiSinkMode, Config};+ use super::{AiRouting, AiSinkMode, CaptureMode, Config};use std::collections::HashMap;use std::str::FromStr;@@ -650,6 +678,54 @@ mod tests {);}+ #[test]+ fn capture_mode_from_str_and_tag_roundtrip() {+ // Locks the CAPTURE_MODE env contract, including the new `import` mode+ // and case/whitespace handling, plus the tag used as a metric label.+ let ok = [+ ("events", CaptureMode::Events, "events"),+ ("Recordings", CaptureMode::Recordings, "recordings"),+ (" ai ", CaptureMode::Ai, "ai"),+ ("import", CaptureMode::Import, "import"),+ ("IMPORT", CaptureMode::Import, "import"),+ ];+ for (input, expected, tag) in ok {+ let parsed = CaptureMode::from_str(input).unwrap();+ assert_eq!(parsed, expected, "input={input}");+ assert_eq!(parsed.as_tag(), tag, "input={input}");+ }++ for bad in ["", "imports", "backfill", "historical"] {+ assert!(+ CaptureMode::from_str(bad).is_err(),+ "expected err for {bad:?}"+ );+ }+ }++ #[test]+ fn capture_mode_import_policy_differs_from_events() {+ // The whole point of Import mode: it skips the global rate limiter and+ // drops non-historical batches, while every other mode does neither.+ assert!(!CaptureMode::Import.applies_global_rate_limit());+ assert!(CaptureMode::Import.requires_historical_migration());++ for mode in [+ CaptureMode::Events,+ CaptureMode::Recordings,+ CaptureMode::Ai,+ ] {+ assert!(+ mode.applies_global_rate_limit(),+ "{mode:?} should apply GRL"+ );+ assert!(+ !mode.requires_historical_migration(),+ "{mode:?} should not require historical_migration"+ );+ }+ }+#[test]fn ai_sink_mode_from_str() {// Locks the AI_SINK_MODE env contract: accepted spellings (incl. thediff --git a/rust/capture/src/event_restrictions/types.rs b/rust/capture/src/event_restrictions/types.rsindex 72a2c8dda212..ae120283ddd2 100644--- a/rust/capture/src/event_restrictions/types.rs+++ b/rust/capture/src/event_restrictions/types.rs@@ -46,11 +46,14 @@ impl Pipeline {/// 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.+ /// service must serve restrictions for all three pipelines. `Import` is an+ /// events deployment restricted to backfills, so it serves the same three./// Other deployments serve their single pipeline.pub fn for_capture_mode(mode: CaptureMode) -> Vec<Pipeline> {match mode {- CaptureMode::Events => vec![Self::Analytics, Self::ErrorTracking, Self::Ai],+ CaptureMode::Events | CaptureMode::Import => {+ vec![Self::Analytics, Self::ErrorTracking, Self::Ai]+ }CaptureMode::Recordings => vec![Self::SessionRecordings],CaptureMode::Ai => vec![Self::Ai],}@@ -384,6 +387,13 @@ mod tests {Pipeline::for_capture_mode(CaptureMode::Events),vec![Pipeline::Analytics, Pipeline::ErrorTracking, Pipeline::Ai]);+ // Import is an events deployment restricted to backfills, so it must+ // serve the identical pipeline set -- a backfill can carry $exception+ // and $ai_* events too.+ assert_eq!(+ Pipeline::for_capture_mode(CaptureMode::Import),+ Pipeline::for_capture_mode(CaptureMode::Events)+ );assert_eq!(Pipeline::for_capture_mode(CaptureMode::Recordings),vec![Pipeline::SessionRecordings]diff --git a/rust/capture/src/events/analytics.rs b/rust/capture/src/events/analytics.rsindex 65f71bcb4aa6..ceb4f2a7b7f0 100644--- a/rust/capture/src/events/analytics.rs+++ b/rust/capture/src/events/analytics.rs@@ -250,6 +250,25 @@ pub async fn process_events(Span::current().record("request_id", &context.request_id);Span::current().record("is_mirror_deploy", context.is_mirror_deploy);+ // Import mode ingests only historical backfills: drop any batch not+ // flagged `historical_migration` (a batch-level flag) and return Ok so the+ // endpoint responds 200 (accept-and-discard) — the batch-import-worker must+ // not retry. Non-batch legacy endpoints never set the flag, so they are+ // always dropped in Import mode, which is intended: imports only arrive via+ // `/batch` and the v1 endpoint.+ if context.capture_mode.requires_historical_migration() && !context.historical_migration {+ let dropped = events.len() as u64;+ // Same label value as the v1 path's capture_v1_events_dropped{reason=...}+ // so one alert expression covers both metric names.+ report_dropped_events("non_historical_import", dropped);+ warn!(+ token = context.token,+ dropped_events = dropped,+ "import mode dropped non-historical batch"+ );+ return Ok(());+ }+// 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@@ -375,46 +394,64 @@ pub async fn process_events(}// Per-(token, distinct_id) global rate limiting: skip person processing for- // hot distinct_ids and reroute AnalyticsMain events to overflow.- if let Some(ref limiter) = global_rate_limiter {- let mut limited_distinct_ids: HashSet<&str> = HashSet::new();- let mut limited_event_count: u64 = 0;- for event in events.iter_mut() {- let cache_key =- GlobalRateLimitKey::TokenDistinctId(&context.token, &event.event.distinct_id)- .to_cache_key();- if limiter.is_limited(&cache_key, 1).await.is_some() {- event.metadata.skip_person_processing = true;- // Reroute the hot key to overflow. AnalyticsMain only: historical- // never overflows, the AI lane keeps its dedicated topic (v1- // 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);+ // hot distinct_ids and reroute AnalyticsMain events to overflow. Import mode+ // opts out entirely — historical backfills must never be throttled — so the+ // limiter is skipped even if one were wired.+ //+ // DIVERGENCE from v1 (`v1::analytics::process`), intentional and out of scope+ // to reconcile here — a future routing refactor must not assume parity:+ // 1. Ordering: legacy runs this GRL step BEFORE burst overflow stamping+ // (`stamp_overflow_reason` below); v1 runs the GRL AFTER its overflow+ // stamping. Both set overflow_reason on AnalyticsMain only, so the+ // end state matches, but the pass order differs.+ // 2. Legacy does NOT skip events that already carry a person-processing+ // opt-out; v1 skips events with `force_disable_person_processing`+ // already set before consulting the limiter.+ // 3. Lane assignment is a single `DataType::from_event_name` match in+ // legacy versus assign-then-reroute in v1.+ // Import is unaffected by all three: the GRL never runs (guard below) and no+ // overflowable lane is reachable, so behavior is identical across paths.+ if context.capture_mode.applies_global_rate_limit() {+ if let Some(ref limiter) = global_rate_limiter {+ let mut limited_distinct_ids: HashSet<&str> = HashSet::new();+ let mut limited_event_count: u64 = 0;+ for event in events.iter_mut() {+ let cache_key =+ GlobalRateLimitKey::TokenDistinctId(&context.token, &event.event.distinct_id)+ .to_cache_key();+ if limiter.is_limited(&cache_key, 1).await.is_some() {+ event.metadata.skip_person_processing = true;+ // Reroute the hot key to overflow. AnalyticsMain only: historical+ // never overflows, the AI lane keeps its dedicated topic (v1+ // 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);+ }+ limited_distinct_ids.insert(&event.event.distinct_id);+ limited_event_count += 1;}- limited_distinct_ids.insert(&event.event.distinct_id);- limited_event_count += 1;}- }- if limited_event_count > 0 {- let ids: Vec<&str> = limited_distinct_ids.iter().copied().collect();- let preview: String = if ids.len() > 10 {- format!("{}...", ids[..10].join(", "))- } else {- ids.join(", ")- };- counter!(- "capture_events_rate_limited_token_distinctid",- "reason" => "global_rate_limit_token_distinctid",- )- .increment(limited_event_count);- warn!(- token = context.token,- limited_event_count = limited_event_count,- distinct_id_count = limited_distinct_ids.len(),- distinct_ids = %preview,- "events rate limited by distinct_id -- person processing disabled"- );+ if limited_event_count > 0 {+ let ids: Vec<&str> = limited_distinct_ids.iter().copied().collect();+ let preview: String = if ids.len() > 10 {+ format!("{}...", ids[..10].join(", "))+ } else {+ ids.join(", ")+ };+ counter!(+ "capture_events_rate_limited_token_distinctid",+ "reason" => "global_rate_limit_token_distinctid",+ )+ .increment(limited_event_count);+ warn!(+ token = context.token,+ limited_event_count = limited_event_count,+ distinct_id_count = limited_distinct_ids.len(),+ distinct_ids = %preview,+ "events rate limited by distinct_id -- person processing disabled"+ );+ }}}@@ -473,6 +510,7 @@ mod tests {is_mirror_deploy: false,historical_migration: false,chatty_debug_enabled: false,+ capture_mode: crate::config::CaptureMode::Events,}}@@ -2155,6 +2193,138 @@ mod tests {assert!(!captured[0].metadata.force_overflow);}+ // ==================== Import-mode legacy path tests ======================++ #[tokio::test]+ async fn import_mode_drops_non_historical_batch() {+ // Import mode ingests only backfills: a batch without historical_migration+ // must be dropped (200, nothing published) so live traffic can't leak in.+ let now = DateTime::parse_from_rfc3339("2023-01-01T12:00:00Z")+ .unwrap()+ .with_timezone(&Utc);+ let mut context = create_test_context(now, None);+ context.capture_mode = crate::config::CaptureMode::Import;+ // historical_migration defaults to false — this batch must be dropped.+ let events = vec![+ create_test_event(Some("2023-01-01T11:00:00Z".to_string()), None, None),+ create_test_event(Some("2023-01-01T11:00:00Z".to_string()), None, None),+ ];++ let sink = Arc::new(MockSink::new());+ let dropper = Arc::new(limiters::token_dropper::TokenDropper::default());+ let historical_cfg = router::HistoricalConfig::new(false, 1);++ process_events(+ sink.clone(),+ dropper,+ None,+ historical_cfg,+ None,+ None,+ None,+ &AiRouting::Primary,+ events,+ &context,+ )+ .await+ .unwrap();++ assert_eq!(+ sink.get_events().len(),+ 0,+ "non-historical batch must be fully dropped in Import mode"+ );+ }++ #[tokio::test]+ async fn import_mode_processes_historical_batch() {+ // A properly flagged historical batch flows through Import mode to the sink.+ let now = DateTime::parse_from_rfc3339("2023-01-01T12:00:00Z")+ .unwrap()+ .with_timezone(&Utc);+ let mut context = create_test_context(now, None);+ context.capture_mode = crate::config::CaptureMode::Import;+ context.historical_migration = true;+ let events = vec![create_test_event(+ Some("2023-01-01T11:00:00Z".to_string()),+ None,+ None,+ )];++ let sink = Arc::new(MockSink::new());+ let dropper = Arc::new(limiters::token_dropper::TokenDropper::default());+ let historical_cfg = router::HistoricalConfig::new(false, 1);++ process_events(+ sink.clone(),+ dropper,+ None,+ historical_cfg,+ None,+ None,+ None,+ &AiRouting::Primary,+ events,+ &context,+ )+ .await+ .unwrap();++ let captured = sink.get_events();+ assert_eq!(captured.len(), 1);+ assert_eq!(+ captured[0].metadata.data_type,+ DataType::AnalyticsHistorical+ );+ }++ #[tokio::test]+ async fn import_mode_skips_global_rate_limiter() {+ // Import mode must never apply the global rate limiter. Same hot key that+ // sets skip_person_processing in Events mode (see+ // global_rate_limit_does_not_overflow_historical_events) must leave the+ // event untouched here. Uses a historical batch so it isn't dropped first.+ let now = DateTime::parse_from_rfc3339("2023-01-01T12:00:00Z")+ .unwrap()+ .with_timezone(&Utc);+ let mut context = create_test_context(now, None);+ context.capture_mode = crate::config::CaptureMode::Import;+ context.historical_migration = true;+ let events = vec![create_test_event(+ Some("2023-01-01T11:00:00Z".to_string()),+ None,+ None,+ )];++ let sink = Arc::new(MockSink::new());+ let dropper = Arc::new(limiters::token_dropper::TokenDropper::default());+ let historical_cfg = router::HistoricalConfig::new(false, 1);+ let global_limiter = Arc::new(GlobalRateLimiter::mock_limiting(&["test_token:test_user"]));++ process_events(+ sink.clone(),+ dropper,+ None,+ historical_cfg,+ Some(global_limiter),+ None,+ None,+ &AiRouting::Primary,+ events,+ &context,+ )+ .await+ .unwrap();++ let captured = sink.get_events();+ assert_eq!(captured.len(), 1);+ assert!(+ !captured[0].metadata.skip_person_processing,+ "GRL must be skipped in Import mode — person processing must stay enabled"+ );+ assert_eq!(captured[0].metadata.overflow_reason, None);+ }+// ============ end-to-end pipeline -> real KafkaSinkBase tests ============// These catch pipeline-to-sink contract drift that neither side's unit// tests alone cover: stamp metadata in pipeline, ensure the real sinkdiff --git a/rust/capture/src/events/recordings.rs b/rust/capture/src/events/recordings.rsindex 3822fd1de6cd..41343ab3fba5 100644--- a/rust/capture/src/events/recordings.rs+++ b/rust/capture/src/events/recordings.rs@@ -586,6 +586,7 @@ mod tests {chatty_debug_enabled: false,user_agent: None,path: "/s/".to_string(),+ capture_mode: crate::config::CaptureMode::Recordings,}}diff --git a/rust/capture/src/payload/analytics.rs b/rust/capture/src/payload/analytics.rsindex f98a3c46b27c..d027ec9dc596 100644--- a/rust/capture/src/payload/analytics.rs+++ b/rust/capture/src/payload/analytics.rs@@ -119,6 +119,7 @@ pub async fn handle_event_payload(historical_migration,user_agent: Some(metadata.user_agent.to_string()),chatty_debug_enabled,+ capture_mode: state.capture_mode,};debug_or_info!(chatty_debug_enabled, context=?context, event_count=?events.len(), "processing complete");diff --git a/rust/capture/src/payload/recordings.rs b/rust/capture/src/payload/recordings.rsindex 5c9734973cd3..27f25fdd873f 100644--- a/rust/capture/src/payload/recordings.rs+++ b/rust/capture/src/payload/recordings.rs@@ -126,6 +126,7 @@ pub async fn handle_recording_payload(historical_migration: false, // recordings don't support historical migrationuser_agent: Some(metadata.user_agent.to_string()),chatty_debug_enabled,+ capture_mode: state.capture_mode,};// Apply all billing limit quotas and drop partial or wholediff --git a/rust/capture/src/quota_limiters.rs b/rust/capture/src/quota_limiters.rsindex bd998da8938f..6f7906d1649f 100644--- a/rust/capture/src/quota_limiters.rs+++ b/rust/capture/src/quota_limiters.rs@@ -231,7 +231,7 @@ impl CaptureQuotaLimiter {pub fn get_resource_for_mode(mode: CaptureMode) -> QuotaResource {match mode {- CaptureMode::Events | CaptureMode::Ai => QuotaResource::Events,+ CaptureMode::Events | CaptureMode::Ai | CaptureMode::Import => QuotaResource::Events,CaptureMode::Recordings => QuotaResource::Recordings,}}diff --git a/rust/capture/src/router.rs b/rust/capture/src/router.rsindex 8f5e51bb58d3..0aaf39412f7a 100644--- a/rust/capture/src/router.rs+++ b/rust/capture/src/router.rs@@ -111,6 +111,10 @@ pub struct State {/// `overflow_limiter` / `event_restriction_service`. Never awaited and/// never allowed to fail a request.pub ingestion_warning_emitter: Option<Arc<dyn WarningEmitter>>,+ /// Deployment capture mode. Threaded into the analytics processing paths+ /// (legacy and v1) so mode-specific policy — Import skips the global rate+ /// limiter and drops non-historical batches — lives with the pipeline.+ pub capture_mode: CaptureMode,}#[derive(Clone, Copy)]@@ -215,6 +219,7 @@ pub fn router<TZ: TimeSource + Send + Sync + 'static, R: Client + Send + Sync +ai_routing,ai_events_overflow_enabled,ingestion_warning_emitter,+ capture_mode,};// Very permissive CORS policy, as old SDK versions@@ -396,6 +401,16 @@ pub fn router<TZ: TimeSource + Send + Sync + 'static, R: Client + Send + Sync +.merge(test_router).merge(ai_router).merge(otel_router),+ // Import must not register ai_router/otel_router: those handlers build+ // their own ProcessingContext with historical_migration: false, so they+ // sidestep both Import gates (historical-only drop and GRL bypass) and+ // would return a false 200 for events this deployment silently discards.+ // The /i/v0/ai/batch path stays reachable via batch_router, which+ // dispatches to the gated v0_endpoint::event handler.+ CaptureMode::Import => Router::new()+ .merge(batch_router)+ .merge(event_router)+ .merge(test_router),CaptureMode::Recordings => Router::new().merge(recordings_router),};@@ -419,9 +434,15 @@ pub fn router<TZ: TimeSource + Send + Sync + 'static, R: Client + Send + Sync +// Merged after every legacy layer above: the v1 router owns its full// middleware stack (CORS, limits) and applies the same per-route// concurrency cap to its own routes.- if matches!(capture_mode, CaptureMode::Events | CaptureMode::Ai)- && state.v1_sink_router.is_some()- {+ //+ // Matched exhaustively, like the legacy route gating above: a new capture+ // mode must declare whether it serves the v1 analytics endpoint instead of+ // silently defaulting to "no v1 routes" and 404ing its traffic.+ let serves_v1_analytics = match capture_mode {+ CaptureMode::Events | CaptureMode::Ai | CaptureMode::Import => true,+ CaptureMode::Recordings => false,+ };+ if serves_v1_analytics && state.v1_sink_router.is_some() {router = router.merge(crate::v1::router::router(crate::v1::router::RouterConfig {concurrency_limit,max_compressed_body_bytes: state.capture_v1_max_compressed_body_bytes,diff --git a/rust/capture/src/setup.rs b/rust/capture/src/setup.rsindex 7a565d45de2a..b5b69d197a8f 100644--- a/rust/capture/src/setup.rs+++ b/rust/capture/src/setup.rs@@ -213,7 +213,7 @@ pub async fn build_components(// event individually, so we should instead allow for some small multiple of our max compressed// body size to be unpacked. If a single event is still too big, we'll drop it at kafka send time.let event_payload_max_bytes = match config.capture_mode {- CaptureMode::Events | CaptureMode::Ai => BATCH_BODY_SIZE * 5,+ CaptureMode::Events | CaptureMode::Ai | CaptureMode::Import => BATCH_BODY_SIZE * 5,CaptureMode::Recordings => config.kafka.kafka_producer_message_max_bytes as usize,};diff --git a/rust/capture/src/v0_request.rs b/rust/capture/src/v0_request.rsindex 271aa8418e2b..3603c70c83f2 100644--- a/rust/capture/src/v0_request.rs+++ b/rust/capture/src/v0_request.rs@@ -8,6 +8,7 @@ use tracing::{instrument, Span};use crate::{api::CaptureError,+ config::CaptureMode,event_restrictions::Pipeline,payload::{decompress_payload, Compression},};@@ -143,6 +144,10 @@ pub struct ProcessingContext {pub is_mirror_deploy: bool, // TODO(eli): can remove after migrationpub historical_migration: bool,pub chatty_debug_enabled: bool,+ /// Deployment capture mode. Governs Import-only policy in the legacy+ /// analytics path: skip the global rate limiter and drop any batch not+ /// flagged `historical_migration: true`.+ pub capture_mode: CaptureMode,}// these are the legacy endpoints capture maintains. Can eliminate thisdiff --git a/rust/capture/src/v1/analytics/constants.rs b/rust/capture/src/v1/analytics/constants.rsindex 2578bf7859a2..faa746ca3c8a 100644--- a/rust/capture/src/v1/analytics/constants.rs+++ b/rust/capture/src/v1/analytics/constants.rs@@ -48,6 +48,10 @@ pub(super) const DETAIL_PERSON_PROCESSING_DISABLED: &str = "person_processing_di/// Detail tag for events dropped by the event restriction service.pub(super) const DETAIL_EVENT_RESTRICTION_DROP: &str = "event_restriction_drop";+/// Detail tag for batches dropped by an Import-mode deployment because they+/// were not flagged `historical_migration: true`.+pub(super) const DETAIL_NON_HISTORICAL_DROP: &str = "non_historical_import_drop";+/// Detail tag for events dropped due to uncoercible options fields.pub(super) const DETAIL_INVALID_OPTIONS: &str = "invalid_options";diff --git a/rust/capture/src/v1/analytics/process.rs b/rust/capture/src/v1/analytics/process.rsindex f0acaffd1d26..2f668d44fa59 100644--- a/rust/capture/src/v1/analytics/process.rs+++ b/rust/capture/src/v1/analytics/process.rs@@ -12,7 +12,8 @@ use super::constants::{CAPTURE_V1_EVENT_ADJUSTMENTS_APPLIED, CAPTURE_V1_MAX_EVENT_NAME_LENGTH,CAPTURE_V1_OVERFLOW_ROUTED, CAPTURE_V1_PARSED_EVENTS, CAPTURE_V1_PROCESSING_DURATION_SECONDS,CAPTURE_V1_RATE_LIMITER, DETAIL_EVENT_RESTRICTION_DROP, DETAIL_INVALID_OPTIONS,- DETAIL_PERSON_PROCESSING_DISABLED, FUTURE_EVENT_HOURS_CUTOFF_MS, ILLEGAL_DISTINCT_IDS,+ DETAIL_NON_HISTORICAL_DROP, DETAIL_PERSON_PROCESSING_DISABLED, FUTURE_EVENT_HOURS_CUTOFF_MS,+ ILLEGAL_DISTINCT_IDS,};use super::response::BatchResponse;use super::types::{Batch, Event, EventResult, Options, WrappedEvent};@@ -82,6 +83,26 @@ pub async fn process_batch(// the all-dropped early return so those batches are covered too.emit_validation_drop_warnings(state, context, &events);+ // Import mode ingests only historical backfills: drop any batch not flagged+ // `historical_migration` (a batch-level flag) by marking every event Drop and+ // returning 200 (accept-and-discard) so the batch-import-worker doesn't retry.+ if state.capture_mode.requires_historical_migration() && !context.historical_migration {+ for ev in events.iter_mut() {+ ev.result = EventResult::Drop;+ ev.destination = Destination::Drop;+ ev.details = Some(DETAIL_NON_HISTORICAL_DROP);+ }+ metrics::counter!(CAPTURE_V1_EVENTS_DROPPED, "reason" => "non_historical_import")+ .increment(events.len() as u64);+ crate::ctx_log!(+ Level::WARN,+ context,+ dropped_events = events.len(),+ "import mode dropped non-historical batch"+ );+ return Ok(BatchResponse::build(context, &events));+ }+// Nothing left to process — return 200 with per-event drops.if events.iter().all(|ev| ev.result != EventResult::Ok) {return Ok(BatchResponse::build(context, &events));@@ -122,8 +143,26 @@ pub async fn process_batch();}- if let Some(ref limiter) = state.global_rate_limiter_token_distinctid {- apply_token_distinct_id_limits(limiter, context, &mut events).await;+ // Import mode opts out of the global rate limiter entirely — historical+ // backfills must never be throttled — so it's skipped even if one were wired.+ //+ // DIVERGENCE from legacy (`events::analytics`), intentional and out of scope+ // to reconcile here — a future routing refactor must not assume parity:+ // 1. Ordering: v1 runs this GRL step AFTER burst overflow stamping (above);+ // legacy runs its GRL BEFORE overflow stamping. Both set overflow on+ // AnalyticsMain/Destination::Overflow only, so the end state matches,+ // but the pass order differs.+ // 2. v1 skips events with `force_disable_person_processing` already set+ // before consulting the limiter (see apply_token_distinct_id_limits);+ // legacy does not skip.+ // 3. Lane assignment is assign-then-reroute in v1 versus a single+ // `DataType::from_event_name` match in legacy.+ // Import is unaffected by all three: the GRL never runs (guard below) and no+ // overflowable lane is reachable, so behavior is identical across paths.+ if state.capture_mode.applies_global_rate_limit() {+ if let Some(ref limiter) = state.global_rate_limiter_token_distinctid {+ apply_token_distinct_id_limits(limiter, context, &mut events).await;+ }}histogram!(@@ -3558,6 +3597,186 @@ mod tests {}}+ // =========================================================================+ // Import-mode process_batch tests — historical-only ingestion + GRL bypass+ // =========================================================================++ /// A `valid_batch` with the historical_migration flag set — the only kind+ /// of batch Import mode accepts.+ fn historical_batch(events: Vec<Event>) -> Batch {+ Batch {+ historical_migration: true,+ ..valid_batch(events)+ }+ }++ #[tokio::test]+ async fn import_mode_drops_non_historical_batch_and_publishes_nothing() {+ // Import mode exists to ingest backfills only: a batch without+ // historical_migration must be fully dropped (200, per-event Drop) and+ // never published — otherwise live traffic could sneak in via the+ // import deployment.+ let ts = TestStateBuilder::new()+ .with_capture_mode(crate::config::CaptureMode::Import)+ .build();+ let mut ctx = test_utils::test_analytics_context();+ let batch = valid_batch(vec![valid_event(), valid_event()]);++ let resp = process_batch(&ts.state, &mut ctx, batch).await.unwrap();++ assert_eq!(resp.entries().len(), 2);+ for (_, entry) in resp.entries() {+ assert_eq!(entry.result, EventResult::Drop);+ assert_eq!(entry.details, Some(DETAIL_NON_HISTORICAL_DROP));+ }+ assert!(!resp.has_retry, "dropped batch must not signal retry");+ ts.mock_producer+ .with_records(|records| assert!(records.is_empty(), "nothing may be published"));+ }++ #[tokio::test]+ async fn import_mode_publishes_historical_batch() {+ // The happy path: a properly flagged historical batch flows through+ // Import mode exactly like Events mode and reaches the sink.+ let ts = TestStateBuilder::new()+ .with_capture_mode(crate::config::CaptureMode::Import)+ .build();+ let mut ctx = test_utils::test_analytics_context();+ let batch = historical_batch(vec![valid_event(), valid_event()]);++ let resp = process_batch(&ts.state, &mut ctx, batch).await.unwrap();++ assert_eq!(resp.entries().len(), 2);+ for (_, entry) in resp.entries() {+ assert_eq!(entry.result, EventResult::Ok);+ }+ ts.mock_producer.with_records(|records| {+ assert_eq!(records.len(), 2, "both historical events must publish");+ });+ }++ #[tokio::test]+ async fn import_mode_skips_global_rate_limiter() {+ // Import mode must never apply the global rate limiter, even when one is+ // wired and the (token, distinct_id) is over its limit. If the limiter+ // ran, the event would be flagged person_processing_disabled; here it+ // must stay untouched. valid_event()'s distinct_id is "user-42".+ let limiter = std::sync::Arc::new(mock_limiter(vec!["phc_test_token:user-42"]));+ let ts = TestStateBuilder::new()+ .with_capture_mode(crate::config::CaptureMode::Import)+ .with_global_rate_limiter(limiter)+ .build();+ let mut ctx = test_utils::test_analytics_context();+ let batch = historical_batch(vec![valid_event()]);++ let resp = process_batch(&ts.state, &mut ctx, batch).await.unwrap();++ let (_, entry) = &resp.entries()[0];+ assert_eq!(entry.result, EventResult::Ok);+ assert_eq!(+ entry.details, None,+ "GRL must be skipped in Import mode — no person_processing_disabled flag"+ );+ }++ #[tokio::test]+ async fn import_mode_historical_batch_never_overflows() {+ // Import's no-overflow guarantee on the v1 path. With AI routing off (the+ // deployment config), every event in a historical batch is rerouted to+ // AnalyticsHistorical before overflow stamping, which only touches+ // AnalyticsMain/AiEvents. Even with the burst overflow limiter armed at+ // burst=1 and all three events sharing one token:distinct_id — which would+ // overflow the 2nd and 3rd in Events mode — nothing lands on+ // events_overflow or the AI lanes.+ let ts = TestStateBuilder::new()+ .with_capture_mode(crate::config::CaptureMode::Import)+ .with_overflow_limiter(1, 1)+ .build();+ let mut ctx = test_utils::test_analytics_context();+ let batch = historical_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| {+ assert_eq!(records.len(), 3, "all three historical events must publish");+ for r in records {+ assert_eq!(+ r.topic, "events_hist",+ "Import must route every event to the historical topic, got {}",+ r.topic,+ );+ }+ });+ }++ #[rstest::rstest]+ #[case::ai_routing_off(crate::config::AiRouting::Primary, "events_hist")]+ #[case::ai_routing_on(crate::config::AiRouting::Secondary, "ai_events")]+ #[tokio::test]+ async fn import_mode_ai_precedence_follows_routing(+ #[case] ai_routing: crate::config::AiRouting,+ #[case] expected_topic: &str,+ ) {+ // Pins the AI-vs-historical precedence the no-overflow guarantee rests on:+ // a historical batch's $ai_* event stays on the historical lane only while+ // AI routing is off. Arming it (Secondary) diverts the event to the AI+ // lane even in a historical batch, because v1 assigns AiEvents up front and+ // apply_historical_rerouting only reroutes AnalyticsMain. This is exactly+ // why capture-import must keep AI routing off — armed, the AI lane becomes+ // reachable and overflowable again.+ let ts = TestStateBuilder::new()+ .with_capture_mode(crate::config::CaptureMode::Import)+ .with_ai_routing(ai_routing)+ .build();+ let mut ctx = test_utils::test_analytics_context();+ let batch = historical_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);+ assert_eq!(records[0].topic, expected_topic);+ });+ }++ #[tokio::test]+ async fn events_mode_applies_global_rate_limiter() {+ // Control for the Import GRL-bypass test: the same over-limit key in the+ // default Events mode flags the event, proving the limiter is genuinely+ // hot and the Import bypass above is meaningful.+ let limiter = std::sync::Arc::new(mock_limiter(vec!["phc_test_token:user-42"]));+ let ts = TestStateBuilder::new()+ .with_global_rate_limiter(limiter)+ .build();+ let mut ctx = test_utils::test_analytics_context();+ let batch = valid_batch(vec![valid_event()]);++ let resp = process_batch(&ts.state, &mut ctx, batch).await.unwrap();++ // A limited AnalyticsMain event is flagged and rerouted to overflow,+ // which lands as a Warning with the person_processing_disabled detail.+ let (_, entry) = &resp.entries()[0];+ assert_eq!(entry.result, EventResult::Warning);+ assert_eq!(+ entry.details,+ Some(DETAIL_PERSON_PROCESSING_DISABLED),+ "Events mode must apply the GRL and flag the hot key"+ );+ }+// =========================================================================// Ingestion warning emission — process_batch with a CollectingEmitter// =========================================================================diff --git a/rust/capture/src/v1/test_utils.rs b/rust/capture/src/v1/test_utils.rsindex 36b0988c940e..218366c8b538 100644--- a/rust/capture/src/v1/test_utils.rs+++ b/rust/capture/src/v1/test_utils.rs@@ -686,6 +686,7 @@ pub struct TestStateBuilder {ai_gateway_signing_secret: Option<String>,ai_routing: crate::config::AiRouting,ingestion_warning_emitter: Option<Arc<dyn common_ingestion_warnings::WarningEmitter>>,+ capture_mode: CaptureMode,}impl Default for TestStateBuilder {@@ -707,6 +708,7 @@ impl TestStateBuilder {ai_gateway_signing_secret: None,ai_routing: crate::config::AiRouting::Primary,ingestion_warning_emitter: None,+ capture_mode: CaptureMode::Events,}}@@ -781,6 +783,12 @@ impl TestStateBuilder {self}+ /// Set the deployment capture mode (defaults to `Events`).+ pub fn with_capture_mode(mut self, mode: CaptureMode) -> Self {+ self.capture_mode = mode;+ self+ }+pub fn build(self) -> TestState {let mut manager = lifecycle::Manager::builder("test_state").with_trap_signals(false)@@ -894,6 +902,7 @@ impl TestStateBuilder {ai_routing: self.ai_routing,ai_events_overflow_enabled,ingestion_warning_emitter: self.ingestion_warning_emitter,+ capture_mode: self.capture_mode,};TestState {diff --git a/rust/capture/tests/common/integration_utils.rs b/rust/capture/tests/common/integration_utils.rsindex 72fabffca9cf..abb6d91aa952 100644--- a/rust/capture/tests/common/integration_utils.rs+++ b/rust/capture/tests/common/integration_utils.rs@@ -1059,17 +1059,27 @@ pub fn test_lifecycle_handlers() -> (}fn setup_capture_router(unit: &TestCase) -> (Router, MemorySink) {+ build_router_for_mode_at(unit.mode, unit.fixed_time)+}++// Builds a capture router for a given mode with test defaults, so route-registration+// tests can assert which paths a mode serves without constructing a full TestCase.+pub fn build_router_for_mode(mode: CaptureMode) -> Router {+ build_router_for_mode_at(mode, DEFAULT_TEST_TIME).0+}++fn build_router_for_mode_at(mode: CaptureMode, fixed_time: &str) -> (Router, MemorySink) {let (readiness, liveness, _monitor) = test_lifecycle_handlers();let sink = MemorySink::default();let timesource = FixedTime {- time: DateTime::parse_from_rfc3339(unit.fixed_time)+ time: DateTime::parse_from_rfc3339(fixed_time).expect("Invalid fixed time format in test case").with_timezone(&Utc),};let redis = Arc::new(MockRedisClient::new());let mut cfg = DEFAULT_CONFIG.clone();- cfg.capture_mode = unit.mode;+ cfg.capture_mode = mode;let quota_limiter =CaptureQuotaLimiter::new(&cfg, redis.clone(), Duration::from_secs(60 * 60 * 24 * 7));@@ -1092,7 +1102,7 @@ fn setup_capture_router(unit: &TestCase) -> (Router, MemorySink) {TokenDropper::default(),None, // event_restriction_servicefalse,- unit.mode,+ mode,String::from("capture"),None,25 * 1024 * 1024,diff --git a/rust/capture/tests/integration_analytics_ai_routing.rs b/rust/capture/tests/integration_analytics_ai_routing.rsindex 51ab7dbb5f64..6d0f3fb027bf 100644--- a/rust/capture/tests/integration_analytics_ai_routing.rs+++ b/rust/capture/tests/integration_analytics_ai_routing.rs@@ -79,6 +79,22 @@ fn setup_analytics_router(ai_events_overflow_enabled: bool,overflow_limiter: Option<Arc<OverflowLimiter>>,ai_events_overflow_limiter: Option<Arc<OverflowLimiter>>,+) -> (Router, CapturingSink) {+ setup_router_for_mode(+ CaptureMode::Events,+ ai_routing,+ ai_events_overflow_enabled,+ overflow_limiter,+ ai_events_overflow_limiter,+ )+}++fn setup_router_for_mode(+ capture_mode: CaptureMode,+ 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();@@ -92,7 +108,7 @@ fn setup_analytics_router(let redis = Arc::new(MockRedisClient::new());let mut cfg = DEFAULT_CONFIG.clone();- cfg.capture_mode = CaptureMode::Events;+ cfg.capture_mode = capture_mode;let quota_limiter =CaptureQuotaLimiter::new(&cfg, redis.clone(), Duration::from_secs(60 * 60 * 24 * 7));@@ -108,7 +124,7 @@ fn setup_analytics_router(TokenDropper::default(),None, // event_restriction_servicefalse,- CaptureMode::Events,+ capture_mode,String::from("capture-analytics"),None,25 * 1024 * 1024,@@ -155,6 +171,28 @@ fn mixed_batch_payload() -> String {.to_string()}+// The same mixed batch flagged as a historical migration — the only kind of+// batch Import mode accepts.+fn historical_mixed_batch_payload() -> String {+ json!({+ "api_key": TOKEN,+ "historical_migration": true,+ "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")@@ -316,3 +354,47 @@ async fn ai_lane_overflow_isolated_from_analytics_limiter() {Some(OverflowReason::ForceLimited));}++/// Import mode's no-overflow guarantee, end-to-end on the legacy path. With the+/// deployment's real config — AI routing off — every event in a historical batch+/// lands on `AnalyticsHistorical`, even with the overflow limiter force-keyed on+/// the batch's `token:distinct_id`. Nothing reaches `AnalyticsMain` or `AiEvents`+/// (the only overflowing lanes), so nothing can be stamped for overflow, and the+/// GRL never runs. The invariant is emergent (historical_migration forces the+/// lane, AI routing off keeps AI events out of the AI lane), so it needs pinning:+/// arming AI routing here would divert `$ai_*` and break it.+#[tokio::test]+async fn import_mode_historical_batch_never_overflows() {+ let (router, sink) = setup_router_for_mode(+ CaptureMode::Import,+ AiRouting::Primary, // matches capture-import: AI routing off+ false,+ Some(force_keyed_limiter()),+ None,+ );+ let client = TestClient::new(router);++ post_batch(&client, historical_mixed_batch_payload()).await;++ let events = sink.get_events().await;+ assert_eq!(+ events.len(),+ 2,+ "both historical events must reach the sink"+ );++ for event in &events {+ assert_eq!(+ event.metadata.data_type,+ DataType::AnalyticsHistorical,+ "Import mode must route every event to the historical lane, got {:?} for {}",+ event.metadata.data_type,+ event.metadata.event_name,+ );+ assert_eq!(+ event.metadata.overflow_reason, None,+ "the historical lane must never overflow, even with the limiter force-keyed ({})",+ event.metadata.event_name,+ );+ }+}diff --git a/rust/capture/tests/integration_import_routes.rs b/rust/capture/tests/integration_import_routes.rsnew file mode 100644index 000000000000..96a9c5d7cf95--- /dev/null+++ b/rust/capture/tests/integration_import_routes.rs@@ -0,0 +1,59 @@+#[path = "common/integration_utils.rs"]+mod integration_utils;+use integration_utils::build_router_for_mode;++use axum::http::StatusCode;+use axum_test_helper::TestClient;+use capture::config::CaptureMode;++// Import mode must not register the AI or OTEL handlers: they build their own+// ProcessingContext with historical_migration: false, so they would bypass both+// Import gates (historical-only drop and GRL) and return a false 200 for traffic+// this deployment silently discards. Events mode keeps them.+#[tokio::test]+async fn test_import_mode_does_not_register_ai_or_otel_routes() {+ let client = TestClient::new(build_router_for_mode(CaptureMode::Import));++ for path in ["/i/v0/ai", "/i/v0/ai/", "/i/v0/ai/otel", "/i/v0/ai/otel/"] {+ let resp = client.post(path).body(vec![]).send().await;+ assert_eq!(+ StatusCode::NOT_FOUND,+ resp.status(),+ "Import mode must not register {path}, expected 404",+ );+ }+}++// The gated batch/event paths stay reachable in Import mode. /i/v0/ai/batch lives+// on batch_router (not ai_router) and dispatches to the gated v0_endpoint::event,+// so it survives the split. "Not 404" is the assertion: an empty body yields a 4xx+// from the handler, which still proves the route is registered.+#[tokio::test]+async fn test_import_mode_serves_gated_event_routes() {+ let client = TestClient::new(build_router_for_mode(CaptureMode::Import));++ for path in ["/i/v0/e", "/batch", "/i/v0/ai/batch"] {+ let resp = client.post(path).body(vec![]).send().await;+ assert_ne!(+ StatusCode::NOT_FOUND,+ resp.status(),+ "Import mode must serve {path}, got 404",+ );+ }+}++// Guard the contrast: Events mode does register the AI/OTEL routes, so the split+// above is the only thing withholding them from Import.+#[tokio::test]+async fn test_events_mode_registers_ai_and_otel_routes() {+ let client = TestClient::new(build_router_for_mode(CaptureMode::Events));++ for path in ["/i/v0/ai", "/i/v0/ai/otel"] {+ let resp = client.post(path).body(vec![]).send().await;+ assert_ne!(+ StatusCode::NOT_FOUND,+ resp.status(),+ "Events mode must register {path}, got 404",+ );+ }+}