Skip to content

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

feat(capture): add AI secondary sink routing modes (#67021)

Paweł Ledwoń9ee39b5b84e5
diff --git a/rust/capture/src/config.rs b/rust/capture/src/config.rs
index 9cd798a03ba8..3456cbabea68 100644
--- a/rust/capture/src/config.rs
+++ b/rust/capture/src/config.rs
@@ -1,3 +1,4 @@
+use std::collections::HashSet;
use std::{net::SocketAddr, num::NonZeroU32};
use common_continuous_profiling::ContinuousProfilingConfig;
@@ -56,6 +57,57 @@ 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,
+ /// 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" => Ok(AiSinkMode::Secondary),
+ _ => Err(format!("Unknown AiSinkMode: {s}")),
+ }
+ }
+}
+
+/// Resolved AI routing policy: the configured `AiSinkMode` with the token
+/// allowlist it needs attached to the one variant that uses it. Built from the
+/// raw `ai_sink_mode` + `ai_secondary_allowlist_tokens` 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>),
+ 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.
+ pub fn routes_to_secondary(&self, token: &str) -> bool {
+ match self {
+ AiRouting::Primary => false,
+ AiRouting::Secondary => true,
+ AiRouting::SecondaryAllowlist(allowlist) => allowlist.contains(token),
+ }
+ }
+}
+
#[derive(Envconfig, Clone)]
pub struct Config {
#[envconfig(default = "false")]
@@ -233,6 +285,27 @@ 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. 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,
+
// 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.
@@ -380,3 +453,73 @@ pub struct KafkaConfig {
pub kafka_metrics_topic_metadata_refresh_interval_ms: Option<u32>,
pub kafka_metrics_metadata_max_age_ms: Option<u32>,
}
+
+#[cfg(test)]
+mod tests {
+ use super::{AiRouting, AiSinkMode};
+ use std::str::FromStr;
+
+ #[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),
+ ];
+ for (input, expected) in ok {
+ assert_eq!(
+ AiSinkMode::from_str(input).unwrap(),
+ expected,
+ "input={input}"
+ );
+ }
+
+ for bad in ["", "secondaryallowlist", "warpstream", "allowlist"] {
+ 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,
+ ),
+ ];
+ for (routing, token, expected) in cases {
+ assert_eq!(
+ routing.routes_to_secondary(token),
+ expected,
+ "routing={routing:?} token={token}"
+ );
+ }
+ }
+}
diff --git a/rust/capture/src/setup.rs b/rust/capture/src/setup.rs
index b0cb154a877c..ca839dc2f55e 100644
--- a/rust/capture/src/setup.rs
+++ b/rust/capture/src/setup.rs
@@ -1,4 +1,4 @@
-use std::collections::HashMap;
+use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use std::time::Duration;
@@ -8,7 +8,7 @@ use common_redis::RedisClient;
use tracing::{info, warn};
use crate::ai_s3::AiBlobStorage;
-use crate::config::{CaptureMode, Config};
+use crate::config::{AiRouting, AiSinkMode, CaptureMode, Config, KafkaConfig};
use crate::event_restrictions::{EventRestrictionService, Pipeline, RedisRestrictionsRepository};
use crate::global_rate_limiter::GlobalRateLimiter;
use crate::quota_limiters::{
@@ -22,6 +22,7 @@ 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};
@@ -38,6 +39,18 @@ 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)),
@@ -229,11 +242,57 @@ pub async fn build_components(
_ => None,
};
- let sink: Arc<dyn Event + Send + Sync> = Arc::from(
- create_sink(&config, sink_handle, advisory_handle)
+ // 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)
.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 = if config.ai_sink_mode == AiSinkMode::SecondaryAllowlist {
+ let allowlist = config
+ .ai_secondary_allowlist_tokens
+ .as_deref()
+ .map(parse_token_allowlist)
+ .unwrap_or_default();
+ AiRouting::SecondaryAllowlist(allowlist)
+ } else {
+ AiRouting::Secondary
+ };
+ 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
@@ -344,6 +403,40 @@ 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()
+}
+
fn create_v1_sink_router(
config: &Config,
sink_env: &HashMap<String, String>,
@@ -400,42 +493,39 @@ async fn create_sink(
} else if config.noop_sink {
info!("NoOpSink enabled, events will be silently dropped");
Ok(Box::new(NoOpSink::new()))
- } else {
- let sink_handle = sink_handle.expect("sink lifecycle handle required for Kafka/S3 sinks");
-
- if config.s3_fallback_enabled {
- let kafka_handle =
- advisory_handle.expect("kafka advisory handle required for fallback");
- let s3_handle = sink_handle;
+ } else if config.s3_fallback_enabled {
+ let s3_handle = sink_handle.expect("sink lifecycle handle required for S3 fallback");
+ let kafka_handle = advisory_handle.expect("kafka advisory handle required for fallback");
- let kafka_sink = KafkaSink::new(config.kafka.clone(), kafka_handle.clone())
- .await
- .expect("failed to start Kafka sink");
-
- let s3_sink = S3Sink::new(
- config
- .s3_fallback_bucket
- .clone()
- .expect("S3 bucket required when fallback enabled"),
- config.s3_fallback_prefix.clone(),
- config.s3_fallback_endpoint.clone(),
- s3_handle,
- )
+ let kafka_sink = KafkaSink::new(config.kafka.clone(), Some(kafka_handle.clone()))
.await
- .expect("failed to create S3 sink");
+ .expect("failed to start Kafka sink");
+
+ let s3_sink = S3Sink::new(
+ config
+ .s3_fallback_bucket
+ .clone()
+ .expect("S3 bucket required when fallback enabled"),
+ config.s3_fallback_prefix.clone(),
+ config.s3_fallback_endpoint.clone(),
+ s3_handle,
+ )
+ .await
+ .expect("failed to create S3 sink");
- Ok(Box::new(FallbackSink::new_with_advisory(
- kafka_sink,
- s3_sink,
- kafka_handle,
- )))
- } else {
- let kafka_sink = KafkaSink::new(config.kafka.clone(), sink_handle)
- .await
- .expect("failed to start Kafka sink");
+ Ok(Box::new(FallbackSink::new_with_advisory(
+ kafka_sink,
+ s3_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
+ .expect("failed to start Kafka sink");
- Ok(Box::new(kafka_sink))
- }
+ Ok(Box::new(kafka_sink))
}
}
@@ -553,4 +643,42 @@ mod tests {
"error should name the failing sink: {msg}"
);
}
+
+ #[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());
+ }
}
diff --git a/rust/capture/src/sinks/kafka.rs b/rust/capture/src/sinks/kafka.rs
index 1b2e6ca13859..2204a61d009e 100644
--- a/rust/capture/src/sinks/kafka.rs
+++ b/rust/capture/src/sinks/kafka.rs
@@ -36,7 +36,11 @@ use tracing::{info_span, instrument, Instrument};
use super::producer::RdKafkaProducer;
pub struct KafkaContext {
- liveness: lifecycle::Handle,
+ /// 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.
+ liveness: Option<lifecycle::Handle>,
}
/// Emit min/avg/max/stddev plus p50/p90/p95/p99 for an rdkafka window stat
@@ -72,7 +76,9 @@ impl rdkafka::ClientContext for KafkaContext {
// Signal liveness when brokers are up
let brokers_up = stats.brokers.values().any(|broker| broker.state == "UP");
if brokers_up {
- self.liveness.report_healthy();
+ if let Some(liveness) = &self.liveness {
+ liveness.report_healthy();
+ }
}
let total_brokers = stats.brokers.len();
@@ -224,7 +230,7 @@ pub type KafkaSink = KafkaSinkBase<RdKafkaProducer<KafkaContext>>;
impl KafkaSink {
pub async fn new(
config: KafkaConfig,
- liveness: lifecycle::Handle,
+ liveness: Option<lifecycle::Handle>,
) -> anyhow::Result<KafkaSink> {
info!("connecting to Kafka brokers at {}...", config.kafka_hosts);
@@ -337,7 +343,9 @@ impl KafkaSink {
)
.is_ok()
{
- liveness.report_healthy();
+ if let Some(liveness) = &liveness {
+ liveness.report_healthy();
+ }
info!("connected to Kafka brokers");
};
@@ -882,7 +890,7 @@ mod tests {
kafka_metrics_metadata_max_age_ms: None,
kafka_replay_envelope_compression: EnvelopeCompression::None,
};
- let sink = KafkaSink::new(config, handle)
+ let sink = KafkaSink::new(config, Some(handle))
.await
.expect("failed to create sink");
(cluster, sink)
diff --git a/rust/capture/src/sinks/mod.rs b/rust/capture/src/sinks/mod.rs
index ed6c7d68ea5a..ef3d86e115bb 100644
--- a/rust/capture/src/sinks/mod.rs
+++ b/rust/capture/src/sinks/mod.rs
@@ -8,6 +8,7 @@ pub mod noop;
pub mod print;
pub mod producer;
pub mod s3;
+pub mod split;
#[cfg(test)]
pub(crate) mod test_sink;
#[async_trait]
diff --git a/rust/capture/src/sinks/split.rs b/rust/capture/src/sinks/split.rs
new file mode 100644
index 000000000000..7226aa0aede5
--- /dev/null
+++ b/rust/capture/src/sinks/split.rs
@@ -0,0 +1,194 @@
+//! 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,
+ },
+ }
+ }
+
+ 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/v1/quota_limiter_shim.rs b/rust/capture/src/v1/quota_limiter_shim.rs
index a3ac342114dd..bbb11ae400d3 100644
--- a/rust/capture/src/v1/quota_limiter_shim.rs
+++ b/rust/capture/src/v1/quota_limiter_shim.rs
@@ -234,6 +234,12 @@ 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(),
http1_header_read_timeout_ms: Some(5000),
body_chunk_read_timeout_ms: None,
body_read_chunk_size_kb: 256,
diff --git a/rust/capture/tests/common/utils.rs b/rust/capture/tests/common/utils.rs
index e5f676eee0e2..272a3b91b8c5 100644
--- a/rust/capture/tests/common/utils.rs
+++ b/rust/capture/tests/common/utils.rs
@@ -150,6 +150,12 @@ 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(),
http1_header_read_timeout_ms: Some(5000), // 5 seconds default
body_chunk_read_timeout_ms: None, // disabled by default in tests
body_read_chunk_size_kb: 256, // 256KB default