: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): route ai events to a fixed sink on analytics deployments (#78260)
Paweł Ledwońe88c2c99fddf
diff --git a/rust/capture/OUTPUTS_REFACTOR_PLAN.md b/rust/capture/OUTPUTS_REFACTOR_PLAN.mdindex 92b8002c4e2e..3906d09f717d 100644--- a/rust/capture/OUTPUTS_REFACTOR_PLAN.md+++ b/rust/capture/OUTPUTS_REFACTOR_PLAN.md@@ -47,7 +47,7 @@ Steps 1–3 land together with this doc: the routing golden oracle, the pure `ro### Invariants-- Metric names and labels stay stable: `capture_events_rerouted_*`, `capture_primary_sink_health`, `capture_fallback_sink_failovers_total`, `capture_split_sink_selected`, `capture_failover_breaker_*`, `capture_event_batch_size`. Renames are out of scope for every step.+- Metric names and labels stay stable: `capture_events_rerouted_*`, `capture_primary_sink_health`, `capture_fallback_sink_failovers_total`, `capture_failover_breaker_*`, `capture_event_batch_size`. Renames are out of scope for every step.- Wire parity is proven by the Step-1 goldens and existing endpoint/integration tests passing **unmodified**, except where a step explicitly says otherwise.- Never mix a mechanical move with a behavior change in one commit.- Every step ships green (`cargo test -p capture`, clippy `-D warnings`, fmt) and rolls back by plain revert.@@ -101,7 +101,7 @@ Step 7 absorbs it into the `OutputTable`; the mode-scoped demand is folded in at#### Step 6 · Narrow the Kafka sink to backend mechanism- **Goal.** New `sinks/sink.rs`: `PreparedPayload { uuid, record: ProduceRecord }` (serialized, addressed) is the sink input; `trait Sink { publish(Vec<PreparedPayload>) -> Vec<SinkResult>; flush() }` — no prepare on the trait, no metadata access — plus `Outcome` and `fold_results` (first failure wins). Kafka: `prepare_batch` (serial <8 / scatter-gather ≥8, fail-fast) extracted from `send_batch` as an inherent method the outputs layer will call; `impl Sink` = serial enqueue + fail-fast ack drain, reporting batch-uniform per-event results (the per-event surface refines only with the response model). `Event::send_batch` becomes the bridge: prep → publish → fold. Kafka only — s3/print/noop gain mechanism impls with the outputs layer, which is what needs them.-- **Sequencing decision.** `FallbackSink` and `SplitKafkaSink` are never ported onto the mechanism trait: the outputs layer owns multi-target policies (single | failover | split) from its first commit, built from the same config, and the Event-era composites are deleted when their last caller migrates.+- **Sequencing decision.** `FallbackSink` is never ported onto the mechanism trait: the outputs layer owns multi-target policies (single | failover) from its first commit, built from the same config, and the Event-era composite is deleted when its last caller migrates. `SplitKafkaSink` is already gone — deleted with the retired AI secondary-cluster routing — so split survives only as a policy shape the outputs layer grows back when a cluster migration needs it.- **Files.** `rust/capture/src/sinks/sink.rs` (new), `rust/capture/src/sinks/kafka.rs`, `rust/capture/src/sinks/mod.rs`.- **Parity proof.** Step-1 goldens + `send_batch` three-phase suite unmodified (they now drive prep → publish → fold — the exact production path).- **Risk / rollback.** Medium-high — core mechanism. Revert.@@ -110,12 +110,12 @@ Step 7 absorbs it into the `OutputTable`; the mode-scoped demand is folded in at#### Step 7 · Outputs layer with policies; composites retired- **Goal.** New `outputs` module — the produce surface, with multi-target policy ownership from day one:- - `Output`: a single backend, or a policy composing two *outputs* — `failover` (health-gated Kafka→S3: skip primary while the advisory handle is unhealthy, re-publish the batch on a retriable failure, fatal never fails over) and `split` (token-routed AI secondary). Targets are outputs themselves, so policies compose the way the old composites did (split over a failover pair). Policies operate on *events*, before prep — each target resolves topics and serializes for itself, exactly like the old per-sink `send_batch` paths, so parity is structural.+ - `Output`: a single backend, or a policy composing two *outputs* — today `failover` (health-gated Kafka→S3: skip primary while the advisory handle is unhealthy, re-publish the batch on a retriable failure, fatal never fails over). Targets are outputs themselves, so a future policy (a split for the next cluster migration) composes over pairs the way the old composites did. Policies operate on *events*, before prep — each target resolves topics and serializes for itself, exactly like the old per-sink `send_batch` paths, so parity is structural.- Leaves run the dance internally via the `pub(crate)` `Prepare` trait (prep → publish → fold); no caller ever sees a two-phase protocol.- `OutputTable`: the `(pipeline, lane)` → output handle the state holds; degenerate today (one deployment-wide output; per-lane topics resolve in prep via the `OutputRegistry`).- - `setup::create_output` builds the policy tree from the same config; **`FallbackSink` and `SplitKafkaSink` are deleted**, their tests re-expressed on `Output` with assertions preserved (+ a new fatal-no-failover case).+ - `setup::create_output` builds the policy tree from the same config; **`FallbackSink` is deleted**, its tests re-expressed on `Output` with assertions preserved (+ a new fatal-no-failover case).- Call sites are untouched: the table serves them through a transitional `Event` facade (which records `capture_event_batch_size`, where the old sink impls recorded it). Migration is Step 8.-- **Files.** `rust/capture/src/outputs.rs` (new); `rust/capture/src/setup.rs`; `rust/capture/src/sinks/{mod,s3,print,noop,test_sink}.rs` (mechanism + `Prepare` impls); `fallback.rs`/`split.rs` deleted.+- **Files.** `rust/capture/src/outputs.rs` (new); `rust/capture/src/setup.rs`; `rust/capture/src/sinks/{mod,s3,print,noop,test_sink}.rs` (mechanism + `Prepare` impls); `fallback.rs` deleted.- **Parity proof.** Goldens + all integration suites unmodified. Known metrics-only deltas, accepted: the batch-size histogram now records on the fallback-to-S3 path (it silently didn't before), and print/noop single sends record it (they didn't).- **Risk / rollback.** Medium. Revert.- **Size.** L.@@ -199,8 +199,8 @@ Goal: v1 endpoints publish through `dyn Outputs` like every other ingress, so fa### AI pipeline and Import mode-- **AI pipeline membership is stamp-based, not name-based.** The per-batch-token `AiRouting` divert decision (`CAPTURE_ANALYTICS_AI_EVENTS_MODE` + allowlist/percentage) stamps `DataType::AiEvents` during processing, mirroring v1's `Destination::AiEvents`; `Pipeline::from_metadata` maps the stamp. An undiverted `$ai_*` event is a plain analytics event on the analytics lanes — the multipart/OTEL AI ingress stamps `AnalyticsMain` and publishes to the analytics rows. `AI_EVENT_PREFIX` remains only for the quota predicate and the stamping decision.-- **The AI lanes own dedicated topics.** `TopicTable` grows optional `ai_events` / `ai_events_overflow` rows (`CAPTURE_ANALYTICS_AI_EVENTS_TOPIC` / `..._OVERFLOW_TOPIC`); there is no `AiLane::Historical` — the divert decision wins over historical, matching v1. The AI overflow valve (overflow topic set) rides `PrepSpec` into `resolve`, so an unarmed deployment never routes the AI lane to overflow, force_overflow included.+- **AI pipeline membership is stamp-based, not name-based.** The divert decision is a capture-mode property: on modes that route AI events (`CaptureMode::routes_ai_events` — Events and Import), `$ai_*` events stamp `DataType::AiEvents` during processing, mirroring v1's `Destination::AiEvents`; `Pipeline::from_metadata` maps the stamp. There is no per-batch routing config — the rollout-era `AiRouting` mode/allowlist/percentage machinery is retired. A `$ai_*` event on a non-routing mode is a plain analytics event on the analytics lanes, and the multipart/OTEL AI ingress stamps `AnalyticsMain` and publishes to the analytics rows. `AI_EVENT_PREFIX` remains only for the quota predicate and the stamping decision.+- **The AI lanes own dedicated topics.** `TopicTable` grows an `ai_events` row (`CAPTURE_ANALYTICS_AI_EVENTS_TOPIC`, required with default `events_plugin_ingestion_ai`) and an optional `ai_events_overflow` row (`..._OVERFLOW_TOPIC`); there is no `AiLane::Historical` — the divert decision wins over historical, matching v1. The AI overflow valve (overflow topic set) rides `PrepSpec` into `resolve`, so an unarmed deployment never routes the AI lane to overflow, force_overflow included.- **Import mode** is an analytics-family deployment on `router::router`; it mounts `/i/v0/ai/batch` (gated batch handler) but not the ai/otel handlers, and shares the Events topic requirements.## Repartitioning coordinator (design note)@@ -209,7 +209,7 @@ Not built in this PR; this note records where it plugs in so nothing landed here**Logical shards, decided before the sinks.** The coordinator owns a stable shard function: `shard = hash(key) % N` over the same partition key the sink would hash, with coordinator-owned `N` (not either cluster's partition count). The shard is stamped at prep time — `AddressedPayload` grows `shard: Option<u32>`, `None` meaning "let the producer partition as today". Stamping at prep keeps the decision above the sinks: both clusters of a failover pair see the same shard on the same payload, so a switchover decision is consistent across targets by construction.-**A `ShardRouted` output policy.** Routing lives in the outputs layer as a policy node holding two child outputs (old cluster, new cluster) and a swappable assignment table `shard → Old | New` (an `ArcSwap`, updated by the coordinator's control plane the same way the failover breaker's control plane seam works). Batch publish splits by assignment and forwards — scatter-gather like `Split`, no serialization changes (both clusters share the prep/serialization contract, as the AI-secondary split already proves).+**A `ShardRouted` output policy.** Routing lives in the outputs layer as a policy node holding two child outputs (old cluster, new cluster) and a swappable assignment table `shard → Old | New` (an `ArcSwap`, updated by the coordinator's control plane the same way the failover breaker's control plane seam works). Batch publish splits by assignment and forwards — scatter-gather like the old `Split` composite, no serialization changes (both clusters share the prep/serialization contract, as the retired AI-secondary split proved).**Explicit partition pass-through in the sink.** `ProduceRecord` grows `partition: Option<i32>`; the Kafka sink maps `shard` to a concrete partition of its own topic (its table realizes the namespace; a shard→ partition map is the same kind of sink-side data as topic names) and sets it on the record. `None` keeps today's key hashing. The sink still makes no routing decisions — it realizes an address (topic) and a shard (partition) in its own namespace.@@ -238,7 +238,7 @@ The hold window is per-shard and bounded by one producer flush — that is the "When all steps land, the five strata hold:- **Pipelines and lanes.** `pipeline::resolve` is the one lane decision (dlq > custom > historical > overflow > main), pure over `ProcessedEventMetadata`; `Pipeline`/`Lane` are the event's address.-- **Outputs are the produce surface.** Every pipeline publishes through the `OutputTable`; the `Output` policy tree (single | failover | split) owns all multi-target behavior, composing the way the old sink composites did. The v0 `Event` trait, `FallbackSink`, and `SplitKafkaSink` are gone.+- **Outputs are the produce surface.** Every pipeline publishes through the `OutputTable`; the `Output` policy tree (single | failover) owns all multi-target behavior, composing the way the old sink composites did. The v0 `Event` trait and `FallbackSink` are gone; `SplitKafkaSink` already is, deleted with the retired AI secondary-cluster routing.- **Serialization is a seam.** Format × envelope per destination, with content headers carrying encoding coexistence (the lz4 replay design, generalized); a protobuf cutover is an output-level config change.- **Sinks are mechanism, and own their namespace.** Payloads carry the abstract `Address`; each sink realizes it in its own namespace at publish time (Kafka: its per-cluster topic table — the swappable seam a repartitioning coordinator plugs into; S3: the buffer path; print/noop: trivially). Sinks make no routing decisions; a failover pair can share one prepared batch because payloads are target-agnostic. Serialization stays output-level (a consumer contract, shared across targets).- **Breaker failover is dark-launched** behind `CAPTURE_FAILOVER_ENABLED` as the failover output's autonomous mode.@@ -267,7 +267,7 @@ When all steps land, the five strata hold:| 4 · Serialization layer | done | `refactor(capture): serialization layer behind one seam` || 5 · `Pipeline` + `Lane`; lane resolution | pending | `refactor(capture): pipeline and lane address; lane decision moves to the pipeline layer` || 6 · Kafka sink → backend mechanism | pending | `refactor(capture): narrow the kafka sink to backend mechanism over prepared payloads` |-| 7 · Outputs layer with policies; composites retired | pending | `feat(capture): outputs layer owns failover and split policies` |+| 7 · Outputs layer with policies; composites retired | pending | `feat(capture): outputs layer owns the failover policy` || 8a · Call sites on the table | pending | `refactor(capture): call sites publish through outputs` || 8b · `Event` retired | pending | `refactor(capture): retire v0 Event trait` || 9 · Mode-scoped completeness | pending | `refactor(capture): mode-scoped output registry completeness` |diff --git a/rust/capture/src/config.rs b/rust/capture/src/config.rsindex 3edb28def8aa..43d5b360cfac 100644--- a/rust/capture/src/config.rs+++ b/rust/capture/src/config.rs@@ -1,9 +1,7 @@-use std::collections::HashSet;use std::{net::SocketAddr, num::NonZeroU32};use common_continuous_profiling::ContinuousProfilingConfig;use envconfig::Envconfig;-use sha2::{Digest, Sha256};use tracing::Level;#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)]@@ -48,6 +46,19 @@ impl CaptureMode {pub fn requires_historical_migration(&self) -> bool {matches!(self, CaptureMode::Import)}++ /// Whether the analytics pipelines divert `$ai_*` events to the dedicated+ /// AI topic (`CAPTURE_ANALYTICS_AI_EVENTS_TOPIC`). `Events` and `Import` do — the AI+ /// lane is the only pipeline with AI processing (cost enrichment, the+ /// ai_events double-write), so historical backfills must divert too or+ /// their `$ai_*` events import incorrectly. `Ai` deployments don't: they+ /// already produce to the AI lane as their main topic. Import deployments+ /// keep their no-overflow guarantee in code: setup refuses to boot import+ /// mode with the AI overflow valve+ /// (`CAPTURE_ANALYTICS_AI_EVENTS_OVERFLOW_TOPIC`) set.+ pub fn routes_ai_events(&self) -> bool {+ matches!(self, CaptureMode::Events | CaptureMode::Import)+ }}impl std::str::FromStr for CaptureMode {@@ -86,79 +97,6 @@ impl std::str::FromStr for EnvelopeCompression {}}-/// Routing mode for AI capture events between the primary cluster and a-/// secondary (e.g. WarpStream) cluster. Only consulted in `CaptureMode::Ai`.-#[derive(Debug, PartialEq, Eq, Clone, Copy, Default)]-pub enum AiSinkMode {- /// All AI events stay on the primary sink (current behavior).- #[default]- Primary,- /// Only tokens listed in `ai_secondary_allowlist_tokens` go to the- /// secondary sink; everything else stays on the primary.- SecondaryAllowlist,- /// Tokens whose deterministic hash bucket falls under the configured- /// percentage go to the secondary sink; everything else stays on the- /// primary.- SecondaryPercentage,- /// All AI events go to the secondary sink.- Secondary,-}--impl std::str::FromStr for AiSinkMode {- type Err = String;-- fn from_str(s: &str) -> Result<Self, Self::Err> {- match s.trim().to_lowercase().as_ref() {- "primary" => Ok(AiSinkMode::Primary),- "secondary_allowlist" | "secondary-allowlist" => Ok(AiSinkMode::SecondaryAllowlist),- "secondary_percentage" | "secondary-percentage" => Ok(AiSinkMode::SecondaryPercentage),- "secondary" => Ok(AiSinkMode::Secondary),- _ => Err(format!("Unknown AiSinkMode: {s}")),- }- }-}--/// Resolved AI routing policy: the configured `AiSinkMode` with the token-/// allowlist or percentage it needs attached to the variant that uses it.-/// Built from the raw `ai_sink_mode` + companion config in `setup` and-/// carried by `SplitKafkaSink`, so routing needs nothing but the event's token.-#[derive(Debug, Clone)]-pub enum AiRouting {- Primary,- SecondaryAllowlist(HashSet<String>),- SecondaryPercentage(u8),- Secondary,-}--impl AiRouting {- /// Whether an AI event for `token` should be routed to the secondary sink.- /// `Primary` never does; `Secondary` always does; `SecondaryAllowlist` routes- /// only allowlisted tokens; `SecondaryPercentage` routes tokens whose bucket- /// falls under the percentage.- pub fn routes_to_secondary(&self, token: &str) -> bool {- match self {- AiRouting::Primary => false,- AiRouting::Secondary => true,- AiRouting::SecondaryAllowlist(allowlist) => allowlist.contains(token),- AiRouting::SecondaryPercentage(percentage) => {- token_percentage_bucket(token) < *percentage- }- }- }-}--/// Deterministic 0-99 bucket for a project API token, used by-/// `AiRouting::SecondaryPercentage`. Keying on the token (not the distinct id)-/// keeps a whole team on one side of the split, and SHA-256 keeps the bucket-/// stable across pods, restarts, and deploys — a process-seeded hash would-/// reshuffle which teams sit under a given percentage. Raising the percentage-/// only ever adds teams to the secondary; it never moves routed teams back.-fn token_percentage_bucket(token: &str) -> u8 {- let digest = Sha256::digest(token.as_bytes());- let n = u64::from_be_bytes(digest[..8].try_into().expect("SHA-256 digest is 32 bytes"));- (n % 100) as u8-}-#[derive(Envconfig, Clone)]pub struct Config {#[envconfig(default = "false")]@@ -348,49 +286,6 @@ pub struct Config {// (all $ai_gateway* props are stripped as untrusted).pub ai_gateway_signing_secret: Option<String>,- // --- AI secondary sink (e.g. WarpStream cluster) routing ---- /// `primary` keeps all AI events on the primary sink; `secondary_allowlist`- /// sends only `ai_secondary_allowlist_tokens` to the secondary; `secondary`- /// sends every AI event to the secondary. `secondary_percentage` is not- /// supported here (it exists for `capture_analytics_ai_events_mode`).- /// Only consulted in `CaptureMode::Ai`.- #[envconfig(default = "primary")]- pub ai_sink_mode: AiSinkMode,-- /// Comma-separated tokens routed to the secondary AI sink when- /// `ai_sink_mode = secondary_allowlist`.- pub ai_secondary_allowlist_tokens: Option<String>,-- /// Secondary AI Kafka cluster connection. When `ai_sink_mode` is not- /// `primary`, `ai_secondary_kafka_hosts` and `ai_secondary_kafka_topic` are- /// required; the secondary producer inherits all other tuning from `kafka`.- pub ai_secondary_kafka_hosts: Option<String>,- pub ai_secondary_kafka_topic: Option<String>,- #[envconfig(default = "false")]- pub ai_secondary_kafka_tls: bool,- #[envconfig(default = "")]- pub ai_secondary_kafka_client_id: String,-- // --- Dedicated $ai_* topic routing on analytics deployments ---- /// Routing mode for `$ai_*` events into the dedicated AI topic- /// (`kafka.capture_analytics_ai_events_topic`, i.e. `CAPTURE_ANALYTICS_AI_EVENTS_TOPIC`): `primary` (default)- /// diverts nothing, `secondary` diverts all `$ai_*` events,- /// `secondary_allowlist` diverts only tokens listed in- /// `capture_analytics_ai_events_allowlist_tokens`, and `secondary_percentage`- /// diverts the `capture_analytics_ai_events_percentage` share of teams (by- /// token hash). The topic is required whenever the mode is not `primary`.- #[envconfig(default = "primary")]- pub capture_analytics_ai_events_mode: AiSinkMode,-- /// Comma-separated project API tokens whose `$ai_*` events are diverted to- /// `capture_analytics_ai_events_topic` when `capture_analytics_ai_events_mode` is `secondary_allowlist`.- pub capture_analytics_ai_events_allowlist_tokens: Option<String>,-- /// Percent of teams (0-100, by deterministic token hash) whose `$ai_*`- /// events are diverted to `capture_analytics_ai_events_topic`. Required- /// when `capture_analytics_ai_events_mode` is `secondary_percentage`.- pub capture_analytics_ai_events_percentage: Option<u8>,-// HTTP/1 header read timeout in milliseconds - closes connections that don't// send complete headers within this duration (slow loris protection).// Set env var to enable; unset to disable.@@ -524,19 +419,19 @@ pub struct KafkaConfig {#[envconfig(default = "events_plugin_ingestion_dlq")]pub kafka_dlq_topic: String,/// Dedicated Kafka topic for `$ai_*` events (env: `CAPTURE_ANALYTICS_AI_EVENTS_TOPIC`).- /// Unlike the `ai_secondary_*` family on `Config` (which picks a secondary- /// CLUSTER on `CaptureMode::Ai` deployments), this picks a TOPIC on the- /// same sink: per `Config::capture_analytics_ai_events_mode`, both the v0 pipeline- /// (via `DataType::AiEvents`) and the v1 pipeline (via- /// `Destination::AiEvents`) divert `$ai_*` events here instead of the- /// analytics main topic. Setup also injects it into every v1 sink config.- pub capture_analytics_ai_events_topic: Option<String>,+ /// On deployments whose capture mode routes AI events+ /// (`CaptureMode::routes_ai_events`), both the v0 pipeline (via+ /// `DataType::AiEvents`) and the v1 pipeline (via `Destination::AiEvents`)+ /// divert `$ai_*` events here instead of the analytics main topic. Setup+ /// also injects it into every v1 sink config.+ #[envconfig(default = "events_plugin_ingestion_ai")]+ pub capture_analytics_ai_events_topic: String,/// Optional overflow topic for the AI lane (env: `CAPTURE_ANALYTICS_AI_EVENTS_OVERFLOW_TOPIC`)./// Unset means AI events never overflow (the pre-overflow behavior). When/// set, the AI lane participates in the same overflow limiter and/// restriction-driven force_overflow as the analytics main lane, rerouting- /// here instead of the analytics overflow topic. Settable in advance of- /// the AI routing mode, so no startup validation ties it to the mode.+ /// here instead of the analytics overflow topic. Refused at boot in import+ /// mode because imports must never overflow.pub capture_analytics_ai_events_overflow_topic: Option<String>,#[envconfig(default = "false")]pub kafka_tls: bool,@@ -612,7 +507,7 @@ pub struct KafkaConfig {#[cfg(test)]mod tests {- use super::{AiRouting, AiSinkMode, CaptureMode, Config};+ use super::{CaptureMode, Config};use std::collections::HashMap;use std::str::FromStr;@@ -630,48 +525,14 @@ mod tests {fn capture_analytics_ai_events_topic_defaults() {let config: Config =envconfig::Envconfig::init_from_hashmap(&required_config_env()).unwrap();- assert_eq!(config.kafka.capture_analytics_ai_events_topic, None);- assert_eq!(config.capture_analytics_ai_events_mode, AiSinkMode::Primary);- assert_eq!(config.capture_analytics_ai_events_allowlist_tokens, None);- assert_eq!(config.capture_analytics_ai_events_percentage, None);- }-- #[test]- fn capture_analytics_ai_events_percentage_parses() {- let mut env = required_config_env();- env.insert(- "CAPTURE_ANALYTICS_AI_EVENTS_MODE".into(),- "secondary_percentage".into(),+ assert_eq!(+ config.kafka.capture_analytics_ai_events_topic,+ "events_plugin_ingestion_ai"+ );+ assert_eq!(+ config.kafka.capture_analytics_ai_events_overflow_topic,+ None);-- // 150 parses here on purpose: the env layer only types the value, the- // 0-100 range check lives in setup so it can refuse to start.- for (raw, expected) in [("0", 0u8), ("25", 25), ("100", 100), ("150", 150)] {- env.insert("CAPTURE_ANALYTICS_AI_EVENTS_PERCENTAGE".into(), raw.into());- let config: Config = envconfig::Envconfig::init_from_hashmap(&env).unwrap();- assert_eq!(- config.capture_analytics_ai_events_mode,- AiSinkMode::SecondaryPercentage- );- assert_eq!(- config.capture_analytics_ai_events_percentage,- Some(expected),- "raw={raw}"- );- }- }-- #[test]- fn capture_analytics_ai_events_percentage_rejects_malformed_values() {- // Locks the fail-fast contract: the field is a typed u8, so malformed- // env values abort startup. Loosening it (e.g. to a string parsed- // later) would let a broken rollout config through init silently.- for bad in ["", " 25 ", "abc", "-1", "25%", "12.5", "300"] {- let mut env = required_config_env();- env.insert("CAPTURE_ANALYTICS_AI_EVENTS_PERCENTAGE".into(), bad.into());- let result: Result<Config, _> = envconfig::Envconfig::init_from_hashmap(&env);- assert!(result.is_err(), "expected init to fail for {bad:?}");- }}#[test]@@ -681,29 +542,8 @@ mod tests {"CAPTURE_ANALYTICS_AI_EVENTS_TOPIC".into(),"ai_events".into(),);- env.insert(- "CAPTURE_ANALYTICS_AI_EVENTS_MODE".into(),- "secondary_allowlist".into(),- );- env.insert(- "CAPTURE_ANALYTICS_AI_EVENTS_ALLOWLIST_TOKENS".into(),- "tok_a,tok_b".into(),- );let config: Config = envconfig::Envconfig::init_from_hashmap(&env).unwrap();- assert_eq!(- config.kafka.capture_analytics_ai_events_topic.as_deref(),- Some("ai_events")- );- assert_eq!(- config.capture_analytics_ai_events_mode,- AiSinkMode::SecondaryAllowlist- );- assert_eq!(- config- .capture_analytics_ai_events_allowlist_tokens- .as_deref(),- Some("tok_a,tok_b")- );+ assert_eq!(config.kafka.capture_analytics_ai_events_topic, "ai_events");}#[test]@@ -755,104 +595,17 @@ mod tests {}#[test]- fn ai_sink_mode_from_str() {- // Locks the AI_SINK_MODE env contract: accepted spellings (incl. the- // dash/underscore allowlist alias), case-insensitivity, and rejection- // of anything else.- let ok = [- ("primary", AiSinkMode::Primary),- ("PRIMARY", AiSinkMode::Primary),- ("secondary", AiSinkMode::Secondary),- (" Secondary ", AiSinkMode::Secondary),- ("secondary_allowlist", AiSinkMode::SecondaryAllowlist),- ("secondary-allowlist", AiSinkMode::SecondaryAllowlist),- ("Secondary_Allowlist", AiSinkMode::SecondaryAllowlist),- ("secondary_percentage", AiSinkMode::SecondaryPercentage),- ("secondary-percentage", AiSinkMode::SecondaryPercentage),- ("Secondary_Percentage", AiSinkMode::SecondaryPercentage),- ];- for (input, expected) in ok {- assert_eq!(- AiSinkMode::from_str(input).unwrap(),- expected,- "input={input}"- );- }-- for bad in [- "",- "secondaryallowlist",- "secondarypercentage",- "percentage",- "warpstream",- "allowlist",- ] {+ fn capture_mode_ai_routing_policy() {+ // Events and Import divert $ai_* events to the AI topic — only the AI+ // lane has AI processing, so imports must divert too. Ai deployments+ // already produce to the AI lane as their main topic.+ assert!(CaptureMode::Events.routes_ai_events());+ assert!(CaptureMode::Import.routes_ai_events());+ for mode in [CaptureMode::Recordings, CaptureMode::Ai] {assert!(- AiSinkMode::from_str(bad).is_err(),- "expected err for {bad:?}"- );- }- }-- #[test]- fn ai_routing_routes_to_secondary() {- // Locks the routing decision: a flipped arm or the allowlist being- // consulted in the wrong variant would send AI traffic to the wrong- // cluster mid-cutover.- use std::collections::HashSet;- let allowlist: HashSet<String> = ["tok_a".to_string()].into_iter().collect();-- // (routing, token, expected_secondary)- let cases = [- (AiRouting::Primary, "tok_a", false),- (AiRouting::Secondary, "tok_a", true),- (AiRouting::Secondary, "unlisted", true),- (- AiRouting::SecondaryAllowlist(allowlist.clone()),- "tok_a",- true,- ),- (AiRouting::SecondaryAllowlist(allowlist), "unlisted", false),- (- AiRouting::SecondaryAllowlist(HashSet::new()),- "tok_a",- false,- ),- (AiRouting::SecondaryPercentage(0), "tok_a", false),- (AiRouting::SecondaryPercentage(100), "tok_a", true),- ];- for (routing, token, expected) in cases {- assert_eq!(- routing.routes_to_secondary(token),- expected,- "routing={routing:?} token={token}"+ !mode.routes_ai_events(),+ "{mode:?} must not route AI events");}}-- #[test]- fn token_percentage_buckets_are_stable() {- // The bucket values are part of the rollout contract: a hash change- // reshuffles which teams sit under a given percentage mid-rollout,- // flipping already-migrated teams back and forth between destinations.- // These pin the exact SHA-256-derived buckets for fixed tokens.- let buckets = [("tok_a", 27), ("tok_b", 40), ("phc_other", 29)];- for (token, expected) in buckets {- assert_eq!(- super::token_percentage_bucket(token),- expected,- "token={token}"- );- }- }-- #[test]- fn secondary_percentage_routes_exactly_at_bucket_boundary() {- // `bucket < percentage` makes the split monotonic: raising the- // percentage only ever adds teams to the secondary. A flipped- // comparison (or off-by-one) would silently invert who migrates first.- let bucket = super::token_percentage_bucket("tok_a");- assert!(!AiRouting::SecondaryPercentage(bucket).routes_to_secondary("tok_a"));- assert!(AiRouting::SecondaryPercentage(bucket + 1).routes_to_secondary("tok_a"));- }}diff --git a/rust/capture/src/event_restrictions/types.rs b/rust/capture/src/event_restrictions/types.rsindex ae120283ddd2..a4849a00c1ed 100644--- a/rust/capture/src/event_restrictions/types.rs+++ b/rust/capture/src/event_restrictions/types.rs@@ -45,10 +45,10 @@ impl Pipeline {/// Pipelines a given capture deployment produces events to. The events/// 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. `Import` is an- /// events deployment restricted to backfills, so it serves the same three.- /// Other deployments serve their single pipeline.+ /// (`$ai_*` events diverted by `CaptureMode::routes_ai_events`), so its+ /// restriction 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 | CaptureMode::Import => {diff --git a/rust/capture/src/events/analytics.rs b/rust/capture/src/events/analytics.rsindex 5080f336573f..be2d111a9921 100644--- a/rust/capture/src/events/analytics.rs+++ b/rust/capture/src/events/analytics.rs@@ -21,7 +21,6 @@ use limiters::overflow::OverflowLimiter;use crate::{api::CaptureError,- config::AiRouting,debug_or_info,event_restrictions::{EventContext as RestrictionEventContext, EventRestrictionService},events::overflow_stamping::stamp_overflow_reason,@@ -120,7 +119,7 @@ fn create_heatmap_redirect(/// Process a single analytics event from RawEvent to ProcessedEvent.///-/// `route_ai_events` is the per-batch `AiRouting` decision (see+/// `route_ai_events` is the deployment's `CaptureMode::routes_ai_events` (see/// `process_events`); when set, `$ai_*` events classify as/// `DataType::AiEvents` instead of the analytics main/historical lanes.#[instrument(skip_all, fields(event_name, request_id))]@@ -231,8 +230,8 @@ pub fn process_single_event(/// Process a batch of analytics events.////// All routing policy lives here: token dropping, `$ai_*` lane assignment-/// (per the deployment-level [`AiRouting`] policy, resolved into-/// `DataType::AiEvents` at classification time), event restrictions, global+/// (per `CaptureMode::routes_ai_events`, resolved into `DataType::AiEvents`+/// at classification time), event restrictions, global/// rate limiting (per `token:distinct_id`), historical rerouting, and/// per-key overflow rerouting via [`OverflowLimiter`]. Overflow stamping/// goes through the shared [`stamp_overflow_reason`] helper, which the AI@@ -253,7 +252,6 @@ pub async fn process_events(overflow_limiter: Option<Arc<OverflowLimiter>>,ai_events_overflow_limiter: Option<Arc<OverflowLimiter>>,ingestion_warning_emitter: Option<Arc<dyn WarningEmitter>>,- ai_routing: &AiRouting,events: Vec<RawEvent>,context: &ProcessingContext,) -> Result<(), CaptureError> {@@ -274,7 +272,6 @@ pub async fn process_events(overflow_limiter,ai_events_overflow_limiter,ingestion_warning_emitter,- ai_routing,events,context,)@@ -296,7 +293,6 @@ async fn process_events_inner(overflow_limiter: Option<Arc<OverflowLimiter>>,ai_events_overflow_limiter: Option<Arc<OverflowLimiter>>,ingestion_warning_emitter: Option<Arc<dyn WarningEmitter>>,- ai_routing: &AiRouting,events: Vec<RawEvent>,context: &ProcessingContext,) -> Result<(), CaptureError> {@@ -324,11 +320,11 @@ async fn process_events_inner(return Ok(());}- // A request carries a single token, so the `$ai_*` lane decision is per- // batch, mirroring v1's `process_batch`. The flag feeds+ // Whether `$ai_*` events divert to the dedicated AI topic is a deployment+ // property, mirroring v1's `process_batch`. The flag feeds// `DataType::from_event_name` via `process_single_event`; the kafka sink// maps the resulting `DataType::AiEvents` to `CAPTURE_ANALYTICS_AI_EVENTS_TOPIC`.- let route_ai_events = ai_routing.routes_to_secondary(&context.token);+ let route_ai_events = context.capture_mode.routes_ai_events();// Build the processed batch one raw event at a time so we can split a// heatmap-carrying event into a stripped original + a `$$heatmap`@@ -674,6 +670,53 @@ mod tests {}}+ /// Named-field collaborators for `process_events`; tests override only+ /// the ones they exercise and take the rest from `Default`.+ struct PipelineOptions {+ dropper: Arc<TokenDropper>,+ restriction_service: Option<EventRestrictionService>,+ historical_cfg: router::HistoricalConfig,+ global_rate_limiter: Option<Arc<GlobalRateLimiter>>,+ overflow_limiter: Option<Arc<OverflowLimiter>>,+ ai_events_overflow_limiter: Option<Arc<OverflowLimiter>>,+ ingestion_warning_emitter: Option<Arc<dyn WarningEmitter>>,+ }++ impl Default for PipelineOptions {+ fn default() -> Self {+ Self {+ dropper: Arc::new(TokenDropper::default()),+ restriction_service: None,+ historical_cfg: router::HistoricalConfig::new(false, 1),+ global_rate_limiter: None,+ overflow_limiter: None,+ ai_events_overflow_limiter: None,+ ingestion_warning_emitter: None,+ }+ }+ }++ async fn run_pipeline(+ sink: Arc<dyn sinks::Event + Send + Sync>,+ events: Vec<RawEvent>,+ context: &ProcessingContext,+ options: PipelineOptions,+ ) -> Result<(), CaptureError> {+ process_events(+ sink,+ options.dropper,+ options.restriction_service,+ options.historical_cfg,+ options.global_rate_limiter,+ options.overflow_limiter,+ options.ai_events_overflow_limiter,+ options.ingestion_warning_emitter,+ events,+ context,+ )+ .await+ }+#[test]fn test_server_assigned_uuid_encodes_event_timestamp() {// Ingestion clock is in 2023, but the event's own timestamp is back in 2020.@@ -696,8 +739,13 @@ mod tests {token: Some("test_token".to_string()),};- let historical_cfg = router::HistoricalConfig::new(false, 1);- let processed = process_single_event(&event, historical_cfg, false, &context).unwrap();+ let processed = process_single_event(+ &event,+ router::HistoricalConfig::new(false, 1),+ false,+ &context,+ )+ .unwrap();let expected_millis = processed.metadata@@ -732,8 +780,13 @@ mod tests {token: Some("test_token".to_string()),};- let historical_cfg = router::HistoricalConfig::new(false, 1);- let processed = process_single_event(&event, historical_cfg, false, &context).unwrap();+ let processed = process_single_event(+ &event,+ router::HistoricalConfig::new(false, 1),+ false,+ &context,+ )+ .unwrap();// The event keeps its pre-epoch timestamp, but the uuid floors to the epoch rather than wrapping to garbage.assert!(@@ -755,8 +808,12 @@ mod tests {let context = create_test_context(now, None);let event = create_test_event(Some("2023-01-01T11:00:00Z".to_string()), None, None);- let historical_cfg = router::HistoricalConfig::new(false, 1);- let result = process_single_event(&event, historical_cfg, false, &context);+ let result = process_single_event(+ &event,+ router::HistoricalConfig::new(false, 1),+ false,+ &context,+ );assert!(result.is_ok());let processed = result.unwrap();@@ -781,8 +838,12 @@ mod tests {let event = create_test_event(Some("2023-01-01T11:59:55Z".to_string()), None, None);- let historical_cfg = router::HistoricalConfig::new(false, 1);- let result = process_single_event(&event, historical_cfg, false, &context);+ let result = process_single_event(+ &event,+ router::HistoricalConfig::new(false, 1),+ false,+ &context,+ );assert!(result.is_ok());let processed = result.unwrap();@@ -805,8 +866,12 @@ mod tests {let event = create_test_event(Some("2023-01-01T11:00:00Z".to_string()), None, Some(true));- let historical_cfg = router::HistoricalConfig::new(false, 1);- let result = process_single_event(&event, historical_cfg, false, &context);+ let result = process_single_event(+ &event,+ router::HistoricalConfig::new(false, 1),+ false,+ &context,+ );assert!(result.is_ok());let processed = result.unwrap();@@ -828,8 +893,12 @@ mod tests {let event = create_test_event(Some("2023-01-01T11:00:00Z".to_string()), None, None);- let historical_cfg = router::HistoricalConfig::new(false, 1);- let result = process_single_event(&event, historical_cfg, false, &context);+ let result = process_single_event(+ &event,+ router::HistoricalConfig::new(false, 1),+ false,+ &context,+ );assert!(result.is_ok());let processed = result.unwrap();@@ -849,8 +918,12 @@ mod tests {let event = create_test_event(Some("2023-01-01T11:00:00Z".to_string()), None, None);- let historical_cfg = router::HistoricalConfig::new(false, 1);- let result = process_single_event(&event, historical_cfg, false, &context);+ let result = process_single_event(+ &event,+ router::HistoricalConfig::new(false, 1),+ false,+ &context,+ );assert!(result.is_ok());let processed = result.unwrap();@@ -881,8 +954,6 @@ mod tests {)];let sink = Arc::new(MockSink::new());- let dropper = Arc::new(limiters::token_dropper::TokenDropper::default());- let historical_cfg = router::HistoricalConfig::new(false, 1);// Create restriction service with DropEventlet service =@@ -899,18 +970,14 @@ mod tests {);service.update(manager).await;- let result = process_events(+ let result = run_pipeline(sink.clone(),- dropper,- Some(service),- historical_cfg,- None,- None,- None,- None,- &AiRouting::Primary,events,&context,+ PipelineOptions {+ restriction_service: Some(service),+ ..Default::default()+ },).await;@@ -932,8 +999,6 @@ mod tests {)];let sink = Arc::new(MockSink::new());- let dropper = Arc::new(limiters::token_dropper::TokenDropper::default());- let historical_cfg = router::HistoricalConfig::new(false, 1);// Create restriction service with ForceOverflowlet service =@@ -950,18 +1015,14 @@ mod tests {);service.update(manager).await;- let result = process_events(+ let result = run_pipeline(sink.clone(),- dropper,- Some(service),- historical_cfg,- None,- None,- None,- None,- &AiRouting::Primary,events,&context,+ PipelineOptions {+ restriction_service: Some(service),+ ..Default::default()+ },).await;@@ -984,8 +1045,6 @@ mod tests {)];let sink = Arc::new(MockSink::new());- let dropper = Arc::new(limiters::token_dropper::TokenDropper::default());- let historical_cfg = router::HistoricalConfig::new(false, 1);// Create restriction service with SkipPersonProcessinglet service =@@ -1002,18 +1061,14 @@ mod tests {);service.update(manager).await;- let result = process_events(+ let result = run_pipeline(sink.clone(),- dropper,- Some(service),- historical_cfg,- None,- None,- None,- None,- &AiRouting::Primary,events,&context,+ PipelineOptions {+ restriction_service: Some(service),+ ..Default::default()+ },).await;@@ -1036,8 +1091,6 @@ mod tests {)];let sink = Arc::new(MockSink::new());- let dropper = Arc::new(limiters::token_dropper::TokenDropper::default());- let historical_cfg = router::HistoricalConfig::new(false, 1);// Create restriction service with RedirectToDlqlet service =@@ -1054,18 +1107,14 @@ mod tests {);service.update(manager).await;- let result = process_events(+ let result = run_pipeline(sink.clone(),- dropper,- Some(service),- historical_cfg,- None,- None,- None,- None,- &AiRouting::Primary,events,&context,+ PipelineOptions {+ restriction_service: Some(service),+ ..Default::default()+ },).await;@@ -1088,8 +1137,6 @@ mod tests {)];let sink = Arc::new(MockSink::new());- let dropper = Arc::new(limiters::token_dropper::TokenDropper::default());- let historical_cfg = router::HistoricalConfig::new(false, 1);// Create restriction service with multiple restrictionslet service =@@ -1113,18 +1160,14 @@ mod tests {);service.update(manager).await;- let result = process_events(+ let result = run_pipeline(sink.clone(),- dropper,- Some(service),- historical_cfg,- None,- None,- None,- None,- &AiRouting::Primary,events,&context,+ PipelineOptions {+ restriction_service: Some(service),+ ..Default::default()+ },).await;@@ -1148,24 +1191,9 @@ mod tests {)];let sink = Arc::new(MockSink::new());- let dropper = Arc::new(limiters::token_dropper::TokenDropper::default());- let historical_cfg = router::HistoricalConfig::new(false, 1);// No restriction service- let result = process_events(- sink.clone(),- dropper,- None,- historical_cfg,- None,- None,- None,- None,- &AiRouting::Primary,- events,- &context,- )- .await;+ let result = run_pipeline(sink.clone(), events, &context, PipelineOptions::default()).await;assert!(result.is_ok());let captured = sink.get_events();@@ -1189,8 +1217,6 @@ mod tests {)];let sink = Arc::new(MockSink::new());- let dropper = Arc::new(limiters::token_dropper::TokenDropper::default());- let historical_cfg = router::HistoricalConfig::new(false, 1);// Create restriction that only applies to different event namelet service =@@ -1209,18 +1235,14 @@ mod tests {);service.update(manager).await;- let result = process_events(+ let result = run_pipeline(sink.clone(),- dropper,- Some(service),- historical_cfg,- None,- None,- None,- None,- &AiRouting::Primary,events,&context,+ PipelineOptions {+ restriction_service: Some(service),+ ..Default::default()+ },).await;@@ -1243,8 +1265,6 @@ mod tests {)];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], Duration::from_secs(300));@@ -1260,18 +1280,14 @@ mod tests {);service.update(manager).await;- let result = process_events(+ let result = run_pipeline(sink.clone(),- dropper,- Some(service),- historical_cfg,- None,- None,- None,- None,- &AiRouting::Primary,events,&context,+ PipelineOptions {+ restriction_service: Some(service),+ ..Default::default()+ },).await;@@ -1284,31 +1300,56 @@ mod tests {);}- /// The `$ai_*` lane assignment is decided once per batch from the request- /// token: `secondary` diverts every `$ai_*` event, an allowlist diverts- /// only listed tokens, and `primary` never diverts. Non-AI events stay on- /// their normal route in every mode. The topic itself is resolved in the- /// kafka sink from `DataType::AiEvents`, not here.+ /// The `$ai_*` lane assignment holds across capture modes: `Events` and+ /// `Import` both divert every `$ai_*` event (only the AI lane has AI+ /// processing, so imports must divert too), winning over historical.+ /// Non-AI events stay on their normal route in every mode. The topic+ /// itself is resolved in the kafka sink from `DataType::AiEvents`, not+ /// here.+ struct AiLaneInput {+ capture_mode: crate::config::CaptureMode,+ // Import mode drops non-historical batches before classification, so+ // its case must arrive flagged historical.+ historical_migration: bool,+ }++ struct AiLaneExpected {+ ai_data_type: DataType,+ pageview_data_type: DataType,+ }+#[rstest]- #[case::secondary(AiRouting::Secondary, true)]- #[case::allowlisted_token(- AiRouting::SecondaryAllowlist(["test_token".to_string()].into_iter().collect()),- true+ #[case::events_mode(+ AiLaneInput {+ capture_mode: crate::config::CaptureMode::Events,+ historical_migration: false,+ },+ AiLaneExpected {+ ai_data_type: DataType::AiEvents,+ pageview_data_type: DataType::AnalyticsMain,+ })]- #[case::unlisted_token(- AiRouting::SecondaryAllowlist(["other_token".to_string()].into_iter().collect()),- false+ #[case::import_mode(+ AiLaneInput {+ capture_mode: crate::config::CaptureMode::Import,+ historical_migration: true,+ },+ AiLaneExpected {+ ai_data_type: DataType::AiEvents,+ pageview_data_type: DataType::AnalyticsHistorical,+ })]- #[case::primary(AiRouting::Primary, false)]#[tokio::test]async fn test_process_events_ai_lane_assignment(- #[case] routing: AiRouting,- #[case] expect_diverted: bool,+ #[case] input: AiLaneInput,+ #[case] expected: AiLaneExpected,) {let now = DateTime::parse_from_rfc3339("2023-01-01T12:00:00Z").unwrap().with_timezone(&Utc);- let context = create_test_context(now, None);+ let mut context = create_test_context(now, None);+ context.capture_mode = input.capture_mode;+ context.historical_migration = input.historical_migration;let events = vec![create_test_event_with_name("$ai_generation",@@ -1325,24 +1366,10 @@ mod tests {];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,- None,- &routing,- events,- &context,- )- .await- .unwrap();+ run_pipeline(sink.clone(), events, &context, PipelineOptions::default())+ .await+ .unwrap();let captured = sink.get_events();assert_eq!(captured.len(), 2);@@ -1350,12 +1377,7 @@ mod tests {.iter().find(|e| e.event.event == "$ai_generation").unwrap();- let expected = if expect_diverted {- DataType::AiEvents- } else {- DataType::AnalyticsMain- };- assert_eq!(ai_event.metadata.data_type, expected);+ assert_eq!(ai_event.metadata.data_type, expected.ai_data_type);// Lane assignment must not leak into the restriction-driven redirect// mechanism; the sink resolves the AI topic from the data type alone.assert_eq!(ai_event.metadata.redirect_to_topic, None);@@ -1363,7 +1385,7 @@ mod tests {.iter().find(|e| e.event.event == "$pageview").unwrap();- assert_eq!(pageview.metadata.data_type, DataType::AnalyticsMain);+ assert_eq!(pageview.metadata.data_type, expected.pageview_data_type);assert_eq!(pageview.metadata.redirect_to_topic, None);}@@ -1371,13 +1393,23 @@ mod tests {/// same slice the dedicated AI endpoints consult), not analytics ones:/// an ai-scoped DropEvent drops it, an analytics-scoped one must not/// cross pipelines into the AI lane.+ struct AiDropScopeCase {+ restriction_pipeline: Pipeline,+ expect_dropped: bool,+ }+#[rstest]- #[case::ai_scoped_drop_applies(Pipeline::Ai, true)]- #[case::analytics_scoped_drop_does_not_cross(Pipeline::Analytics, false)]+ #[case::ai_scoped_drop_applies(AiDropScopeCase {+ restriction_pipeline: Pipeline::Ai,+ expect_dropped: true,+ })]+ #[case::analytics_scoped_drop_does_not_cross(AiDropScopeCase {+ restriction_pipeline: Pipeline::Analytics,+ expect_dropped: false,+ })]#[tokio::test]async fn test_process_events_drop_restriction_on_diverted_ai_events(- #[case] restriction_pipeline: Pipeline,- #[case] expect_dropped: bool,+ #[case] case: AiDropScopeCase,) {let now = DateTime::parse_from_rfc3339("2023-01-01T12:00:00Z").unwrap()@@ -1391,8 +1423,6 @@ mod tests {)];let sink = Arc::new(MockSink::new());- let dropper = Arc::new(limiters::token_dropper::TokenDropper::default());- let historical_cfg = router::HistoricalConfig::new(false, 1);let service = EventRestrictionService::new(vec![Pipeline::Analytics, Pipeline::Ai],@@ -1400,7 +1430,7 @@ mod tests {);let mut manager = RestrictionManager::new();manager.insert_restrictions(- restriction_pipeline,+ case.restriction_pipeline,"test_token",vec![Restriction {restriction_type: RestrictionType::DropEvent,@@ -1410,24 +1440,20 @@ mod tests {);service.update(manager).await;- process_events(+ run_pipeline(sink.clone(),- dropper,- Some(service),- historical_cfg,- None,- None,- None,- None,- &AiRouting::Secondary,events,&context,+ PipelineOptions {+ restriction_service: Some(service),+ ..Default::default()+ },).await.unwrap();let captured = sink.get_events();- if expect_dropped {+ if case.expect_dropped {assert!(captured.is_empty());} else {assert_eq!(captured.len(), 1);@@ -1454,8 +1480,6 @@ mod tests {)];let sink = Arc::new(MockSink::new());- let dropper = Arc::new(limiters::token_dropper::TokenDropper::default());- let historical_cfg = router::HistoricalConfig::new(false, 1);let service = EventRestrictionService::new(vec![Pipeline::Analytics, Pipeline::Ai],@@ -1473,18 +1497,14 @@ mod tests {);service.update(manager).await;- process_events(+ run_pipeline(sink.clone(),- dropper,- Some(service),- historical_cfg,- None,- None,- None,- None,- &AiRouting::Secondary,events,&context,+ PipelineOptions {+ restriction_service: Some(service),+ ..Default::default()+ },).await.unwrap();@@ -1518,8 +1538,6 @@ mod tests {)];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], Duration::from_secs(300));@@ -1535,18 +1553,14 @@ mod tests {);service.update(manager).await;- process_events(+ run_pipeline(sink.clone(),- dropper,- Some(service),- historical_cfg,- None,- None,- None,- None,- &AiRouting::Primary,events,&context,+ PipelineOptions {+ restriction_service: Some(service),+ ..Default::default()+ },).await.unwrap();@@ -1582,8 +1596,6 @@ mod tests {)];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], Duration::from_secs(300));@@ -1611,18 +1623,14 @@ mod tests {);service.update(manager).await;- process_events(+ run_pipeline(sink.clone(),- dropper,- Some(service),- historical_cfg,- None,- None,- None,- None,- &AiRouting::Primary,events,&context,+ PipelineOptions {+ restriction_service: Some(service),+ ..Default::default()+ },).await.unwrap();@@ -1665,8 +1673,6 @@ mod tests {];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.@@ -1686,18 +1692,14 @@ mod tests {);service.update(manager).await;- process_events(+ run_pipeline(sink.clone(),- dropper,- Some(service),- historical_cfg,- None,- None,- None,- None,- &AiRouting::Primary,events,&context,+ PipelineOptions {+ restriction_service: Some(service),+ ..Default::default()+ },).await.unwrap();@@ -1737,8 +1739,6 @@ mod tests {];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],@@ -1756,18 +1756,14 @@ mod tests {);service.update(manager).await;- process_events(+ run_pipeline(sink.clone(),- dropper,- Some(service),- historical_cfg,- None,- None,- None,- None,- &AiRouting::Primary,events,&context,+ PipelineOptions {+ restriction_service: Some(service),+ ..Default::default()+ },).await.unwrap();@@ -1801,8 +1797,6 @@ mod tests {)];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], Duration::from_secs(300));@@ -1818,18 +1812,14 @@ mod tests {);service.update(manager).await;- process_events(+ run_pipeline(sink.clone(),- dropper,- Some(service),- historical_cfg,- None,- None,- None,- None,- &AiRouting::Primary,events,&context,+ PipelineOptions {+ restriction_service: Some(service),+ ..Default::default()+ },).await.unwrap();@@ -1871,24 +1861,10 @@ mod tests {)];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, // no overflow limiter- None,- None,- &AiRouting::Primary,- events,- &context,- )- .await- .unwrap();+ run_pipeline(sink.clone(), events, &context, PipelineOptions::default())+ .await+ .unwrap();let captured = sink.get_events();assert_eq!(captured.len(), 1);@@ -1908,23 +1884,17 @@ mod tests {)];let sink = Arc::new(MockSink::new());- let dropper = Arc::new(limiters::token_dropper::TokenDropper::default());- let historical_cfg = router::HistoricalConfig::new(false, 1);// test_token is in the reroute list -> ForceLimitedlet limiter = build_limiter(10, 10, Some("test_token".to_string()), false);- process_events(+ run_pipeline(sink.clone(),- dropper,- None,- historical_cfg,- None,- Some(limiter),- None,- None,- &AiRouting::Primary,events,&context,+ PipelineOptions {+ overflow_limiter: Some(limiter),+ ..Default::default()+ },).await.unwrap();@@ -1937,18 +1907,26 @@ mod tests {);}+ struct AiValveCase {+ ai_limiter_present: bool,+ expected_reason: Option<OverflowReason>,+ }+/// End-to-end gate for the AI overflow valve: a diverted `$ai_*` event/// is overflow-stamped only when the AI limiter is wired (setup builds/// it exactly when `CAPTURE_ANALYTICS_AI_EVENTS_OVERFLOW_TOPIC` is/// configured), and keeps its AI lane either way.#[rstest]- #[case::limiter_present(true, Some(OverflowReason::ForceLimited))]- #[case::limiter_absent(false, None)]+ #[case::limiter_present(AiValveCase {+ ai_limiter_present: true,+ expected_reason: Some(OverflowReason::ForceLimited),+ })]+ #[case::limiter_absent(AiValveCase {+ ai_limiter_present: false,+ expected_reason: None,+ })]#[tokio::test]- async fn test_ai_events_overflow_stamp_gated_on_limiter_presence(- #[case] ai_limiter_present: bool,- #[case] expected_reason: Option<OverflowReason>,- ) {+ async fn test_ai_events_overflow_stamp_gated_on_limiter_presence(#[case] case: AiValveCase) {let now = DateTime::parse_from_rfc3339("2023-01-01T12:00:00Z").unwrap().with_timezone(&Utc);@@ -1961,23 +1939,18 @@ mod tests {)];let sink = Arc::new(MockSink::new());- let dropper = Arc::new(limiters::token_dropper::TokenDropper::default());- let historical_cfg = router::HistoricalConfig::new(false, 1);- let ai_limiter = ai_limiter_present+ let ai_limiter = case+ .ai_limiter_present.then(|| build_limiter(10, 10, Some("test_token".to_string()), false));- process_events(+ run_pipeline(sink.clone(),- dropper,- None,- historical_cfg,- None,- None,- ai_limiter,- None,- &AiRouting::Secondary,events,&context,+ PipelineOptions {+ ai_events_overflow_limiter: ai_limiter,+ ..Default::default()+ },).await.unwrap();@@ -1985,7 +1958,7 @@ mod tests {let captured = sink.get_events();assert_eq!(captured.len(), 1);assert_eq!(captured[0].metadata.data_type, DataType::AiEvents);- assert_eq!(captured[0].metadata.overflow_reason, expected_reason);+ assert_eq!(captured[0].metadata.overflow_reason, case.expected_reason);}#[tokio::test]@@ -2000,23 +1973,17 @@ mod tests {];let sink = Arc::new(MockSink::new());- let dropper = Arc::new(limiters::token_dropper::TokenDropper::default());- let historical_cfg = router::HistoricalConfig::new(false, 1);// burst of 1 -> first event passes, second event rate-limitedlet limiter = build_limiter(1, 1, None, true);- process_events(+ run_pipeline(sink.clone(),- dropper,- None,- historical_cfg,- None,- Some(limiter),- None,- None,- &AiRouting::Primary,events,&context,+ PipelineOptions {+ overflow_limiter: Some(limiter),+ ..Default::default()+ },).await.unwrap();@@ -2044,22 +2011,16 @@ mod tests {];let sink = Arc::new(MockSink::new());- let dropper = Arc::new(limiters::token_dropper::TokenDropper::default());- let historical_cfg = router::HistoricalConfig::new(false, 1);let limiter = build_limiter(1, 1, None, false);- process_events(+ run_pipeline(sink.clone(),- dropper,- None,- historical_cfg,- None,- Some(limiter),- None,- None,- &AiRouting::Primary,events,&context,+ PipelineOptions {+ overflow_limiter: Some(limiter),+ ..Default::default()+ },).await.unwrap();@@ -2089,8 +2050,6 @@ mod tests {)];let sink = Arc::new(MockSink::new());- let dropper = Arc::new(limiters::token_dropper::TokenDropper::default());- let historical_cfg = router::HistoricalConfig::new(false, 1);// Even with a limiter that would flag this token, force_overflow wins.let limiter = build_limiter(10, 10, Some("test_token".to_string()), false);@@ -2108,18 +2067,15 @@ mod tests {);service.update(manager).await;- process_events(+ run_pipeline(sink.clone(),- dropper,- Some(service),- historical_cfg,- None,- Some(limiter),- None,- None,- &AiRouting::Primary,events,&context,+ PipelineOptions {+ restriction_service: Some(service),+ overflow_limiter: Some(limiter),+ ..Default::default()+ },).await.unwrap();@@ -2146,22 +2102,16 @@ mod tests {)];let sink = Arc::new(MockSink::new());- let dropper = Arc::new(limiters::token_dropper::TokenDropper::default());- let historical_cfg = router::HistoricalConfig::new(false, 1);let limiter = build_limiter(10, 10, Some("test_token".to_string()), false);- process_events(+ run_pipeline(sink.clone(),- dropper,- None,- historical_cfg,- None,- Some(limiter),- None,- None,- &AiRouting::Primary,events,&context,+ PipelineOptions {+ overflow_limiter: Some(limiter),+ ..Default::default()+ },).await.unwrap();@@ -2194,8 +2144,6 @@ mod tests {];let sink = Arc::new(MockSink::new());- let dropper = Arc::new(limiters::token_dropper::TokenDropper::default());- let historical_cfg = router::HistoricalConfig::new(false, 1);// Global RL: limits (test_token, test_user) -> key `test_token:test_user`.let global_limiter = Arc::new(GlobalRateLimiter::mock_limiting(&["test_token:test_user"]));@@ -2204,18 +2152,15 @@ mod tests {// stamped RateLimited{preserve_locality: true}.let overflow_limiter = build_limiter(1, 1, None, true);- process_events(+ run_pipeline(sink.clone(),- dropper,- None,- historical_cfg,- Some(global_limiter),- Some(overflow_limiter),- None,- None,- &AiRouting::Primary,events,&context,+ PipelineOptions {+ global_rate_limiter: Some(global_limiter),+ overflow_limiter: Some(overflow_limiter),+ ..Default::default()+ },).await.unwrap();@@ -2266,22 +2211,16 @@ mod tests {)];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(+ run_pipeline(sink.clone(),- dropper,- None,- historical_cfg,- Some(global_limiter),- None, // no overflow limiter -- isolate global RL behavior- None,- None,- &AiRouting::Primary,events,&context,+ PipelineOptions {+ global_rate_limiter: Some(global_limiter),+ ..Default::default()+ },).await.unwrap();@@ -2297,30 +2236,36 @@ mod tests {);}+ struct SdkWarningCase {+ attribution: Option<SdkAttribution>,+ expected_lib: &'static str,+ expected_lib_version: &'static str,+ }+// The legacy path carries the bulk of rate-limited traffic, and it's the one// whose SDK attribution has to survive a snapshot taken back at batch// construction — by this stage the events are serialized.#[rstest::rstest]- #[case::sdk_reported(- Some(SdkAttribution {+ #[case::sdk_reported(SdkWarningCase {+ attribution: Some(SdkAttribution {lib: Some("web".to_string()),lib_version: Some("1.2.3".to_string()),}),- "web",- "1.2.3"- )]- #[case::sdk_absent(None, "unknown", "unknown")]+ expected_lib: "web",+ expected_lib_version: "1.2.3",+ })]+ #[case::sdk_absent(SdkWarningCase {+ attribution: None,+ expected_lib: "unknown",+ expected_lib_version: "unknown",+ })]#[tokio::test]- async fn global_rate_limit_emits_a_warning_naming_the_hot_key(- #[case] attribution: Option<SdkAttribution>,- #[case] expected_lib: &str,- #[case] expected_lib_version: &str,- ) {+ async fn global_rate_limit_emits_a_warning_naming_the_hot_key(#[case] case: SdkWarningCase) {let now = DateTime::parse_from_rfc3339("2023-01-01T12:00:00Z").unwrap().with_timezone(&Utc);let mut context = create_test_context(now, None);- if let Some(attribution) = attribution {+ if let Some(attribution) = case.attribution {context.sdk_attribution = attribution;}let events = vec![create_test_event(@@ -2330,23 +2275,18 @@ mod tests {)];let sink = Arc::new(MockSink::new());- let dropper = Arc::new(limiters::token_dropper::TokenDropper::default());- let historical_cfg = router::HistoricalConfig::new(false, 1);let global_limiter = Arc::new(GlobalRateLimiter::mock_limiting(&["test_token:test_user"]));let collector = Arc::new(CollectingEmitter::new());- process_events(+ run_pipeline(sink.clone(),- dropper,- None,- historical_cfg,- Some(global_limiter),- None,- None,- Some(collector.clone()),- &AiRouting::Primary,events,&context,+ PipelineOptions {+ global_rate_limiter: Some(global_limiter),+ ingestion_warning_emitter: Some(collector.clone()),+ ..Default::default()+ },).await.unwrap();@@ -2363,10 +2303,10 @@ mod tests {serde_json::json!("test_user"));assert_eq!(w.extra_details["distinctIdCount"], serde_json::json!(1));- assert_eq!(w.extra_details["lib"], serde_json::json!(expected_lib));+ assert_eq!(w.extra_details["lib"], serde_json::json!(case.expected_lib));assert_eq!(w.extra_details["libVersion"],- serde_json::json!(expected_lib_version)+ serde_json::json!(case.expected_lib_version));assert_eq!(w.extra_details["path"], serde_json::json!("/e/"));}@@ -2387,18 +2327,14 @@ mod tests {let sink = Arc::new(MockSink::new());let collector = Arc::new(CollectingEmitter::new());- let result = process_events(+ let result = run_pipeline(sink.clone(),- Arc::new(limiters::token_dropper::TokenDropper::default()),- None,- router::HistoricalConfig::new(false, 1),- None,- None,- None,- Some(collector.clone()),- &AiRouting::Primary,events,&context,+ PipelineOptions {+ ingestion_warning_emitter: Some(collector.clone()),+ ..Default::default()+ },).await;@@ -2444,18 +2380,14 @@ mod tests {let collector = Arc::new(CollectingEmitter::new());- let result = process_events(+ let result = run_pipeline(Arc::new(RejectingSink),- Arc::new(limiters::token_dropper::TokenDropper::default()),- None,- router::HistoricalConfig::new(false, 1),- None,- None,- None,- Some(collector.clone()),- &AiRouting::Primary,events,&context,+ PipelineOptions {+ ingestion_warning_emitter: Some(collector.clone()),+ ..Default::default()+ },).await;@@ -2479,8 +2411,6 @@ mod tests {)];let sink = Arc::new(MockSink::new());- let dropper = Arc::new(limiters::token_dropper::TokenDropper::default());- let historical_cfg = router::HistoricalConfig::new(false, 1);let global_limiter = Arc::new(GlobalRateLimiter::mock_limiting(&["test_token:test_user"]));let collector = Arc::new(CollectingEmitter::new());@@ -2498,18 +2428,16 @@ mod tests {);service.update(manager).await;- process_events(+ run_pipeline(sink.clone(),- dropper,- Some(service),- historical_cfg,- Some(global_limiter),- None,- None,- Some(collector.clone()),- &AiRouting::Primary,events,&context,+ PipelineOptions {+ restriction_service: Some(service),+ global_rate_limiter: Some(global_limiter),+ ingestion_warning_emitter: Some(collector.clone()),+ ..Default::default()+ },).await.unwrap();@@ -2541,22 +2469,16 @@ mod tests {)];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(+ run_pipeline(sink.clone(),- dropper,- None,- historical_cfg,- Some(global_limiter),- None, // no overflow limiter -- isolate global RL behavior- None,- None,- &AiRouting::Primary,events,&context,+ PipelineOptions {+ global_rate_limiter: Some(global_limiter),+ ..Default::default()+ },).await.unwrap();@@ -2592,24 +2514,10 @@ mod tests {];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,- None,- &AiRouting::Primary,- events,- &context,- )- .await- .unwrap();+ run_pipeline(sink.clone(), events, &context, PipelineOptions::default())+ .await+ .unwrap();assert_eq!(sink.get_events().len(),@@ -2634,24 +2542,10 @@ mod tests {)];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,- None,- &AiRouting::Primary,- events,- &context,- )- .await- .unwrap();+ run_pipeline(sink.clone(), events, &context, PipelineOptions::default())+ .await+ .unwrap();let captured = sink.get_events();assert_eq!(captured.len(), 1);@@ -2680,22 +2574,16 @@ mod tests {)];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(+ run_pipeline(sink.clone(),- dropper,- None,- historical_cfg,- Some(global_limiter),- None,- None,- None,- &AiRouting::Primary,events,&context,+ PipelineOptions {+ global_rate_limiter: Some(global_limiter),+ ..Default::default()+ },).await.unwrap();@@ -2734,23 +2622,17 @@ mod tests {producer.clone(),test_topics(),));- let dropper = Arc::new(limiters::token_dropper::TokenDropper::default());- let historical_cfg = router::HistoricalConfig::new(false, 1);// test_token in reroute list -> ForceLimited stamped in pipeline.let limiter = build_limiter(10, 10, Some("test_token".to_string()), false);- process_events(+ run_pipeline(sink,- dropper,- None,- historical_cfg,- None,- Some(limiter),- None,- None,- &AiRouting::Primary,events,&context,+ PipelineOptions {+ overflow_limiter: Some(limiter),+ ..Default::default()+ },).await.unwrap();@@ -2796,23 +2678,17 @@ mod tests {producer.clone(),test_topics(),));- let dropper = Arc::new(limiters::token_dropper::TokenDropper::default());- let historical_cfg = router::HistoricalConfig::new(false, 1);// burst=1 => event[1] stamped RateLimited { preserve_locality }.let limiter = build_limiter(1, 1, None, preserve_locality);- process_events(+ run_pipeline(sink,- dropper,- None,- historical_cfg,- None,- Some(limiter),- None,- None,- &AiRouting::Primary,events,&context,+ PipelineOptions {+ overflow_limiter: Some(limiter),+ ..Default::default()+ },).await.unwrap();@@ -2903,20 +2779,40 @@ mod tests {}}+ struct HeatmapDataCase {+ property_keys: &'static [&'static str],+ expect_has_heatmap_data: bool,+ }+#[rstest]- #[case::heatmap_data_present(&["$heatmap_data"], true)]- #[case::scroll_depth_pair(&["$prev_pageview_pathname", "$current_url"], true)]- #[case::heatmap_data_with_scroll_depth(- &["$heatmap_data", "$prev_pageview_pathname", "$current_url"],- true,- )]- #[case::only_prev_pageview_pathname(&["$prev_pageview_pathname"], false)]- #[case::only_current_url(&["$current_url"], false)]- #[case::no_heatmap_properties(&[], false)]- fn test_has_heatmap_data(#[case] property_keys: &[&str], #[case] expected: bool) {+ #[case::heatmap_data_present(HeatmapDataCase {+ property_keys: &["$heatmap_data"],+ expect_has_heatmap_data: true,+ })]+ #[case::scroll_depth_pair(HeatmapDataCase {+ property_keys: &["$prev_pageview_pathname", "$current_url"],+ expect_has_heatmap_data: true,+ })]+ #[case::heatmap_data_with_scroll_depth(HeatmapDataCase {+ property_keys: &["$heatmap_data", "$prev_pageview_pathname", "$current_url"],+ expect_has_heatmap_data: true,+ })]+ #[case::only_prev_pageview_pathname(HeatmapDataCase {+ property_keys: &["$prev_pageview_pathname"],+ expect_has_heatmap_data: false,+ })]+ #[case::only_current_url(HeatmapDataCase {+ property_keys: &["$current_url"],+ expect_has_heatmap_data: false,+ })]+ #[case::no_heatmap_properties(HeatmapDataCase {+ property_keys: &[],+ expect_has_heatmap_data: false,+ })]+ fn test_has_heatmap_data(#[case] case: HeatmapDataCase) {let mut properties = HashMap::new();properties.insert("distinct_id".to_string(), json!("test_user"));- for key in property_keys {+ for key in case.property_keys {properties.insert((*key).to_string(), json!("anything"));}@@ -2932,7 +2828,7 @@ mod tests {token: Some("test_token".to_string()),};- assert_eq!(has_heatmap_data(&event), expected);+ assert_eq!(has_heatmap_data(&event), case.expect_has_heatmap_data);}#[test]@@ -2940,11 +2836,11 @@ mod tests {let now = Utc::now();let context = create_test_context(now, None);let event = build_heatmap_carrier_event(HeatmapShape::HeatmapData);- let historical_cfg = router::HistoricalConfig::new(false, 1);- let redirect = create_heatmap_redirect(&event, historical_cfg, &context)- .unwrap()- .expect("redirect should be created when distinct_id is resolvable");+ let redirect =+ create_heatmap_redirect(&event, router::HistoricalConfig::new(false, 1), &context)+ .unwrap()+ .expect("redirect should be created when distinct_id is resolvable");assert_eq!(redirect.metadata.data_type, DataType::HeatmapMain);assert_eq!(redirect.metadata.event_name, "$$heatmap");@@ -2990,11 +2886,11 @@ mod tests {event.properties.insert("$cookieless_mode".to_string(), json!(true));- let historical_cfg = router::HistoricalConfig::new(false, 1);- let redirect = create_heatmap_redirect(&event, historical_cfg, &context)- .unwrap()- .expect("redirect should be created");+ let redirect =+ create_heatmap_redirect(&event, router::HistoricalConfig::new(false, 1), &context)+ .unwrap()+ .expect("redirect should be created");let data: RawEvent = serde_json::from_str(&redirect.event.data).unwrap();for key in [@@ -3024,9 +2920,10 @@ mod tests {let mut event = build_heatmap_carrier_event(HeatmapShape::HeatmapData);event.distinct_id = None;event.properties.remove("distinct_id");- let historical_cfg = router::HistoricalConfig::new(false, 1);- let result = create_heatmap_redirect(&event, historical_cfg, &context).unwrap();+ let result =+ create_heatmap_redirect(&event, router::HistoricalConfig::new(false, 1), &context)+ .unwrap();assert!(result.is_none());}@@ -3037,11 +2934,11 @@ mod tests {let event = build_heatmap_carrier_event(HeatmapShape::HeatmapData);// Carrier event has distinct_id only in properties (top-level is None).assert!(event.distinct_id.is_none());- let historical_cfg = router::HistoricalConfig::new(false, 1);- let redirect = create_heatmap_redirect(&event, historical_cfg, &context)- .unwrap()- .expect("redirect should fall back to properties for distinct_id");+ let redirect =+ create_heatmap_redirect(&event, router::HistoricalConfig::new(false, 1), &context)+ .unwrap()+ .expect("redirect should fall back to properties for distinct_id");let data: RawEvent = serde_json::from_str(&redirect.event.data).unwrap();assert_eq!(data.distinct_id, Some(json!("test_user")));@@ -3057,24 +2954,10 @@ mod tests {let events = vec![build_heatmap_carrier_event(shape)];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,- None,- &AiRouting::Primary,- events,- &context,- )- .await- .unwrap();+ run_pipeline(sink.clone(), events, &context, PipelineOptions::default())+ .await+ .unwrap();let captured = sink.get_events();assert_eq!(captured.len(), 2, "should produce original + redirect");@@ -3108,24 +2991,10 @@ mod tests {let events = vec![event];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,- None,- &AiRouting::Primary,- events,- &context,- )- .await- .unwrap();+ run_pipeline(sink.clone(), events, &context, PipelineOptions::default())+ .await+ .unwrap();let captured = sink.get_events();assert_eq!(@@ -3148,24 +3017,10 @@ mod tests {)];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,- None,- &AiRouting::Primary,- events,- &context,- )- .await- .unwrap();+ run_pipeline(sink.clone(), events, &context, PipelineOptions::default())+ .await+ .unwrap();let captured = sink.get_events();assert_eq!(captured.len(), 1);@@ -3196,24 +3051,10 @@ mod tests {producer.clone(),test_topics(),));- let dropper = Arc::new(limiters::token_dropper::TokenDropper::default());- let historical_cfg = router::HistoricalConfig::new(false, 1);- process_events(- sink,- dropper,- None,- historical_cfg,- None,- None,- None,- None,- &AiRouting::Primary,- events,- &context,- )- .await- .unwrap();+ run_pipeline(sink, events, &context, PipelineOptions::default())+ .await+ .unwrap();let records = producer.get_records();assert_eq!(@@ -3419,18 +3260,15 @@ mod tests {let context = create_test_context(now, None);let collector = Arc::new(CollectingEmitter::new());- let result = process_events(+ let result = run_pipeline(sink,- dropper,- None,- router::HistoricalConfig::new(false, 1),- None,- None,- None,- Some(collector.clone()),- &AiRouting::Primary,events,&context,+ PipelineOptions {+ dropper,+ ingestion_warning_emitter: Some(collector.clone()),+ ..Default::default()+ },).await;diff --git a/rust/capture/src/overflow_parity.rs b/rust/capture/src/overflow_parity.rsindex 781b315db25c..9c9afcd9f868 100644--- a/rust/capture/src/overflow_parity.rs+++ b/rust/capture/src/overflow_parity.rs@@ -19,7 +19,6 @@ use limiters::token_dropper::TokenDropper;use rstest::rstest;use std::num::NonZeroU32;-use crate::config::AiRouting;use crate::global_rate_limiter::GlobalRateLimiter;use crate::router::HistoricalConfig;use crate::sinks::kafka::{test_topics, KafkaSinkBase};@@ -145,7 +144,6 @@ async fn run_v0(limits: Limits, batch_size: usize, observe: usize) -> Observed {v0_overflow_limiter(limits),None,None,- &AiRouting::Primary,(0..batch_size).map(|_| v0_raw_event()).collect(),&v0_context(now),)diff --git a/rust/capture/src/router.rs b/rust/capture/src/router.rsindex 5dcbc45feb35..1336c5700cdd 100644--- a/rust/capture/src/router.rs+++ b/rust/capture/src/router.rs@@ -27,7 +27,7 @@ use limiters::overflow::OverflowLimiter;use limiters::redis::RedisLimiter;use limiters::token_dropper::TokenDropper;-use crate::config::{AiRouting, CaptureMode};+use crate::config::CaptureMode;use crate::metrics_middleware::track_metrics;use crate::quota_limiters::CaptureQuotaLimiter;use metrics_exporter_prometheus::PrometheusHandle;@@ -91,14 +91,6 @@ pub struct State {/// V1 sink router for the new capture analytics pipeline./// When present, the v1 analytics handler publishes events through this.pub v1_sink_router: Option<Arc<crate::v1::sinks::Router>>,- /// Routing policy for diverting `$ai_*` events to the dedicated AI topic- /// (`CAPTURE_ANALYTICS_AI_EVENTS_TOPIC`), derived from `CAPTURE_ANALYTICS_AI_EVENTS_MODE` and- /// `CAPTURE_ANALYTICS_AI_EVENTS_ALLOWLIST_TOKENS`. `Primary` keeps everything on the- /// analytics main topic; the other modes divert per batch token, in both- /// the v0 pipeline (via `DataType::AiEvents`, mapped to the topic in the- /// kafka sink) and the v1 pipeline (via `Destination::AiEvents`, mapped- /// via the `topic_ai` injected into each sink config at setup).- pub ai_routing: AiRouting,/// Whether the AI overflow valve is armed (`CAPTURE_ANALYTICS_AI_EVENTS_OVERFLOW_TOPIC` is/// set). Gates overflow stamping for the AI lane in both pipelines: when/// false, AI events never overflow (pre-overflow behavior).@@ -184,7 +176,6 @@ pub fn router<TZ: TimeSource + Send + Sync + 'static, R: Client + Send + Sync +v1_sink_router: Option<Arc<crate::v1::sinks::Router>>,capture_v1_scatter_gather_min_batch: usize,ai_gateway_signing_secret: Option<String>,- ai_routing: AiRouting,ai_events_overflow_enabled: bool,ingestion_warning_emitter: Option<Arc<dyn WarningEmitter>>,) -> Router {@@ -215,7 +206,6 @@ pub fn router<TZ: TimeSource + Send + Sync + 'static, R: Client + Send + Sync +v1_sink_router,capture_v1_scatter_gather_min_batch,ai_gateway_signing_secret,- ai_routing,ai_events_overflow_enabled,ingestion_warning_emitter,capture_mode,diff --git a/rust/capture/src/setup.rs b/rust/capture/src/setup.rsindex 8c3460a61dc4..ea997687a947 100644--- a/rust/capture/src/setup.rs+++ b/rust/capture/src/setup.rs@@ -1,4 +1,4 @@-use std::collections::{HashMap, HashSet};+use std::collections::HashMap;use std::sync::Arc;use std::time::Duration;@@ -14,7 +14,7 @@ use metrics::gauge;use tracing::{info, warn};use crate::ai_s3::AiBlobStorage;-use crate::config::{AiRouting, AiSinkMode, CaptureMode, Config, KafkaConfig};+use crate::config::{CaptureMode, Config};use crate::event_restrictions::{EventRestrictionService, Pipeline, RedisRestrictionsRepository};use crate::global_rate_limiter::GlobalRateLimiter;use crate::prometheus::setup_metrics_recorder;@@ -29,7 +29,6 @@ use crate::sinks::kafka::KafkaSink;use crate::sinks::noop::NoOpSink;use crate::sinks::print::PrintSink;use crate::sinks::s3::S3Sink;-use crate::sinks::split::SplitKafkaSink;use crate::sinks::Event;use limiters::overflow::OverflowLimiter;use limiters::redis::{QuotaResource, RedisLimiter, ServiceName, OVERFLOW_LIMITER_CACHE_KEY};@@ -47,18 +46,6 @@ pub struct LifecycleHandles {}pub fn register_components(manager: &mut lifecycle::Manager, config: &Config) -> LifecycleHandles {- // S3 fallback and AI secondary routing both contend for the single gating- // sink handle, and only one can own it. Enabling both leaves one cluster's- // producer unmonitored while the pod's liveness gates on an idle sink — refuse- // to start rather than silently watch the wrong cluster.- let ai_secondary_routing =- config.capture_mode == CaptureMode::Ai && config.ai_sink_mode != AiSinkMode::Primary;- assert!(- !(config.s3_fallback_enabled && ai_secondary_routing),- "invalid configuration: S3_FALLBACK_ENABLED cannot be combined with AI secondary routing (AI_SINK_MODE={:?}); enable at most one",- config.ai_sink_mode,- );-let server = manager.register("server",lifecycle::ComponentOptions::new().with_graceful_shutdown(Duration::from_secs(60)),@@ -279,64 +266,11 @@ pub async fn build_components(_ => None,};- // The capture sink is a single lifecycle component: `register_components`- // mints exactly one gating sink handle. When AI secondary routing is on we- // wrap the primary in a `SplitKafkaSink` that diverts events (all, or an- // allowlisted subset) to a second producer pointing at the secondary cluster- // (e.g. WarpStream). The KafkaSink layer is unchanged, so overflow/DLQ/redirect- // stamping applies on either cluster.- let build_secondary =- config.capture_mode == CaptureMode::Ai && config.ai_sink_mode != AiSinkMode::Primary;-- // Decide which producer carries the single gating handle so the right- // cluster's health gates the pod: the secondary when it is the sole- // destination (full `Secondary` cutover), the primary otherwise. The- // non-gating producer is built with no handle — it still produces and emits- // metrics, it just doesn't drive a manager component. S3 fallback keeps the- // handle on the primary path (it owns its own advisory wiring).- let secondary_owns_liveness = build_secondary- && config.ai_sink_mode == AiSinkMode::Secondary- && !config.s3_fallback_enabled;- let (primary_handle, secondary_handle) = if secondary_owns_liveness {- (None, sink_handle)- } else {- (sink_handle, None)- };-- let primary_sink: Arc<dyn Event + Send + Sync> = Arc::from(- create_sink(&config, primary_handle, advisory_handle)+ let sink: Arc<dyn Event + Send + Sync> = Arc::from(+ create_sink(&config, sink_handle, advisory_handle).await.expect("failed to create sink"),);-- let sink: Arc<dyn Event + Send + Sync> = if build_secondary {- let secondary: Arc<dyn Event + Send + Sync> = Arc::new(- KafkaSink::new(build_ai_secondary_kafka_config(&config), secondary_handle)- .await- .expect("failed to start AI secondary Kafka sink"),- );- let routing = match config.ai_sink_mode {- // build_secondary excludes Primary, so this arm cannot be reached.- AiSinkMode::Primary => AiRouting::Primary,- AiSinkMode::Secondary => AiRouting::Secondary,- AiSinkMode::SecondaryAllowlist => AiRouting::SecondaryAllowlist(- config- .ai_secondary_allowlist_tokens- .as_deref()- .map(parse_token_allowlist)- .unwrap_or_default(),- ),- // The percentage mode exists for the analytics topic routing only;- // refuse to start rather than fall through to a full cutover.- AiSinkMode::SecondaryPercentage => panic!(- "invalid configuration: AI_SINK_MODE=secondary_percentage is not supported; percentage routing exists only for CAPTURE_ANALYTICS_AI_EVENTS_MODE"- ),- };- info!(mode = ?config.ai_sink_mode, "AI secondary sink enabled");- Arc::new(SplitKafkaSink::new(primary_sink, secondary, routing))- } else {- primary_sink- };let sink_for_flush = sink.clone();// Create AI blob storage if S3 is configured@@ -392,47 +326,16 @@ pub async fn build_components(None};- // Deployment-level policy for diverting `$ai_*` events to a dedicated- // topic, shared by the v0 and v1 analytics pipelines. Distinct from the AI- // secondary CLUSTER routing above: this stays on the same sink and only- // changes the destination topic.- let ai_routing = match config.capture_analytics_ai_events_mode {- AiSinkMode::Primary => AiRouting::Primary,- AiSinkMode::Secondary => AiRouting::Secondary,- AiSinkMode::SecondaryAllowlist => AiRouting::SecondaryAllowlist(- config- .capture_analytics_ai_events_allowlist_tokens- .as_deref()- .map(parse_token_allowlist)- .unwrap_or_default(),- ),- AiSinkMode::SecondaryPercentage => AiRouting::SecondaryPercentage(require_percentage(- config.capture_analytics_ai_events_percentage,- )),- };assert!(- config.capture_analytics_ai_events_mode == AiSinkMode::Primary- || config- .kafka- .capture_analytics_ai_events_topic- .as_deref()- .is_some_and(|t| !t.is_empty()),- "invalid configuration: CAPTURE_ANALYTICS_AI_EVENTS_TOPIC must be set when CAPTURE_ANALYTICS_AI_EVENTS_MODE is not primary (got {:?})",- config.capture_analytics_ai_events_mode,+ !config.kafka.capture_analytics_ai_events_topic.is_empty(),+ "invalid configuration: CAPTURE_ANALYTICS_AI_EVENTS_TOPIC must not be empty",);- // The AI overflow valve: settable in advance of the routing mode (or- // absent), so it is deliberately not validated against it.- let ai_events_overflow_enabled = config- .kafka- .capture_analytics_ai_events_overflow_topic- .as_deref()- .is_some_and(|t| !t.is_empty());+ let ai_events_overflow_enabled = ai_events_overflow_valve(&config);info!(- ai_routing = ?ai_routing,- capture_analytics_ai_events_topic = ?config.kafka.capture_analytics_ai_events_topic,+ capture_analytics_ai_events_topic = %config.kafka.capture_analytics_ai_events_topic,capture_analytics_ai_events_overflow_topic = ?config.kafka.capture_analytics_ai_events_overflow_topic,ai_events_overflow_enabled,- "AI events topic routing policy"+ "AI events topic routing");// The AI lane gets its own limiter instance with the same knobs: the@@ -510,7 +413,6 @@ pub async fn build_components(v1_sink_router.clone(),config.capture_v1_scatter_gather_min_batch,config.ai_gateway_signing_secret.clone(),- ai_routing,ai_events_overflow_enabled,ingestion_warning_emitter,);@@ -529,54 +431,24 @@ pub async fn build_components(}}-/// Build the secondary AI Kafka config by inheriting all producer tuning from-/// the primary `kafka` config and overriding only the destination cluster and-/// main topic. Panics with a clear message if the required secondary-/// connection settings are missing — callers only invoke this when the AI sink-/// mode requires a secondary, so missing config is a fatal misconfiguration.-fn build_ai_secondary_kafka_config(config: &Config) -> KafkaConfig {- let mut kafka = config.kafka.clone();- kafka.kafka_hosts = config- .ai_secondary_kafka_hosts- .clone()- .filter(|h| !h.is_empty())- .expect("AI_SECONDARY_KAFKA_HOSTS is required when AI_SINK_MODE != primary");- kafka.kafka_topic = config- .ai_secondary_kafka_topic- .clone()- .filter(|t| !t.is_empty())- .expect("AI_SECONDARY_KAFKA_TOPIC is required when AI_SINK_MODE != primary");- kafka.kafka_tls = config.ai_secondary_kafka_tls;- if !config.ai_secondary_kafka_client_id.is_empty() {- kafka.kafka_client_id = config.ai_secondary_kafka_client_id.clone();- }- kafka-}--/// Parse a comma-separated token allowlist into a set, trimming whitespace and-/// dropping empty entries.-fn parse_token_allowlist(csv: &str) -> HashSet<String> {- csv.split(',')- .map(str::trim)- .filter(|s| !s.is_empty())- .map(String::from)- .collect()-}--/// Validate the percentage companion of the `secondary_percentage` routing-/// mode. Unlike the allowlist (where unset defaults to an empty set that-/// routes nothing), an unset percentage refuses to start: the mode being set-/// with no percentage is almost certainly a misconfigured rollout, not an-/// intent to route 0% of teams.-fn require_percentage(value: Option<u8>) -> u8 {- let percentage = value.expect(- "invalid configuration: CAPTURE_ANALYTICS_AI_EVENTS_PERCENTAGE must be set when CAPTURE_ANALYTICS_AI_EVENTS_MODE is secondary_percentage"- );+/// The AI overflow valve: an unset or empty+/// `CAPTURE_ANALYTICS_AI_EVENTS_OVERFLOW_TOPIC` means AI events never+/// overflow. Import mode refuses an armed valve at boot: non-AI import events+/// can't overflow because historical rerouting takes precedence no matter how+/// the deployment is configured, but nothing structural protects `$ai_*`+/// imports, so an armed valve would silently break the imports-never-overflow+/// guarantee.+fn ai_events_overflow_valve(config: &Config) -> bool {+ let armed = config+ .kafka+ .capture_analytics_ai_events_overflow_topic+ .as_deref()+ .is_some_and(|topic| !topic.is_empty());assert!(- percentage <= 100,- "invalid configuration: CAPTURE_ANALYTICS_AI_EVENTS_PERCENTAGE must be between 0 and 100 (got {percentage})"+ !(armed && matches!(config.capture_mode, CaptureMode::Import)),+ "invalid configuration: CAPTURE_ANALYTICS_AI_EVENTS_OVERFLOW_TOPIC must be unset in import mode; imports must never overflow");- percentage+ armed}/// Builds the v1 sink router. The dedicated `$ai_*` topics are@@ -674,8 +546,6 @@ async fn create_sink(kafka_handle,)))} else {- // `sink_handle` is `None` for a primary that must not gate the pod (a- // full `Secondary` cutover hands the gating handle to the secondary).let kafka_sink = KafkaSink::new(config.kafka.clone(), sink_handle).await.context("failed to start Kafka sink")?;@@ -978,6 +848,78 @@ mod tests {.expect("runtime")}+ struct AiValveInput {+ capture_mode: &'static str,+ overflow_topic: Option<&'static str>,+ }++ fn ai_valve_config(input: &AiValveInput) -> Config {+ let mut cfg_env: HashMap<String, String> = [+ ("REDIS_URL", "redis://localhost:6379/"),+ ("CAPTURE_MODE", input.capture_mode),+ ("KAFKA_HOSTS", "localhost:9092"),+ ("KAFKA_TOPIC", "events_plugin_ingestion"),+ ]+ .into_iter()+ .map(|(k, v)| (k.to_string(), v.to_string()))+ .collect();+ if let Some(topic) = input.overflow_topic {+ cfg_env.insert(+ "CAPTURE_ANALYTICS_AI_EVENTS_OVERFLOW_TOPIC".to_string(),+ topic.to_string(),+ );+ }+ envconfig::Envconfig::init_from_hashmap(&cfg_env).expect("test config")+ }++ #[rstest]+ #[case::events_set(+ AiValveInput {+ capture_mode: "events",+ overflow_topic: Some("events_plugin_ingestion_ai_overflow"),+ },+ true+ )]+ #[case::events_unset(+ AiValveInput {+ capture_mode: "events",+ overflow_topic: None,+ },+ false+ )]+ #[case::import_unset(+ AiValveInput {+ capture_mode: "import",+ overflow_topic: None,+ },+ false+ )]+ #[case::import_empty(+ AiValveInput {+ capture_mode: "import",+ overflow_topic: Some(""),+ },+ false+ )]+ fn ai_events_overflow_valve_arms_only_on_a_set_topic(+ #[case] input: AiValveInput,+ #[case] expected_armed: bool,+ ) {+ assert_eq!(+ ai_events_overflow_valve(&ai_valve_config(&input)),+ expected_armed+ );+ }++ #[test]+ #[should_panic(expected = "imports must never overflow")]+ fn ai_events_overflow_valve_rejects_armed_valve_in_import_mode() {+ ai_events_overflow_valve(&ai_valve_config(&AiValveInput {+ capture_mode: "import",+ overflow_topic: Some("events_plugin_ingestion_ai_overflow"),+ }));+ }+#[test]fn create_v1_sink_router_fails_on_invalid_config() {let cfg_env: HashMap<String, String> = [@@ -1144,44 +1086,6 @@ mod tests {assert!(!server.is_shutting_down(), "capture must still be serving");}- #[test]- #[should_panic(expected = "S3_FALLBACK_ENABLED cannot be combined with AI secondary routing")]- fn register_components_rejects_s3_fallback_with_ai_secondary() {- let cfg_env: HashMap<String, String> = [- ("REDIS_URL", "redis://localhost:6379/"),- ("CAPTURE_MODE", "ai"),- ("KAFKA_HOSTS", "localhost:9092"),- ("KAFKA_TOPIC", "events_plugin_ingestion"),- ("S3_FALLBACK_ENABLED", "true"),- ("AI_SINK_MODE", "secondary"),- ]- .into_iter()- .map(|(k, v)| (k.to_string(), v.to_string()))- .collect();- let config: Config =- envconfig::Envconfig::init_from_hashmap(&cfg_env).expect("test config");-- let mut manager = lifecycle::Manager::builder("test")- .with_trap_signals(false)- .with_prestop_check(false)- .build();- register_components(&mut manager, &config);- }-- #[test]- fn parse_token_allowlist_trims_and_drops_empties() {- // A stray space or trailing/double comma in AI_SECONDARY_ALLOWLIST_TOKENS- // must not produce a mismatched or empty token that breaks routing.- let set = super::parse_token_allowlist(" tok_a , tok_b ,,tok_c, ");- assert_eq!(set.len(), 3);- assert!(set.contains("tok_a"));- assert!(set.contains("tok_b"));- assert!(set.contains("tok_c"));- assert!(!set.contains(""));-- assert!(super::parse_token_allowlist(" , , ").is_empty());- }-/// A blank output topic makes `create_sink` refuse to boot in every capture/// mode — the misconfig fails fast at startup (via the `OutputRegistry`/// completeness check inside `KafkaSink::new`) rather than at first produce.diff --git a/rust/capture/src/sinks/kafka.rs b/rust/capture/src/sinks/kafka.rsindex 8098478449ae..e613b15cae7c 100644--- a/rust/capture/src/sinks/kafka.rs+++ b/rust/capture/src/sinks/kafka.rs@@ -40,9 +40,8 @@ use super::producer::RdKafkaProducer;pub struct KafkaContext {/// Lifecycle handle this producer reports liveness to. `None` for a producer- /// whose health must not gate the pod (e.g. the non-critical side of a- /// `SplitKafkaSink`) — it still produces and emits metrics, it just doesn't- /// drive a manager component.+ /// whose health must not gate the pod — it still produces and emits+ /// metrics, it just doesn't drive a manager component.liveness: Option<lifecycle::Handle>,}@@ -1191,7 +1190,7 @@ mod tests {kafka_replay_overflow_topic: "session_recording_snapshot_item_overflow".to_string(),kafka_dlq_topic: "events_plugin_ingestion_dlq".to_string(),outputs_completeness_check_enabled: true,- capture_analytics_ai_events_topic: None,+ capture_analytics_ai_events_topic: "events_plugin_ingestion_ai".to_string(),capture_analytics_ai_events_overflow_topic: None,kafka_traces_topic: "traces_ingestion".to_string(),kafka_metrics_topic: "metrics_ingestion".to_string(),@@ -2866,45 +2865,6 @@ mod tests {);}- #[tokio::test]- async fn ai_events_missing_topic_falls_back_to_main() {- // Should be impossible in production (startup validation), but a- // misconfigured sink must degrade to the main topic, not error.- let producer = MockKafkaProducer::new();- let mut topics = test_topics();- topics.ai_events = None;- let sink = KafkaSinkBase::with_producer(producer.clone(), topics);-- let input = EventInput {- data_type: DataType::AiEvents,- ..Default::default()- };- sink.send(create_test_event(&input)).await.unwrap();-- let records = producer.get_records();- assert_eq!(records.len(), 1);- assert_eq!(records[0].topic, MAIN_TOPIC);- assert_eq!(records[0].key.as_deref(), Some("test_token:test_user"));- }-- #[tokio::test]- async fn ai_events_empty_topic_falls_back_to_main() {- let producer = MockKafkaProducer::new();- let mut topics = test_topics();- topics.ai_events = Some(String::new());- let sink = KafkaSinkBase::with_producer(producer.clone(), topics);-- let input = EventInput {- data_type: DataType::AiEvents,- ..Default::default()- };- sink.send(create_test_event(&input)).await.unwrap();-- let records = producer.get_records();- assert_eq!(records.len(), 1);- assert_eq!(records[0].topic, MAIN_TOPIC);- }-// ==================== RedirectToTopic ====================// redirect_to_topic overrides normal routing but DLQ takes prioritydiff --git a/rust/capture/src/sinks/mod.rs b/rust/capture/src/sinks/mod.rsindex c5f4af0dd623..f6f78dd9ee72 100644--- a/rust/capture/src/sinks/mod.rs+++ b/rust/capture/src/sinks/mod.rs@@ -9,7 +9,6 @@ pub mod print;pub mod producer;pub mod registry;pub mod s3;-pub mod split;#[cfg(test)]pub(crate) mod test_sink;#[async_trait]diff --git a/rust/capture/src/sinks/registry.rs b/rust/capture/src/sinks/registry.rsindex dbedfbc74573..2d6c3d0b8bd6 100644--- a/rust/capture/src/sinks/registry.rs+++ b/rust/capture/src/sinks/registry.rs@@ -11,11 +11,8 @@//!//! Two outputs sit outside the completeness check: `Custom` topics are//! admin-supplied inline on the event's metadata (they carry their own topic),-//! and the AI outputs are opt-in — setup separately requires-//! `CAPTURE_ANALYTICS_AI_EVENTS_TOPIC` whenever the routing policy can produce-//! `AiEvents` records.--use tracing::log::warn;+//! and `AiOverflow` is the opt-in overflow valve — unset means routing never+//! selects it.use crate::config::KafkaConfig;@@ -41,9 +38,7 @@ pub enum Output {Dlq,ErrorTrackingMain,/// The AI pipeline's main lane — the dedicated `$ai_*` topic- /// (`CAPTURE_ANALYTICS_AI_EVENTS_TOPIC`). Opt-in, so not part of the- /// completeness check — setup validates it whenever the routing policy- /// can produce `AiEvents` records.+ /// (`CAPTURE_ANALYTICS_AI_EVENTS_TOPIC`).AiMain,/// The AI pipeline's overflow lane; only routed to when the AI overflow/// valve (`CAPTURE_ANALYTICS_AI_EVENTS_OVERFLOW_TOPIC`) is armed.@@ -56,7 +51,7 @@ pub enum Output {impl Output {/// Every registered always-required output. `check_complete` walks this so/// a newly added output is caught at boot rather than at first produce.- const REGISTERED: [Output; 9] = [+ const REGISTERED: [Output; 10] = [Output::AnalyticsMain,Output::AnalyticsOverflow,Output::AnalyticsHistorical,@@ -66,6 +61,7 @@ impl Output {Output::SessionReplayOverflow,Output::Dlq,Output::ErrorTrackingMain,+ Output::AiMain,];/// Whether this output participates in the boot completeness check.@@ -85,10 +81,11 @@ impl Output {| Output::SessionReplayMain| Output::SessionReplayOverflow| Output::Dlq- | Output::ErrorTrackingMain => true,- // Opt-in AI lanes (setup validates them against the routing- // mode) and per-event custom topics sit outside the check.- Output::AiMain | Output::AiOverflow | Output::Custom(_) => false,+ | Output::ErrorTrackingMain+ | Output::AiMain => true,+ // The opt-in AI overflow valve and per-event custom topics sit+ // outside the check.+ Output::AiOverflow | Output::Custom(_) => false,}}@@ -124,10 +121,9 @@ pub struct OutputRegistry {pub(crate) replay_overflow: String,pub(crate) dlq: String,pub(crate) error_tracking: String,- /// Dedicated topic for `Output::AiMain`. Optional because the AI lane- /// is opt-in: startup validation guarantees it is set whenever the routing- /// policy can produce `AiEvents` records.- pub(crate) ai_events: Option<String>,+ /// Dedicated topic for `Output::AiMain` (`CAPTURE_ANALYTICS_AI_EVENTS_TOPIC`,+ /// required with a default).+ pub(crate) ai_events: String,/// Overflow topic for the AI lane. Unset means the AI overflow valve is/// unarmed and routing never selects `Output::AiOverflow`.pub(crate) ai_events_overflow: Option<String>,@@ -136,11 +132,6 @@ pub struct OutputRegistry {impl OutputRegistry {/// Resolve an output to its topic. Fixed outputs read the registered topic;/// `Custom` returns its inline, admin-supplied topic.- ///- /// An unset AI topic should be impossible for a reachable AI output- /// (startup validation requires `CAPTURE_ANALYTICS_AI_EVENTS_TOPIC`- /// whenever the routing policy can produce `AiEvents`), so it falls back- /// to the main topic rather than failing the batch.pub fn topic_for<'a>(&'a self, output: &'a Output) -> &'a str {match output {Output::AnalyticsMain | Output::SessionReplayMain => &self.main,@@ -151,12 +142,12 @@ impl OutputRegistry {Output::SessionReplayOverflow => &self.replay_overflow,Output::Dlq => &self.dlq,Output::ErrorTrackingMain => &self.error_tracking,- Output::AiMain => self.ai_events_topic_or_fallback(),+ Output::AiMain => &self.ai_events,Output::AiOverflow => match self.ai_events_overflow.as_deref() {Some(topic) if !topic.is_empty() => topic,// Unreachable: routing only selects this output when the// valve is armed, i.e. exactly when the topic is set.- _ => self.ai_events_topic_or_fallback(),+ _ => &self.ai_events,},Output::Custom(topic) => topic,}@@ -170,22 +161,11 @@ impl OutputRegistry {.is_some_and(|t| !t.is_empty())}- fn ai_events_topic_or_fallback(&self) -> &str {- match self.ai_events.as_deref() {- Some(topic) if !topic.is_empty() => topic,- _ => {- warn!(- "CAPTURE_ANALYTICS_AI_EVENTS_TOPIC not configured for an AiEvents record; falling back to main topic"- );- &self.main- }- }- }-/// Startup completeness check: every registered output must resolve to a/// non-empty topic, so a misconfigured or newly-added-but-unwired output- /// fails fast at boot instead of at first produce. `Custom` is excluded (it carries its own topic per event), as- /// are the opt-in AI outputs (validated by setup against the routing mode).+ /// fails fast at boot instead of at first produce. `Custom` is excluded+ /// (it carries its own topic per event), as is the opt-in `AiOverflow`+ /// valve (unset means routing never selects it).pub fn check_complete(&self) -> anyhow::Result<()> {for output in &Output::REGISTERED {anyhow::ensure!(@@ -230,7 +210,7 @@ pub(crate) fn test_topics() -> OutputRegistry {replay_overflow: "replay_overflow".to_string(),dlq: "events_plugin_ingestion_dlq".to_string(),error_tracking: "error_tracking_events".to_string(),- ai_events: Some("ai_events".to_string()),+ ai_events: "ai_events".to_string(),ai_events_overflow: Some("ai_events_overflow".to_string()),}}@@ -265,23 +245,15 @@ mod tests {);}- /// Unset AI topics carry no completeness requirement (they are opt-in) and- /// degrade to the main topic instead of failing the batch.+ /// An unarmed overflow valve carries no completeness requirement and never+ /// disarms the AI main lane.#[test]- fn unset_ai_outputs_fall_back_to_main() {+ fn unset_ai_overflow_valve_is_unarmed() {let mut registry = test_topics();- registry.ai_events = None;registry.ai_events_overflow = None;assert!(registry.check_complete().is_ok());assert!(!registry.ai_events_overflow_armed());- assert_eq!(- registry.topic_for(&Output::AiMain),- "events_plugin_ingestion"- );- assert_eq!(- registry.topic_for(&Output::AiOverflow),- "events_plugin_ingestion"- );+ assert_eq!(registry.topic_for(&Output::AiMain), "ai_events");}#[test]@@ -331,6 +303,7 @@ mod tests {#[case("sessionreplay-overflow", |r: &mut OutputRegistry| r.replay_overflow.clear())]#[case("dlq", |r: &mut OutputRegistry| r.dlq.clear())]#[case("errortracking-main", |r: &mut OutputRegistry| r.error_tracking.clear())]+ #[case("ai-main", |r: &mut OutputRegistry| r.ai_events.clear())]fn check_complete_rejects_empty_topic(#[case] output_name: &str,#[case] blank: fn(&mut OutputRegistry),diff --git a/rust/capture/src/sinks/split.rs b/rust/capture/src/sinks/split.rsdeleted file mode 100644index 72a11baa58a6..000000000000--- a/rust/capture/src/sinks/split.rs+++ /dev/null@@ -1,195 +0,0 @@-//! Split sink: routes each AI capture event to either the primary or a-//! secondary sink based on the configured `AiSinkMode` (and token allowlist).-//!-//! Composes two `Event` sinks behind the `Event` trait — the same pattern as-//! `FallbackSink` — but selects a destination per event instead of failing-//! over. Used to migrate AI ingestion to a secondary cluster (e.g. WarpStream)-//! gradually: allowlist a few tokens, then cut everything over. The routing-//! policy lives in `AiSinkMode::routes_to_secondary`; this sink only dispatches.--use std::sync::Arc;--use async_trait::async_trait;-use metrics::counter;--use crate::api::CaptureError;-use crate::config::AiRouting;-use crate::sinks::Event;-use crate::v0_request::ProcessedEvent;--/// Routes events between a primary and secondary sink per the `AiRouting` policy.-pub struct SplitKafkaSink {- primary: Arc<dyn Event + Send + Sync>,- secondary: Arc<dyn Event + Send + Sync>,- routing: AiRouting,-}--impl SplitKafkaSink {- pub fn new(- primary: Arc<dyn Event + Send + Sync>,- secondary: Arc<dyn Event + Send + Sync>,- routing: AiRouting,- ) -> Self {- Self {- primary,- secondary,- routing,- }- }-- fn routes_to_secondary(&self, event: &ProcessedEvent) -> bool {- self.routing.routes_to_secondary(&event.event.token)- }-}--#[async_trait]-impl Event for SplitKafkaSink {- async fn send(&self, event: ProcessedEvent) -> Result<(), CaptureError> {- if self.routes_to_secondary(&event) {- counter!("capture_split_sink_selected", "cluster" => "secondary").increment(1);- self.secondary.send(event).await- } else {- counter!("capture_split_sink_selected", "cluster" => "primary").increment(1);- self.primary.send(event).await- }- }-- async fn send_batch(&self, events: Vec<ProcessedEvent>) -> Result<(), CaptureError> {- // Partition by destination, preserving per-destination order. The common- // case (every event routes the same way — e.g. a single-token batch in- // full-secondary mode) leaves one Vec empty and forwards the other whole.- let mut primary: Vec<ProcessedEvent> = Vec::new();- let mut secondary: Vec<ProcessedEvent> = Vec::new();- for event in events {- if self.routes_to_secondary(&event) {- secondary.push(event);- } else {- primary.push(event);- }- }-- counter!("capture_split_sink_selected", "cluster" => "primary")- .increment(primary.len() as u64);- counter!("capture_split_sink_selected", "cluster" => "secondary")- .increment(secondary.len() as u64);-- // A batch is built from a single request, so every event carries the- // same request-level token (see `events::analytics` / `otel`). Routing is- // token-based, so today one of these partitions is always empty and the- // whole batch goes to a single cluster — the both-non-empty arm below is- // defensive against a future multi-token batch path, not a hot path.- match (primary.is_empty(), secondary.is_empty()) {- (false, true) => self.primary.send_batch(primary).await,- (true, false) => self.secondary.send_batch(secondary).await,- (false, false) => {- // Cross-destination ordering is irrelevant (separate clusters);- // send concurrently and fail if either fails. Caveat for the day- // this arm goes live: failing the whole batch makes the caller- // retry both partitions, duplicating events the healthy cluster- // already accepted. Avoiding that needs partial-batch retry, which- // the `Event` contract (one Result per batch) can't express.- let (p, s) = tokio::join!(- self.primary.send_batch(primary),- self.secondary.send_batch(secondary),- );- p.and(s)- }- (true, true) => Ok(()),- }- }-- fn flush(&self) -> Result<(), anyhow::Error> {- self.primary.flush()?;- self.secondary.flush()?;- Ok(())- }-}--#[cfg(test)]-mod tests {- use super::*;- use crate::sinks::test_sink::MockSink;- use crate::utils::uuid_v7_from_datetime;- use crate::v0_request::{DataType, ProcessedEventMetadata};- use common_types::CapturedEvent;-- fn event_with_token(token: &str) -> ProcessedEvent {- let timestamp = chrono::Utc::now();- ProcessedEvent {- event: CapturedEvent {- uuid: uuid_v7_from_datetime(timestamp),- distinct_id: "did".to_string(),- session_id: None,- ip: "127.0.0.1".to_string(),- data: "{}".to_string(),- now: "2024-01-01T00:00:00Z".to_string(),- sent_at: None,- token: token.to_string(),- event: "$ai_generation".to_string(),- timestamp,- is_cookieless_mode: false,- historical_migration: false,- },- metadata: ProcessedEventMetadata {- data_type: DataType::AnalyticsMain,- session_id: None,- computed_timestamp: None,- event_name: "$ai_generation".to_string(),- force_overflow: false,- skip_person_processing: false,- redirect_to_dlq: false,- redirect_to_topic: None,- skip_heatmap_processing: false,- overflow_reason: None,- distinct_id_truncated_from: None,- },- }- }-- fn split_sink(allowed: &[&str]) -> (SplitKafkaSink, MockSink, MockSink) {- let primary = MockSink::new();- let secondary = MockSink::new();- let allowlist = allowed.iter().map(|s| s.to_string()).collect();- let sink = SplitKafkaSink::new(- Arc::new(primary.clone()),- Arc::new(secondary.clone()),- AiRouting::SecondaryAllowlist(allowlist),- );- (sink, primary, secondary)- }-- fn tokens(sink: &MockSink) -> Vec<String> {- sink.get_events()- .iter()- .map(|e| e.event.token.clone())- .collect()- }-- #[tokio::test]- async fn routes_single_event_by_allowlist() {- let (sink, primary, secondary) = split_sink(&["secondary_tok"]);-- sink.send(event_with_token("secondary_tok")).await.unwrap();- sink.send(event_with_token("other")).await.unwrap();-- assert_eq!(tokens(&secondary), vec!["secondary_tok"]);- assert_eq!(tokens(&primary), vec!["other"]);- }-- #[tokio::test]- async fn batch_partitions_across_sinks_preserving_order() {- let (sink, primary, secondary) = split_sink(&["sec_1", "sec_2"]);-- sink.send_batch(vec![- event_with_token("sec_1"),- event_with_token("pri_1"),- event_with_token("sec_2"),- event_with_token("pri_2"),- ])- .await- .unwrap();-- assert_eq!(tokens(&secondary), vec!["sec_1", "sec_2"]);- assert_eq!(tokens(&primary), vec!["pri_1", "pri_2"]);- }-}diff --git a/rust/capture/src/v0_endpoint.rs b/rust/capture/src/v0_endpoint.rsindex e7252ec145bf..82dd40ccac1c 100644--- a/rust/capture/src/v0_endpoint.rs+++ b/rust/capture/src/v0_endpoint.rs@@ -69,7 +69,6 @@ pub async fn event(state.overflow_limiter.clone(),state.ai_events_overflow_limiter.clone(),state.ingestion_warning_emitter.clone(),- &state.ai_routing,events,&context,)diff --git a/rust/capture/src/v0_request.rs b/rust/capture/src/v0_request.rsindex a3bec95d8706..6bd332e767f2 100644--- a/rust/capture/src/v0_request.rs+++ b/rust/capture/src/v0_request.rs@@ -178,9 +178,10 @@ pub enum DataType {ExceptionErrorTracking,SnapshotMain,/// Dedicated `$ai_*` lane, mirroring v1's `Destination::AiEvents`. Only- /// produced when the deployment's `AiRouting` policy diverts the batch- /// token; the kafka sink maps it to `CAPTURE_ANALYTICS_AI_EVENTS_TOPIC`. Like heatmaps and- /// exceptions, AI events never overflow and never reroute historical.+ /// produced on deployments whose capture mode routes AI events (see+ /// `CaptureMode::routes_ai_events`); the kafka sink maps it to+ /// `CAPTURE_ANALYTICS_AI_EVENTS_TOPIC`. Like heatmaps and exceptions, AI events never+ /// reroute historical.AiEvents,}@@ -216,12 +217,11 @@ impl DataType {/// `apply_restrictions` so the analytics → exception → heatmap →/// ingestion-warning split stays in one place.///- /// `route_ai_events` reflects the per-batch `AiRouting` decision,+ /// `route_ai_events` reflects the deployment's `CaptureMode::routes_ai_events`,/// mirroring v1's `destination_for_event_name`: when set, AI events (per/// [`is_ai_event`]) divert to `AiEvents`, winning over historical (in v1/// the historical reroute only applies to the analytics-main destination).- /// When unset the mapping is a strict no-op relative to the pre-AI-lane- /// behavior.+ /// When unset the mapping keeps AI events on the main/historical lanes.////// `SnapshotMain` is not produced here — replay events arrive on a/// separate endpoint and never flow through analytics processing.diff --git a/rust/capture/src/v1/analytics/process.rs b/rust/capture/src/v1/analytics/process.rsindex 3cc954f59f01..ff6dbd1ed8b6 100644--- a/rust/capture/src/v1/analytics/process.rs+++ b/rust/capture/src/v1/analytics/process.rs@@ -43,11 +43,10 @@ use common_ingestion_warnings::{/// (extractHeatmapDataStep) handles extraction when `skip_heatmap_processing` is unset/// in Kafka headers — removing that fallback would break scroll-depth heatmaps for v1.///-/// When `route_ai_events` is set (this batch's token routes to the AI topic-/// per the configured `AiRouting` policy: mode plus token allowlist), AI events-/// (per [`is_ai_event`]) are diverted to `Destination::AiEvents`; otherwise they-/// fall through to `AnalyticsMain` exactly as before, so an unconfigured AI-/// topic or `primary` mode is a strict no-op.+/// When `route_ai_events` is set (the deployment's capture mode routes AI+/// events, see `CaptureMode::routes_ai_events`), AI events (per+/// [`is_ai_event`]) are diverted to `Destination::AiEvents`; otherwise they+/// fall through to `AnalyticsMain`.fn destination_for_event_name(name: &str, route_ai_events: bool) -> Destination {match name {"$exception" => Destination::ExceptionErrorTracking,@@ -73,8 +72,8 @@ pub async fn process_batch(}context.set_batch_metadata(&batch);- // A batch carries a single token, so the AI routing decision is per batch.- let route_ai_events = state.ai_routing.routes_to_secondary(&context.api_token);+ // Whether `$ai_*` events divert to the AI lane is a deployment property.+ let route_ai_events = state.capture_mode.routes_ai_events();let mut events = match validate_events(context, batch, route_ai_events) {Ok(events) => events,Err(err) => {@@ -3623,22 +3622,11 @@ mod tests {});}- /// process_batch wiring: the AI routing decision is derived once per batch- /// from the request token, so with a `SecondaryAllowlist` policy the same- /// `$ai_*` event lands on the AI topic only when the batch token is listed.- #[rstest::rstest]- #[case("phc_allowlisted", "ai_events")]- #[case("phc_other", "events_main")]+ /// process_batch wiring: an `$ai_*` event lands on the AI topic.#[tokio::test]- async fn process_batch_gates_ai_topic_on_batch_token(- #[case] token: &str,- #[case] expected_topic: &str,- ) {- let allowlist: HashSet<String> = ["phc_allowlisted".to_string()].into_iter().collect();- let ts = TestStateBuilder::new()- .with_ai_routing(crate::config::AiRouting::SecondaryAllowlist(allowlist))- .build();- let mut ctx = gateway_context(token, Utc::now(), None);+ async fn process_batch_routes_ai_events_to_ai_topic() {+ let ts = TestStateBuilder::new().build();+ let mut ctx = gateway_context("phc_test_token", Utc::now(), None);let batch = valid_batch(vec![Event {event: "$ai_generation".to_string(),..valid_event()@@ -3648,7 +3636,7 @@ mod tests {ts.mock_producer.with_records(|records| {assert_eq!(records.len(), 1, "the event must be published");- assert_eq!(records[0].topic, expected_topic);+ assert_eq!(records[0].topic, "ai_events");});}@@ -3661,7 +3649,6 @@ mod tests {#[tokio::test]async fn process_batch_routes_ai_overflow_with_only_ai_limiter_armed() {let ts = TestStateBuilder::new()- .with_ai_routing(crate::config::AiRouting::Secondary).with_ai_events_overflow_limiter(1, 1).build();let mut ctx = test_utils::test_analytics_context();@@ -3990,13 +3977,14 @@ mod tests {#[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.+ // Import's no-overflow guarantee on the v1 path. Non-AI events in a+ // historical batch reroute to AnalyticsHistorical before overflow+ // stamping (which only touches AnalyticsMain), and $ai_* events divert+ // to the AI lane, which cannot stamp overflow while the AI overflow+ // valve is unset — the capture-import config. 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 overflow lane.let ts = TestStateBuilder::new().with_capture_mode(crate::config::CaptureMode::Import).with_overflow_limiter(1, 1)@@ -4019,33 +4007,29 @@ mod tests {ts.mock_producer.with_records(|records| {assert_eq!(records.len(), 3, "all three historical events must publish");for r in records {+ let expected = if r.payload.contains("$ai_generation") {+ "ai_events"+ } else {+ "events_hist"+ };assert_eq!(- r.topic, "events_hist",- "Import must route every event to the historical topic, got {}",- r.topic,+ r.topic, expected,+ "unexpected lane for a historical import event",);}});}- #[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.+ async fn import_mode_routes_ai_events_to_ai_lane() {+ // A historical batch's $ai_* event diverts to the AI lane, winning+ // over historical: only the AI lane has AI processing (cost+ // enrichment, the ai_events double-write), so leaving it on the+ // historical lane would import it incorrectly. Import's no-overflow+ // guarantee holds by config: capture-import leaves the AI overflow+ // valve unset, and an unarmed valve never stamps overflow.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 {@@ -4057,7 +4041,7 @@ mod tests {ts.mock_producer.with_records(|records| {assert_eq!(records.len(), 1);- assert_eq!(records[0].topic, expected_topic);+ assert_eq!(records[0].topic, "ai_events");});}diff --git a/rust/capture/src/v1/quota_limiter_shim.rs b/rust/capture/src/v1/quota_limiter_shim.rsindex 082f1bd8e624..7ae9c42c0e3c 100644--- a/rust/capture/src/v1/quota_limiter_shim.rs+++ b/rust/capture/src/v1/quota_limiter_shim.rs@@ -172,7 +172,7 @@ mod tests {kafka_replay_overflow_topic: "session_recording_snapshot_item_overflow".to_string(),kafka_dlq_topic: "events_plugin_ingestion_dlq".to_string(),outputs_completeness_check_enabled: true,- capture_analytics_ai_events_topic: None,+ capture_analytics_ai_events_topic: "events_plugin_ingestion_ai".to_string(),capture_analytics_ai_events_overflow_topic: None,kafka_traces_topic: "ingestion_traces".to_string(),kafka_metrics_topic: "ingestion_metrics".to_string(),@@ -239,15 +239,6 @@ mod tests {ai_s3_access_key_id: None,ai_s3_secret_access_key: None,ai_gateway_signing_secret: None,- ai_sink_mode: crate::config::AiSinkMode::Primary,- ai_secondary_allowlist_tokens: None,- ai_secondary_kafka_hosts: None,- ai_secondary_kafka_topic: None,- ai_secondary_kafka_tls: false,- ai_secondary_kafka_client_id: String::new(),- capture_analytics_ai_events_mode: crate::config::AiSinkMode::Primary,- capture_analytics_ai_events_allowlist_tokens: None,- capture_analytics_ai_events_percentage: None,http1_header_read_timeout_ms: Some(5000),body_chunk_read_timeout_ms: None,body_read_chunk_size_kb: 256,diff --git a/rust/capture/src/v1/sinks/kafka/config.rs b/rust/capture/src/v1/sinks/kafka/config.rsindex acfd1d027a32..7ddadd025063 100644--- a/rust/capture/src/v1/sinks/kafka/config.rs+++ b/rust/capture/src/v1/sinks/kafka/config.rs@@ -105,10 +105,11 @@ pub struct Config {pub topic_heatmap: String,pub topic_client_ingestion_warning: String,- /// Optional dedicated topic for `$ai_*` events. Not meant to be set via- /// per-sink env: setup injects the deployment-level `CAPTURE_ANALYTICS_AI_EVENTS_TOPIC` into+ /// Dedicated topic for `$ai_*` events. Not meant to be set via per-sink+ /// env: setup injects the deployment-level `CAPTURE_ANALYTICS_AI_EVENTS_TOPIC` into/// every sink config, overwriting whatever the env parse produced.- pub topic_ai: Option<String>,+ #[envconfig(default = "events_plugin_ingestion_ai")]+ pub topic_ai: String,/// Optional overflow topic for the AI lane. Like `topic_ai`, injected at/// setup from the deployment-level `CAPTURE_ANALYTICS_AI_EVENTS_OVERFLOW_TOPIC`; unset@@ -168,7 +169,7 @@ impl Config {Destination::ExceptionErrorTracking => Some(&self.topic_exception),Destination::HeatmapMain => Some(&self.topic_heatmap),Destination::ClientIngestionWarning => Some(&self.topic_client_ingestion_warning),- Destination::AiEvents => self.topic_ai.as_deref(),+ Destination::AiEvents => Some(&self.topic_ai),Destination::AiEventsOverflow => self.topic_ai_overflow.as_deref(),Destination::Custom(t) => Some(t.as_str()),Destination::Drop => None,@@ -401,10 +402,13 @@ mod tests {}#[test]- fn topic_ai_absent_defaults_to_none() {+ fn topic_ai_defaults() {let cfg = Config::init_from_hashmap(&required_kafka_env()).unwrap();- assert_eq!(cfg.topic_ai, None);- assert_eq!(cfg.topic_for(&Destination::AiEvents), None);+ assert_eq!(cfg.topic_ai, "events_plugin_ingestion_ai");+ assert_eq!(+ cfg.topic_for(&Destination::AiEvents),+ Some("events_plugin_ingestion_ai")+ );assert_eq!(cfg.topic_ai_overflow, None);assert_eq!(cfg.topic_for(&Destination::AiEventsOverflow), None);}@@ -426,7 +430,7 @@ mod tests {// Set the field directly, mirroring how setup injects CAPTURE_ANALYTICS_AI_EVENTS_TOPIC// into sink configs after env loading.let mut cfg = Config::init_from_hashmap(&required_kafka_env()).unwrap();- cfg.topic_ai = Some("ai_events".to_string());+ cfg.topic_ai = "ai_events".to_string();assert_eq!(cfg.topic_for(&Destination::AiEvents), Some("ai_events"));}}diff --git a/rust/capture/src/v1/test_utils.rs b/rust/capture/src/v1/test_utils.rsindex c6c83feaab3b..63bda6c7420f 100644--- a/rust/capture/src/v1/test_utils.rs+++ b/rust/capture/src/v1/test_utils.rs@@ -186,7 +186,7 @@ pub fn test_kafka_config() -> crate::v1::sinks::kafka::config::Config {// Mirrors production, where setup injects the deployment-level// CAPTURE_ANALYTICS_AI_EVENTS_TOPIC and CAPTURE_ANALYTICS_AI_EVENTS_OVERFLOW_TOPIC into every sink config// after env loading.- cfg.topic_ai = Some("ai_events".to_string());+ cfg.topic_ai = "ai_events".to_string();cfg.topic_ai_overflow = Some("ai_events_overflow".to_string());cfg}@@ -703,7 +703,6 @@ pub struct TestStateBuilder {global_rate_limiter: Option<Arc<GlobalRateLimiter>>,mock_producer: Option<Arc<MockProducer>>,ai_gateway_signing_secret: Option<String>,- ai_routing: crate::config::AiRouting,ingestion_warning_emitter: Option<Arc<dyn common_ingestion_warnings::WarningEmitter>>,capture_mode: CaptureMode,}@@ -727,18 +726,11 @@ impl TestStateBuilder {global_rate_limiter: None,mock_producer: None,ai_gateway_signing_secret: None,- ai_routing: crate::config::AiRouting::Primary,ingestion_warning_emitter: None,capture_mode: CaptureMode::Events,}}- /// Set the `$ai_*` topic routing policy (defaults to `Primary`: no diversion).- pub fn with_ai_routing(mut self, routing: crate::config::AiRouting) -> Self {- self.ai_routing = routing;- self- }-/// Configure quota limiter to reject all events for any token.pub fn with_quota_limited(mut self) -> Self {self.quota_limited = true;@@ -944,7 +936,6 @@ impl TestStateBuilder {v1_sink_router: Some(Arc::new(v1_router)),capture_v1_scatter_gather_min_batch: 8,ai_gateway_signing_secret: self.ai_gateway_signing_secret,- ai_routing: self.ai_routing,ai_events_overflow_enabled,ingestion_warning_emitter: self.ingestion_warning_emitter,capture_mode: self.capture_mode,diff --git a/rust/capture/tests/common/integration_utils.rs b/rust/capture/tests/common/integration_utils.rsindex a3e44ca1fdf2..4091314e2033 100644--- a/rust/capture/tests/common/integration_utils.rs+++ b/rust/capture/tests/common/integration_utils.rs@@ -7,7 +7,7 @@ use std::time::Duration;use capture::{api::{CaptureError, CaptureResponse, CaptureResponseCode},- config::{AiRouting, CaptureMode},+ config::CaptureMode,quota_limiters::CaptureQuotaLimiter,router::router,sinks::Event,@@ -1109,21 +1109,20 @@ fn build_router_for_mode_at(mode: CaptureMode, fixed_time: &str) -> (Router, Memhistorical_rerouting_threshold_days,is_mirror_deploy,verbose_sample_percent,- 26_214_400, // 25MB default for AI endpoint- None, // ai_blob_storage- None, // body_chunk_read_timeout_ms- 256, // body_read_chunk_size_kb- 10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes- 50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytes- None, // overflow_limiter- None, // ai_events_overflow_limiter- None, // replay_overflow_limiter- None, // v1_sink_router- 8, // capture_v1_scatter_gather_min_batch- None, // ai_gateway_signing_secret- AiRouting::Primary, // ai_routing- false, // ai_events_overflow_enabled- None, // ingestion_warning_emitter+ 26_214_400, // 25MB default for AI endpoint+ None, // ai_blob_storage+ None, // body_chunk_read_timeout_ms+ 256, // body_read_chunk_size_kb+ 10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes+ 50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytes+ None, // overflow_limiter+ None, // ai_events_overflow_limiter+ None, // replay_overflow_limiter+ None, // v1_sink_router+ 8, // capture_v1_scatter_gather_min_batch+ None, // ai_gateway_signing_secret+ false, // ai_events_overflow_enabled+ None, // ingestion_warning_emitter),sink,)diff --git a/rust/capture/tests/common/utils.rs b/rust/capture/tests/common/utils.rsindex 2a7cfcaea8c0..94f5b6af11f5 100644--- a/rust/capture/tests/common/utils.rs+++ b/rust/capture/tests/common/utils.rs@@ -88,7 +88,7 @@ pub static DEFAULT_CONFIG: Lazy<Config> = Lazy::new(|| Config {kafka_replay_overflow_topic: "session_recording_snapshot_item_overflow".to_string(),kafka_dlq_topic: "events_plugin_ingestion_dlq".to_string(),outputs_completeness_check_enabled: true,- capture_analytics_ai_events_topic: None,+ capture_analytics_ai_events_topic: "events_plugin_ingestion_ai".to_string(),capture_analytics_ai_events_overflow_topic: None,kafka_traces_topic: "ingestion_traces".to_string(),kafka_metrics_topic: "ingestion_metrics".to_string(),@@ -155,15 +155,6 @@ pub static DEFAULT_CONFIG: Lazy<Config> = Lazy::new(|| Config {ai_s3_access_key_id: None,ai_s3_secret_access_key: None,ai_gateway_signing_secret: None,- ai_sink_mode: capture::config::AiSinkMode::Primary,- ai_secondary_allowlist_tokens: None,- ai_secondary_kafka_hosts: None,- ai_secondary_kafka_topic: None,- ai_secondary_kafka_tls: false,- ai_secondary_kafka_client_id: String::new(),- capture_analytics_ai_events_mode: capture::config::AiSinkMode::Primary,- capture_analytics_ai_events_allowlist_tokens: None,- capture_analytics_ai_events_percentage: None,http1_header_read_timeout_ms: Some(5000), // 5 seconds defaultbody_chunk_read_timeout_ms: None, // disabled by default in testsbody_read_chunk_size_kb: 256, // 256KB default@@ -311,6 +302,9 @@ impl ServerHandle {let mut config = DEFAULT_CONFIG.clone();config.capture_v1_sinks = "msk".to_string();config.ai_gateway_signing_secret = Some(secret.to_string());+ // The gateway tests send `$ai_*` events, which route to the AI topic;+ // point it at the same ephemeral topic so the consumer sees them.+ config.kafka.capture_analytics_ai_events_topic = topic.topic_name().to_string();let sink_env = v1_sink_env_for_topic("msk", topic.topic_name());Self::for_config_with_sink_env(config, sink_env).await}diff --git a/rust/capture/tests/integration_ai_endpoint.rs b/rust/capture/tests/integration_ai_endpoint.rsindex 5858b70d550c..7ec983f4d2ed 100644--- a/rust/capture/tests/integration_ai_endpoint.rs+++ b/rust/capture/tests/integration_ai_endpoint.rs@@ -7,7 +7,7 @@ use axum::Router;use axum_test_helper::TestClient;use capture::ai_s3::{BlobStorage, MockBlobStorage};use capture::api::CaptureError;-use capture::config::{AiRouting, CaptureMode};+use capture::config::CaptureMode;use capture::quota_limiters::CaptureQuotaLimiter;use capture::router::router;use capture::sinks::Event;@@ -199,7 +199,6 @@ fn setup_ai_test_router() -> Router {None, // v1_sink_router8, // capture_v1_scatter_gather_min_batchNone, // ai_gateway_signing_secret- AiRouting::Primary, // ai_routingfalse, // ai_events_overflow_enabledNone, // ingestion_warning_emitter)@@ -256,7 +255,6 @@ fn setup_ai_router_collecting_warnings() -> (Router, Arc<CollectingEmitter>) {None,8,None,- AiRouting::Primary,false,warning_emitter,);@@ -1724,7 +1722,6 @@ fn setup_ai_test_router_with_capturing_sink() -> (Router, CapturingSink) {None, // v1_sink_router8, // capture_v1_scatter_gather_min_batchNone, // ai_gateway_signing_secret- AiRouting::Primary, // ai_routingfalse, // ai_events_overflow_enabledNone, // ingestion_warning_emitter);@@ -2642,7 +2639,6 @@ fn setup_ai_test_router_with_token_dropper(token_dropper: TokenDropper) -> (RoutNone, // v1_sink_router8, // capture_v1_scatter_gather_min_batchNone, // ai_gateway_signing_secret- AiRouting::Primary, // ai_routingfalse, // ai_events_overflow_enabledNone, // ingestion_warning_emitter);@@ -2855,7 +2851,6 @@ fn setup_ai_test_router_with_llm_quota_limited(token: &str) -> (Router, CapturinNone, // v1_sink_router8, // capture_v1_scatter_gather_min_batchNone, // ai_gateway_signing_secret- AiRouting::Primary, // ai_routingfalse, // ai_events_overflow_enabledNone, // ingestion_warning_emitter);@@ -3008,14 +3003,13 @@ fn setup_ai_test_router_with_overflow_limiter(10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytesSome(overflow_limiter),- None, // ai_events_overflow_limiter- None, // replay_overflow_limiter- None, // v1_sink_router- 8, // capture_v1_scatter_gather_min_batch- None, // ai_gateway_signing_secret- AiRouting::Primary, // ai_routing- false, // ai_events_overflow_enabled- None, // ingestion_warning_emitter+ None, // ai_events_overflow_limiter+ None, // replay_overflow_limiter+ None, // v1_sink_router+ 8, // capture_v1_scatter_gather_min_batch+ None, // ai_gateway_signing_secret+ false, // ai_events_overflow_enabled+ None, // ingestion_warning_emitter);(router, sink_clone)@@ -3155,9 +3149,8 @@ fn ai_router(None,8,Some(GW_SECRET.to_string()),- AiRouting::Primary, // ai_routing- false, // ai_events_overflow_enabled- None, // ingestion_warning_emitter+ false, // ai_events_overflow_enabled+ None, // ingestion_warning_emitter);(router, sink_clone)}diff --git a/rust/capture/tests/integration_ai_restrictions.rs b/rust/capture/tests/integration_ai_restrictions.rsindex d009b678bd1f..5d6a0f07561c 100644--- a/rust/capture/tests/integration_ai_restrictions.rs+++ b/rust/capture/tests/integration_ai_restrictions.rs@@ -7,7 +7,7 @@ use axum::Router;use axum_test_helper::TestClient;use capture::ai_s3::{BlobStorage, MockBlobStorage};use capture::api::CaptureError;-use capture::config::{AiRouting, CaptureMode};+use capture::config::CaptureMode;use capture::event_restrictions::{EventRestrictionService, Pipeline, Restriction, RestrictionManager, RestrictionScope,RestrictionType,@@ -186,18 +186,17 @@ async fn setup_ai_router_with_restriction(26_214_400,Some(create_mock_blob_storage()),None,- 256, // body_read_chunk_size_kb- 10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes- 50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytes- None, // overflow_limiter- None, // ai_events_overflow_limiter- None, // replay_overflow_limiter- None, // v1_sink_router- 8, // capture_v1_scatter_gather_min_batch- None, // ai_gateway_signing_secret- AiRouting::Primary, // ai_routing- false, // ai_events_overflow_enabled- None, // ingestion_warning_emitter+ 256, // body_read_chunk_size_kb+ 10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes+ 50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytes+ None, // overflow_limiter+ None, // ai_events_overflow_limiter+ None, // replay_overflow_limiter+ None, // v1_sink_router+ 8, // capture_v1_scatter_gather_min_batch+ None, // ai_gateway_signing_secret+ false, // ai_events_overflow_enabled+ None, // ingestion_warning_emitter);(router, sink_clone)@@ -508,18 +507,17 @@ async fn setup_ai_router_with_redirect_to_topic(26_214_400,Some(create_mock_blob_storage()),None,- 256, // body_read_chunk_size_kb- 10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes- 50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytes- None, // overflow_limiter- None, // ai_events_overflow_limiter- None, // replay_overflow_limiter- None, // v1_sink_router- 8, // capture_v1_scatter_gather_min_batch- None, // ai_gateway_signing_secret- AiRouting::Primary, // ai_routing- false, // ai_events_overflow_enabled- None, // ingestion_warning_emitter+ 256, // body_read_chunk_size_kb+ 10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes+ 50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytes+ None, // overflow_limiter+ None, // ai_events_overflow_limiter+ None, // replay_overflow_limiter+ None, // v1_sink_router+ 8, // capture_v1_scatter_gather_min_batch+ None, // ai_gateway_signing_secret+ false, // ai_events_overflow_enabled+ None, // ingestion_warning_emitter);(router, sink_clone)@@ -534,7 +532,6 @@ async fn setup_ai_router_with_redirect_to_topic(async fn setup_ai_router_with_force_overflow_and_limiter(token: &str,overflow_limiter: Arc<OverflowLimiter>,- ai_routing: AiRouting,ai_events_overflow_enabled: bool,) -> (Router, CapturingSink) {let (readiness, liveness, _monitor) = test_lifecycle_handlers();@@ -598,7 +595,6 @@ async fn setup_ai_router_with_force_overflow_and_limiter(None, // v1_sink_router8, // capture_v1_scatter_gather_min_batchNone, // ai_gateway_signing_secret- ai_routing,ai_events_overflow_enabled,None, // ingestion_warning_emitter);@@ -625,13 +621,9 @@ async fn test_ai_force_overflow_restriction_wins_over_overflow_limiter() {true, // preserve_locality));- let (router, sink) = setup_ai_router_with_force_overflow_and_limiter(- restricted_token,- overflow_limiter,- AiRouting::Primary,- false,- )- .await;+ let (router, sink) =+ setup_ai_router_with_force_overflow_and_limiter(restricted_token, overflow_limiter, false)+ .await;let test_client = TestClient::new(router);let properties = json!({"$ai_model": "gpt-4"});@@ -666,14 +658,12 @@ async fn test_ai_force_overflow_restriction_wins_over_overflow_limiter() {}#[tokio::test]-async fn test_ai_endpoint_ignores_analytics_ai_routing_config() {- // Deployment-config cross-contamination guard: the CAPTURE_ANALYTICS_AI_EVENTS_*- // family configures $ai_* routing on capture-analytics deployments. If it- // leaks onto a capture-ai deployment (whose main topic already IS the AI- // topic), the AI endpoint must behave exactly as without it: events stay- // on the AnalyticsMain lane and the OverflowLimiter applies by analytics- // rules. Catches a regression that types AI-endpoint events as- // DataType::AiEvents or gates their overflow on the analytics valve.+async fn test_ai_endpoint_keeps_events_on_analytics_main() {+ // The AI endpoint's events are typed at the handler, not by the analytics+ // $ai_* lane assignment: they stay on the AnalyticsMain lane and the+ // OverflowLimiter applies by analytics rules. Catches a regression that+ // types AI-endpoint events as DataType::AiEvents or gates their overflow+ // on the analytics valve.let token = "phc_ai_endpoint_routing_leak_token";let distinct_id = "test_user";let hot_key = format!("{token}:{distinct_id}");@@ -689,7 +679,6 @@ async fn test_ai_endpoint_ignores_analytics_ai_routing_config() {let (router, sink) = setup_ai_router_with_force_overflow_and_limiter("phc_some_other_token",overflow_limiter,- AiRouting::Secondary,true,).await;diff --git a/rust/capture/tests/integration_analytics_ai_routing.rs b/rust/capture/tests/integration_analytics_ai_routing.rsindex aedf92514a8a..9d1facfc5b9c 100644--- a/rust/capture/tests/integration_analytics_ai_routing.rs+++ b/rust/capture/tests/integration_analytics_ai_routing.rs@@ -1,7 +1,7 @@//! Endpoint-level coverage for `$ai_*` routing on analytics deployments://! HTTP request -> router state -> `process_events` -> sink. The pipeline//! tests in `events::analytics` exercise `process_events` directly, so they-//! cannot catch a regression in the router wiring (`ai_routing` /+//! cannot catch a regression in the router wiring (capture mode ///! `ai_events_overflow_enabled` not reaching the pipeline) or in the//! endpoint-level batch handling of mixed `$ai_*` / non-AI payloads.@@ -13,7 +13,7 @@ use axum::http::StatusCode;use axum::Router;use axum_test_helper::TestClient;use capture::api::CaptureError;-use capture::config::{AiRouting, CaptureMode};+use capture::config::CaptureMode;use capture::quota_limiters::CaptureQuotaLimiter;use capture::router::router;use capture::sinks::Event;@@ -26,7 +26,6 @@ use limiters::overflow::OverflowLimiter;use limiters::token_dropper::TokenDropper;use rstest::rstest;use serde_json::json;-use std::collections::HashSet;use std::num::NonZeroU32;use std::sync::Arc;use std::time::Duration;@@ -75,14 +74,12 @@ impl Event for CapturingSink {}fn setup_analytics_router(- ai_routing: AiRouting,ai_events_overflow_enabled: bool,overflow_limiter: Option<Arc<OverflowLimiter>>,ai_events_overflow_limiter: Option<Arc<OverflowLimiter>>,) -> (Router, CapturingSink) {setup_router_for_mode(CaptureMode::Events,- ai_routing,ai_events_overflow_enabled,overflow_limiter,ai_events_overflow_limiter,@@ -91,7 +88,6 @@ fn setup_analytics_router(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>>,@@ -143,7 +139,6 @@ fn setup_router_for_mode(None, // v1_sink_router8, // capture_v1_scatter_gather_min_batchNone, // ai_gateway_signing_secret- ai_routing,ai_events_overflow_enabled,None, // ingestion_warning_emitter);@@ -208,7 +203,7 @@ async fn post_batch(client: &TestClient, payload: String) {#[case("/batch")]#[tokio::test]async fn legacy_routes_strip_forged_gateway_properties(#[case] path: &str) {- let (router, sink) = setup_analytics_router(AiRouting::Primary, false, None, None);+ let (router, sink) = setup_analytics_router(false, None, None);let client = TestClient::new(router);let event = json!({"event": "$ai_span",@@ -249,29 +244,16 @@ async fn legacy_routes_strip_forged_gateway_properties(#[case] path: &str) {assert!(data["properties"].get("$ai_gateway_request_id").is_none());}-fn allowlist(tokens: &[&str]) -> AiRouting {- AiRouting::SecondaryAllowlist(tokens.iter().map(|t| t.to_string()).collect::<HashSet<_>>())-}--/// A mixed batch must split lanes per the deployment's routing mode: only-/// `$ai_*` events divert, only when the mode says so, and the `$pageview`-/// stays on the analytics lane in every mode. The `primary` case runs with-/// the overflow valve armed, pinning down that topic/valve config alone-/// (mode left at `primary`) diverts nothing.+/// A mixed batch must split lanes: `$ai_*` events divert to the AI lane on+/// analytics deployments, and the `$pageview` stays on the analytics lane.+/// The valve-armed case pins down that the overflow valve alone does not+/// change lane assignment.#[rstest]-#[case::secondary(AiRouting::Secondary, false, DataType::AiEvents)]-#[case::allowlisted_token(allowlist(&[TOKEN]), false, DataType::AiEvents)]-#[case::unlisted_token(allowlist(&["phc_other"]), false, DataType::AnalyticsMain)]-#[case::full_percentage(AiRouting::SecondaryPercentage(100), false, DataType::AiEvents)]-#[case::zero_percentage(AiRouting::SecondaryPercentage(0), false, DataType::AnalyticsMain)]-#[case::primary_with_valve_armed(AiRouting::Primary, true, DataType::AnalyticsMain)]+#[case::valve_unarmed(false)]+#[case::valve_armed(true)]#[tokio::test]-async fn mixed_batch_diverts_only_ai_events_per_routing_mode(- #[case] ai_routing: AiRouting,- #[case] ai_events_overflow_enabled: bool,- #[case] expected_ai_data_type: DataType,-) {- let (router, sink) = setup_analytics_router(ai_routing, ai_events_overflow_enabled, None, None);+async fn mixed_batch_diverts_only_ai_events(#[case] ai_events_overflow_enabled: bool) {+ let (router, sink) = setup_analytics_router(ai_events_overflow_enabled, None, None);let client = TestClient::new(router);post_batch(&client, mixed_batch_payload()).await;@@ -283,7 +265,7 @@ async fn mixed_batch_diverts_only_ai_events_per_routing_mode(.iter().find(|e| e.metadata.event_name == "$ai_generation").expect("$ai_generation must reach the sink");- assert_eq!(ai_event.metadata.data_type, expected_ai_data_type);+ assert_eq!(ai_event.metadata.data_type, DataType::AiEvents);assert_eq!(ai_event.metadata.overflow_reason, None,"no limiter is configured, so nothing may stamp overflow"@@ -296,6 +278,30 @@ async fn mixed_batch_diverts_only_ai_events_per_routing_mode(assert_eq!(pageview.metadata.data_type, DataType::AnalyticsMain);}+/// Ai-mode deployments don't divert: their main topic is already the AI+/// topic, so `$ai_*` events stay on the analytics lane alongside everything+/// else. Pins the no-divert path end-to-end; the `routes_ai_events()` unit+/// test alone can't catch the router failing to thread the mode into the+/// pipeline.+#[tokio::test]+async fn ai_mode_keeps_ai_events_on_the_analytics_lane() {+ let (router, sink) = setup_router_for_mode(CaptureMode::Ai, false, None, None);+ let client = TestClient::new(router);++ post_batch(&client, mixed_batch_payload()).await;++ let events = sink.get_events().await;+ assert_eq!(events.len(), 2);+ for event in &events {+ assert_eq!(+ event.metadata.data_type,+ DataType::AnalyticsMain,+ "no event may divert on an Ai-mode deployment ({})",+ event.metadata.event_name,+ );+ }+}+fn force_keyed_limiter() -> Arc<OverflowLimiter> {let hot_key = format!("{TOKEN}:{DISTINCT_ID}");Arc::new(OverflowLimiter::new(@@ -323,7 +329,6 @@ async fn ai_lane_overflow_stamping_gated_on_valve(#[case] expected_ai_reason: Option<OverflowReason>,) {let (router, sink) = setup_analytics_router(- AiRouting::Secondary,ai_events_overflow_enabled,Some(force_keyed_limiter()),ai_events_overflow_enabled.then(force_keyed_limiter),@@ -368,7 +373,6 @@ async fn ai_lane_overflow_isolated_from_analytics_limiter() {));let (router, sink) = setup_analytics_router(- AiRouting::Secondary,true, // valve armedSome(force_keyed_limiter()),Some(clean_ai_limiter),@@ -400,19 +404,16 @@ async fn ai_lane_overflow_isolated_from_analytics_limiter() {);}-/// 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.+/// Import mode's no-overflow guarantee, end-to-end on the legacy path. Non-AI+/// events in a historical batch land on `AnalyticsHistorical`; `$ai_*` events+/// divert to the AI lane (only the AI lane has AI processing, so imports must+/// divert too). With the AI overflow valve unset — the capture-import config —+/// neither lane can stamp overflow, even with the overflow limiter force-keyed+/// on the batch's `token:distinct_id`, and the GRL never runs.#[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 offfalse,Some(force_keyed_limiter()),None,@@ -429,16 +430,19 @@ async fn import_mode_historical_batch_never_overflows() {);for event in &events {+ let expected = if event.metadata.event_name == "$ai_generation" {+ DataType::AiEvents+ } else {+ DataType::AnalyticsHistorical+ };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.data_type, expected,+ "unexpected lane for {}",event.metadata.event_name,);assert_eq!(event.metadata.overflow_reason, None,- "the historical lane must never overflow, even with the limiter force-keyed ({})",+ "no lane may overflow in Import mode with the AI valve unset ({})",event.metadata.event_name,);}diff --git a/rust/capture/tests/integration_analytics_restrictions.rs b/rust/capture/tests/integration_analytics_restrictions.rsindex 74af84e5372b..962329311e92 100644--- a/rust/capture/tests/integration_analytics_restrictions.rs+++ b/rust/capture/tests/integration_analytics_restrictions.rs@@ -6,7 +6,7 @@ use axum::http::StatusCode;use axum::Router;use axum_test_helper::TestClient;use capture::api::CaptureError;-use capture::config::{AiRouting, CaptureMode};+use capture::config::CaptureMode;use capture::event_restrictions::{EventRestrictionService, Pipeline, Restriction, RestrictionManager, RestrictionScope,RestrictionType,@@ -68,7 +68,6 @@ async fn setup_analytics_router_with_restriction(restriction_type: RestrictionType,restriction_pipeline: Pipeline,token: &str,- ai_routing: AiRouting,ai_events_overflow_enabled: bool,) -> (Router, CapturingSink) {let (readiness, liveness, _monitor) = test_lifecycle_handlers();@@ -135,7 +134,6 @@ async fn setup_analytics_router_with_restriction(None, // v1_sink_router8, // capture_v1_scatter_gather_min_batchNone, // ai_gateway_signing_secret- ai_routing,ai_events_overflow_enabled,None, // ingestion_warning_emitter);@@ -220,7 +218,6 @@ async fn test_analytics_drop_event_restriction() {RestrictionType::DropEvent,Pipeline::Analytics,restricted_token,- AiRouting::Primary,false,).await;@@ -257,7 +254,6 @@ async fn test_analytics_redirect_to_dlq_restriction() {RestrictionType::RedirectToDlq,Pipeline::Analytics,restricted_token,- AiRouting::Primary,false,).await;@@ -304,7 +300,6 @@ async fn test_analytics_force_overflow_restriction() {RestrictionType::ForceOverflow,Pipeline::Analytics,restricted_token,- AiRouting::Primary,false,).await;@@ -350,8 +345,8 @@ async fn test_analytics_force_overflow_restriction_applies_to_diverted_ai_event(// restrictions — the same Pipeline::Ai slice the dedicated AI endpoints// consult — so this test inserts its ForceOverflow under Pipeline::Ai.//- // The restriction must follow the event onto the lane: with secondary- // routing and the overflow valve armed, the event keeps+ // The restriction must follow the event onto the lane: with the overflow+ // valve armed, the event keeps// DataType::AiEvents and carries force_overflow (the sink maps that pair// to the AI overflow topic, never the analytics one). Catches the// restriction pipeline or the router dropping restrictions for diverted@@ -361,7 +356,6 @@ async fn test_analytics_force_overflow_restriction_applies_to_diverted_ai_event(RestrictionType::ForceOverflow,Pipeline::Ai,restricted_token,- AiRouting::Secondary,true,).await;@@ -412,7 +406,6 @@ async fn test_analytics_skip_person_processing_restriction() {RestrictionType::SkipPersonProcessing,Pipeline::Analytics,restricted_token,- AiRouting::Primary,false,).await;@@ -459,7 +452,6 @@ async fn test_analytics_restriction_does_not_apply_to_other_tokens() {RestrictionType::DropEvent,Pipeline::Analytics,restricted_token,- AiRouting::Primary,false,).await;@@ -559,18 +551,17 @@ async fn setup_analytics_router_with_redirect_to_topic(26_214_400,None,None,- 256, // body_read_chunk_size_kb- 10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes- 50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytes- None, // overflow_limiter- None, // ai_events_overflow_limiter- None, // replay_overflow_limiter- None, // v1_sink_router- 8, // capture_v1_scatter_gather_min_batch- None, // ai_gateway_signing_secret- AiRouting::Primary, // ai_routing- false, // ai_events_overflow_enabled- None, // ingestion_warning_emitter+ 256, // body_read_chunk_size_kb+ 10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes+ 50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytes+ None, // overflow_limiter+ None, // ai_events_overflow_limiter+ None, // replay_overflow_limiter+ None, // v1_sink_router+ 8, // capture_v1_scatter_gather_min_batch+ None, // ai_gateway_signing_secret+ false, // ai_events_overflow_enabled+ None, // ingestion_warning_emitter);(router, sink_clone)diff --git a/rust/capture/tests/integration_otel_endpoint.rs b/rust/capture/tests/integration_otel_endpoint.rsindex d9b09dea81bc..c0782e2eea8e 100644--- a/rust/capture/tests/integration_otel_endpoint.rs+++ b/rust/capture/tests/integration_otel_endpoint.rs@@ -5,7 +5,7 @@ use async_trait::async_trait;use axum_test_helper::TestClient;use capture::ai_s3::MockBlobStorage;use capture::api::CaptureError;-use capture::config::{AiRouting, CaptureMode};+use capture::config::CaptureMode;use capture::event_restrictions::{EventRestrictionService, Pipeline, Restriction, RestrictionFilters, RestrictionManager,RestrictionScope, RestrictionType,@@ -199,7 +199,6 @@ fn make_test_client_with_options(sink: &CapturingSink, options: TestClientOptionNone, // v1_sink_router8, // capture_v1_scatter_gather_min_batchoptions.ai_gateway_signing_secret,- AiRouting::Primary, // ai_routingfalse, // ai_events_overflow_enabledoptions.ingestion_warning_emitter, // ingestion_warning_emitter);diff --git a/rust/capture/tests/integration_replay_restrictions.rs b/rust/capture/tests/integration_replay_restrictions.rsindex 22add8397adf..dd2094721f6e 100644--- a/rust/capture/tests/integration_replay_restrictions.rs+++ b/rust/capture/tests/integration_replay_restrictions.rs@@ -6,7 +6,7 @@ use axum::http::StatusCode;use axum::Router;use axum_test_helper::TestClient;use capture::api::CaptureError;-use capture::config::{AiRouting, CaptureMode};+use capture::config::CaptureMode;use capture::event_restrictions::{EventRestrictionService, Pipeline, Restriction, RestrictionManager, RestrictionScope,RestrictionType,@@ -122,18 +122,17 @@ async fn setup_recordings_router_with_restriction(26_214_400,None, // no blob storage for recordingsNone,- 256, // body_read_chunk_size_kb- 10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes- 50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytes- None, // overflow_limiter- None, // ai_events_overflow_limiter- None, // replay_overflow_limiter- None, // v1_sink_router- 8, // capture_v1_scatter_gather_min_batch- None, // ai_gateway_signing_secret- AiRouting::Primary, // ai_routing- false, // ai_events_overflow_enabled- None, // ingestion_warning_emitter+ 256, // body_read_chunk_size_kb+ 10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes+ 50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytes+ None, // overflow_limiter+ None, // ai_events_overflow_limiter+ None, // replay_overflow_limiter+ None, // v1_sink_router+ 8, // capture_v1_scatter_gather_min_batch+ None, // ai_gateway_signing_secret+ false, // ai_events_overflow_enabled+ None, // ingestion_warning_emitter);(router, sink_clone)@@ -495,18 +494,17 @@ async fn setup_recordings_router_with_redirect_to_topic(26_214_400,None, // no blob storage for recordingsNone,- 256, // body_read_chunk_size_kb- 10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes- 50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytes- None, // overflow_limiter- None, // ai_events_overflow_limiter- None, // replay_overflow_limiter- None, // v1_sink_router- 8, // capture_v1_scatter_gather_min_batch- None, // ai_gateway_signing_secret- AiRouting::Primary, // ai_routing- false, // ai_events_overflow_enabled- None, // ingestion_warning_emitter+ 256, // body_read_chunk_size_kb+ 10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes+ 50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytes+ None, // overflow_limiter+ None, // ai_events_overflow_limiter+ None, // replay_overflow_limiter+ None, // v1_sink_router+ 8, // capture_v1_scatter_gather_min_batch+ None, // ai_gateway_signing_secret+ false, // ai_events_overflow_enabled+ None, // ingestion_warning_emitter);(router, sink_clone)diff --git a/rust/capture/tests/quota_limiters.rs b/rust/capture/tests/quota_limiters.rsindex a67a26e41740..fa86979792df 100644--- a/rust/capture/tests/quota_limiters.rs+++ b/rust/capture/tests/quota_limiters.rs@@ -15,7 +15,7 @@ use limiters::token_dropper::TokenDropper;use serde_json::Value;use capture::api::CaptureError;-use capture::config::{AiRouting, CaptureMode};+use capture::config::CaptureMode;use capture::quota_limiters::{is_exception_event, is_llm_event, is_survey_event, CaptureQuotaLimiter, EventInfo,};@@ -135,27 +135,26 @@ async fn setup_router_with_limits(None, // event_restriction_serviceNone, // recorder_handleCaptureMode::Events,- None, // concurrency_limit- 1024 * 1024, // event_payload_size_limit- false, // enable_historical_rerouting- 1, // historical_rerouting_threshold_days- false, // is_mirror_deploy- 0.0, // verbose_sample_percent- 26_214_400, // ai_max_sum_of_parts_bytes (25MB)- None, // ai_blob_storage- None, // body_chunk_read_timeout_ms- 256, // body_read_chunk_size_kb- 10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes- 50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytes- None, // overflow_limiter- None, // ai_events_overflow_limiter- None, // replay_overflow_limiter- None, // v1_sink_router- 8, // capture_v1_scatter_gather_min_batch- None, // ai_gateway_signing_secret- AiRouting::Primary, // ai_routing- false, // ai_events_overflow_enabled- None, // ingestion_warning_emitter+ None, // concurrency_limit+ 1024 * 1024, // event_payload_size_limit+ false, // enable_historical_rerouting+ 1, // historical_rerouting_threshold_days+ false, // is_mirror_deploy+ 0.0, // verbose_sample_percent+ 26_214_400, // ai_max_sum_of_parts_bytes (25MB)+ None, // ai_blob_storage+ None, // body_chunk_read_timeout_ms+ 256, // body_read_chunk_size_kb+ 10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes+ 50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytes+ None, // overflow_limiter+ None, // ai_events_overflow_limiter+ None, // replay_overflow_limiter+ None, // v1_sink_router+ 8, // capture_v1_scatter_gather_min_batch+ None, // ai_gateway_signing_secret+ false, // ai_events_overflow_enabled+ None, // ingestion_warning_emitter);(app, sink)@@ -1197,20 +1196,19 @@ async fn test_survey_quota_cross_batch_first_submission_allowed() {false,0.0,26_214_400,- None, // ai_blob_storage- None, // body_chunk_read_timeout_ms- 256, // body_read_chunk_size_kb- 10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes- 50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytes- None, // overflow_limiter- None, // ai_events_overflow_limiter- None, // replay_overflow_limiter- None, // v1_sink_router- 8, // capture_v1_scatter_gather_min_batch- None, // ai_gateway_signing_secret- AiRouting::Primary, // ai_routing- false, // ai_events_overflow_enabled- None, // ingestion_warning_emitter+ None, // ai_blob_storage+ None, // body_chunk_read_timeout_ms+ 256, // body_read_chunk_size_kb+ 10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes+ 50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytes+ None, // overflow_limiter+ None, // ai_events_overflow_limiter+ None, // replay_overflow_limiter+ None, // v1_sink_router+ 8, // capture_v1_scatter_gather_min_batch+ None, // ai_gateway_signing_secret+ false, // ai_events_overflow_enabled+ None, // ingestion_warning_emitter);let client = TestClient::new(app);@@ -1290,20 +1288,19 @@ async fn test_survey_quota_cross_batch_duplicate_submission_dropped() {false,0.0,26_214_400,- None, // ai_blob_storage- None, // body_chunk_read_timeout_ms- 256, // body_read_chunk_size_kb- 10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes- 50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytes- None, // overflow_limiter- None, // ai_events_overflow_limiter- None, // replay_overflow_limiter- None, // v1_sink_router- 8, // capture_v1_scatter_gather_min_batch- None, // ai_gateway_signing_secret- AiRouting::Primary, // ai_routing- false, // ai_events_overflow_enabled- None, // ingestion_warning_emitter+ None, // ai_blob_storage+ None, // body_chunk_read_timeout_ms+ 256, // body_read_chunk_size_kb+ 10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes+ 50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytes+ None, // overflow_limiter+ None, // ai_events_overflow_limiter+ None, // replay_overflow_limiter+ None, // v1_sink_router+ 8, // capture_v1_scatter_gather_min_batch+ None, // ai_gateway_signing_secret+ false, // ai_events_overflow_enabled+ None, // ingestion_warning_emitter);let client = TestClient::new(app);@@ -1387,20 +1384,19 @@ async fn test_survey_quota_cross_batch_redis_error_fail_open() {false,0.0,26_214_400,- None, // ai_blob_storage- None, // body_chunk_read_timeout_ms- 256, // body_read_chunk_size_kb- 10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes- 50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytes- None, // overflow_limiter- None, // ai_events_overflow_limiter- None, // replay_overflow_limiter- None, // v1_sink_router- 8, // capture_v1_scatter_gather_min_batch- None, // ai_gateway_signing_secret- AiRouting::Primary, // ai_routing- false, // ai_events_overflow_enabled- None, // ingestion_warning_emitter+ None, // ai_blob_storage+ None, // body_chunk_read_timeout_ms+ 256, // body_read_chunk_size_kb+ 10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes+ 50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytes+ None, // overflow_limiter+ None, // ai_events_overflow_limiter+ None, // replay_overflow_limiter+ None, // v1_sink_router+ 8, // capture_v1_scatter_gather_min_batch+ None, // ai_gateway_signing_secret+ false, // ai_events_overflow_enabled+ None, // ingestion_warning_emitter);let client = TestClient::new(app);@@ -1821,20 +1817,19 @@ async fn test_ai_quota_cross_batch_redis_error_fail_open() {false,0.0,26_214_400,- None, // ai_blob_storage- None, // body_chunk_read_timeout_ms- 256, // body_read_chunk_size_kb- 10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes- 50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytes- None, // overflow_limiter- None, // ai_events_overflow_limiter- None, // replay_overflow_limiter- None, // v1_sink_router- 8, // capture_v1_scatter_gather_min_batch- None, // ai_gateway_signing_secret- AiRouting::Primary, // ai_routing- false, // ai_events_overflow_enabled- None, // ingestion_warning_emitter+ None, // ai_blob_storage+ None, // body_chunk_read_timeout_ms+ 256, // body_read_chunk_size_kb+ 10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes+ 50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytes+ None, // overflow_limiter+ None, // ai_events_overflow_limiter+ None, // replay_overflow_limiter+ None, // v1_sink_router+ 8, // capture_v1_scatter_gather_min_batch+ None, // ai_gateway_signing_secret+ false, // ai_events_overflow_enabled+ None, // ingestion_warning_emitter);let client = TestClient::new(app);