: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
refactor(capture): lane decision moves to the pipeline layer (#78977)
Paweł Ledwońd347bab42983
diff --git a/rust/capture/OUTPUTS_REFACTOR_PLAN.md b/rust/capture/OUTPUTS_REFACTOR_PLAN.mdindex 3906d09f717d..108d1a6a500e 100644--- a/rust/capture/OUTPUTS_REFACTOR_PLAN.md+++ b/rust/capture/OUTPUTS_REFACTOR_PLAN.md@@ -265,7 +265,7 @@ When all steps land, the five strata hold:| 2 · Pure `route()` | done | `refactor(capture): extract pure route() from prepare_record` || 3 · `OutputRegistry` + completeness | done | `refactor(capture): output registry with startup completeness check` || 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` |+| 5 · `Pipeline` + `Lane`; lane resolution | done | `refactor(capture): 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 the failover policy` || 8a · Call sites on the table | pending | `refactor(capture): call sites publish through outputs` |diff --git a/rust/capture/src/event_restrictions/manager.rs b/rust/capture/src/event_restrictions/manager.rsindex d25743b863ba..5f38071ee61a 100644--- a/rust/capture/src/event_restrictions/manager.rs+++ b/rust/capture/src/event_restrictions/manager.rs@@ -347,6 +347,14 @@ impl EventRestrictionService {now}+ /// Whether at least one refresh has succeeded since boot. Until then the+ /// service is fail-open and every lookup returns empty, so callers that+ /// need loaded state (tests synchronizing with the initial load) poll this+ /// instead of guessing at refresh timing.+ pub fn has_loaded(&self) -> bool {+ self.last_successful_refresh.load(Ordering::SeqCst) != 0+ }+/// Check if the cache is stale (fail-open should be active).fn is_stale_at(&self, now_ts: i64) -> bool {let last_refresh = self.last_successful_refresh.load(Ordering::SeqCst);diff --git a/rust/capture/src/lib.rs b/rust/capture/src/lib.rsindex e1baaa3ac123..b0ae59d8af90 100644--- a/rust/capture/src/lib.rs+++ b/rust/capture/src/lib.rs@@ -17,6 +17,7 @@ pub mod otel;#[cfg(test)]mod overflow_parity;pub mod payload;+pub mod pipeline;pub mod prometheus;pub mod quota_limiters;pub mod router;diff --git a/rust/capture/src/pipeline.rs b/rust/capture/src/pipeline.rsnew file mode 100644index 000000000000..5cb85d26cc33--- /dev/null+++ b/rust/capture/src/pipeline.rs@@ -0,0 +1,570 @@+//! Pipeline and lane — an event's address, and the one place it is decided.+//!+//! [`resolve`] folds the intent stamped on [`ProcessedEventMetadata`] during+//! processing (restrictions, overflow reasons, the historical flag) through+//! one precedence chain — dlq > custom > historical > overflow > main — and+//! returns an [`AddressDecision`]: the [`Address`] the event publishes to and+//! the customer-facing [`OrderingGuarantee`] the sink realizes as a partition+//! key. The decision is pure — no counters, no headers, no I/O; side effects+//! are implied by the address and applied by the layer that realizes it.+//!+//! The sink still invokes `resolve` from its prep path and bridges the+//! decision to its configured topics; the invocation site moves up when the+//! outputs layer exists to own it (see the plan doc).++use crate::api::CaptureError;+use crate::ordering::{person_ordering, OrderingGuarantee};+use crate::v0_request::{DataType, OverflowReason, ProcessedEventMetadata};++/// The high-level "which product stream is this" classification, decided at+/// the edge (endpoint + event name) and stamped as the pipeline half of+/// [`DataType`]. AI membership is stamp-based, not name-based: an undiverted+/// `$ai_*` event is a plain analytics event.+#[derive(Debug, Copy, Clone, PartialEq, Eq)]+pub enum Pipeline {+ Analytics,+ Ai,+ Heatmaps,+ Warnings,+ ErrorTracking,+ Replay,+}++/// A lane of a pipeline. Flat for now — every pipeline shares this shape, and+/// `resolve` only ever pairs a pipeline with the lanes it actually has (the+/// typed-per-pipeline lanes step makes invalid pairs unrepresentable).+#[derive(Debug, Copy, Clone, PartialEq, Eq)]+pub enum Lane {+ Main,+ Overflow,+ Historical,+}++/// Where an event publishes: a lane of its pipeline, or an admin redirect+/// that sits outside the pipeline-lane model. The redirects carry no+/// pipeline because nothing consumes one — every pipeline shares a single+/// dlq output today (per-pipeline dlq rows arrive with typed addresses), and+/// a custom redirect carries its own topic.+#[derive(Debug, Clone, PartialEq, Eq)]+pub enum Address {+ Lane { pipeline: Pipeline, lane: Lane },+ Dlq,+ Custom(String),+}++/// The pure routing decision for a single event: which address, and which+/// ordering guarantee. Depends only on [`ProcessedEventMetadata`] (stamped+/// upstream by the pipeline) and the AI overflow valve — the one piece of+/// deployment config that changes a routing decision rather than a topic+/// name. Side effects are not part of the decision: the dlq header set and+/// the reroute counters follow from the address, and the person-processing+/// header follows from+/// [`ProcessedEventMetadata::person_processing_disabled`] — the stamped flag,+/// or a `ForceLimited` reason, which implies the skip on its own.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct AddressDecision {+ pub address: Address,+ pub ordering: OrderingGuarantee,+}++impl AddressDecision {+ fn lane(pipeline: Pipeline, lane: Lane, ordering: OrderingGuarantee) -> Self {+ Self {+ address: Address::Lane { pipeline, lane },+ ordering,+ }+ }++ /// Both admin redirects key on the event key.+ fn redirect(address: Address) -> Self {+ Self {+ address,+ ordering: OrderingGuarantee::PerDistinctId,+ }+ }+}++/// Decide an event's address from its metadata. DLQ and custom-topic+/// redirects take priority over per-datatype and overflow routing. Consulted+/// by the sink, which resolves the address to a topic string and the ordering+/// guarantee to a partition key, and applies the address-implied side+/// effects. A replay event with no session id is rejected here, so every+/// returned decision is realizable by the sink.+pub fn resolve(+ metadata: &ProcessedEventMetadata,+ ai_events_overflow_armed: bool,+) -> Result<AddressDecision, CaptureError> {+ // redirect_to_dlq takes priority over all other routing.+ if metadata.redirect_to_dlq {+ return Ok(AddressDecision::redirect(Address::Dlq));+ }++ if let Some(ref topic) = metadata.redirect_to_topic {+ return Ok(AddressDecision::redirect(Address::Custom(topic.clone())));+ }++ Ok(match metadata.data_type {+ DataType::AnalyticsHistorical => AddressDecision::lane(+ Pipeline::Analytics,+ // Historical events never overflow — force_overflow and+ // overflow_reason are deliberately ignored here.+ Lane::Historical,+ OrderingGuarantee::PerDistinctId,+ ),+ DataType::AnalyticsMain => {+ // Precedence: force_overflow (restrictions) -> overflow_reason+ // (pipeline-stamped) -> default main-lane routing.+ if metadata.force_overflow {+ AddressDecision::lane(+ Pipeline::Analytics,+ Lane::Overflow,+ person_ordering(metadata.person_processing_disabled()),+ )+ } else {+ match &metadata.overflow_reason {+ Some(OverflowReason::ForceLimited) => AddressDecision::lane(+ Pipeline::Analytics,+ Lane::Overflow,+ OrderingGuarantee::None,+ ),+ // The person flag alone decides the key here, in both+ // directions. A burst keeps its key while person processing+ // is on — the overflow consumer updates persons keyed on+ // distinct id, so spreading one distinct id across+ // partitions turns a hot key into contended person-row+ // updates — which makes the locality preference irrelevant+ // on this lane. And a key whose person processing is+ // already off (the global rate limiter stamps its verdict+ // before the overflow limiter overwrites the reason) must+ // not get its partition back.+ Some(OverflowReason::RateLimited { .. }) => AddressDecision::lane(+ Pipeline::Analytics,+ Lane::Overflow,+ person_ordering(metadata.person_processing_disabled()),+ ),+ // ReplayLimited is stamped only by the recordings pipeline,+ // so an analytics event cannot carry it — the shared+ // OverflowReason enum forces the arm, which treats the+ // impossible stamp as unstamped.+ Some(OverflowReason::ReplayLimited) | None => AddressDecision::lane(+ Pipeline::Analytics,+ Lane::Main,+ person_ordering(metadata.person_processing_disabled()),+ ),+ }+ }+ }+ DataType::AiEvents => {+ // Valve armed: the AI lanes route overflow like analytics, except+ // that a burst may spread while person processing is on — the AI+ // consumer reads persons without writing them, so keyless+ // person-on records cause no person-update contention there.+ // Valve unarmed: AI events never overflow —+ // force_overflow and stamped reasons are deliberately ignored+ // (the pipeline never stamps a reason on this lane anyway). The+ // default route keeps the event key regardless of+ // skip_person_processing (v1 only nulls keys for+ // Main/Overflow-shaped destinations). AI events never reroute+ // historical.+ if ai_events_overflow_armed && metadata.force_overflow {+ AddressDecision::lane(+ Pipeline::Ai,+ Lane::Overflow,+ person_ordering(metadata.person_processing_disabled()),+ )+ } else if ai_events_overflow_armed {+ match &metadata.overflow_reason {+ Some(OverflowReason::ForceLimited) => {+ AddressDecision::lane(Pipeline::Ai, Lane::Overflow, OrderingGuarantee::None)+ }+ Some(OverflowReason::RateLimited {+ preserve_locality: true,+ }) => AddressDecision::lane(+ Pipeline::Ai,+ Lane::Overflow,+ // Same precedence as the analytics overflow lane above.+ person_ordering(metadata.person_processing_disabled()),+ ),+ Some(OverflowReason::RateLimited {+ preserve_locality: false,+ }) => {+ AddressDecision::lane(Pipeline::Ai, Lane::Overflow, OrderingGuarantee::None)+ }+ // ReplayLimited cannot be stamped on the AI lane either;+ // treated as unstamped, as above.+ Some(OverflowReason::ReplayLimited) | None => AddressDecision::lane(+ Pipeline::Ai,+ Lane::Main,+ OrderingGuarantee::PerDistinctId,+ ),+ }+ } else {+ AddressDecision::lane(Pipeline::Ai, Lane::Main, OrderingGuarantee::PerDistinctId)+ }+ }+ // Single-lane pipelines: capture has no overflow topic for warnings,+ // heatmaps, or error tracking, so `Lane::Overflow` is never resolved+ // for them. Error tracking is the only one of the three that can+ // actually carry overflow intent — an error-tracking-scoped+ // ForceOverflow restriction stamps `force_overflow` on an exception+ // event — and the stamp is deliberately ignored here; the event+ // publishes to main. Warnings and heatmaps flow through event+ // restrictions unrestricted (no restriction pipeline covers them).+ DataType::ClientIngestionWarning => AddressDecision::lane(+ Pipeline::Warnings,+ Lane::Main,+ OrderingGuarantee::PerDistinctId,+ ),+ DataType::HeatmapMain => AddressDecision::lane(+ Pipeline::Heatmaps,+ Lane::Main,+ OrderingGuarantee::PerDistinctId,+ ),+ DataType::ExceptionErrorTracking => AddressDecision::lane(+ Pipeline::ErrorTracking,+ Lane::Main,+ OrderingGuarantee::PerDistinctId,+ ),+ DataType::SnapshotMain => {+ // Precedence: force_overflow (restrictions) -> overflow_reason+ // (pipeline-stamped ReplayLimited) -> default main-lane routing.+ // Partition key is always session_id for replay to keep per-session+ // ordering on the overflow lane; a missing id makes the decision+ // unrealizable, so it is rejected as part of the decision.+ if metadata.session_id.is_none() {+ return Err(CaptureError::MissingSessionId);+ }+ let lane = if metadata.force_overflow+ || matches!(+ metadata.overflow_reason,+ Some(OverflowReason::ReplayLimited)+ ) {+ Lane::Overflow+ } else {+ Lane::Main+ };+ AddressDecision::lane(Pipeline::Replay, lane, OrderingGuarantee::PerSession)+ }+ })+}++#[cfg(test)]+mod tests {+ use super::*;+ use rstest::rstest;++ fn meta(data_type: DataType) -> ProcessedEventMetadata {+ ProcessedEventMetadata {+ data_type,+ session_id: Some("session123".to_string()),+ computed_timestamp: None,+ event_name: "test_event".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 lane(pipeline: Pipeline, lane: Lane) -> Address {+ Address::Lane { pipeline, lane }+ }++ #[test]+ fn dlq_wins_over_custom_topic_and_datatype() {+ // redirect_to_dlq set alongside redirect_to_topic and an overflow+ // reason: DLQ still wins, keyed on the event key, with the DLQ effect.+ let mut m = meta(DataType::AnalyticsMain);+ m.redirect_to_dlq = true;+ m.redirect_to_topic = Some("custom".to_string());+ m.force_overflow = true;+ assert_eq!(+ resolve(&m, false).unwrap(),+ AddressDecision {+ address: Address::Dlq,+ ordering: OrderingGuarantee::PerDistinctId,+ }+ );+ }++ #[test]+ fn custom_topic_wins_over_datatype() {+ // Custom-topic redirect beats per-datatype/overflow routing (but not DLQ).+ let mut m = meta(DataType::AnalyticsMain);+ m.redirect_to_topic = Some("my_topic".to_string());+ m.force_overflow = true;+ assert_eq!(+ resolve(&m, false).unwrap(),+ AddressDecision {+ address: Address::Custom("my_topic".to_string()),+ ordering: OrderingGuarantee::PerDistinctId,+ }+ );+ }++ #[rstest]+ #[case(DataType::AnalyticsMain, Pipeline::Analytics, Lane::Main)]+ #[case(DataType::AnalyticsHistorical, Pipeline::Analytics, Lane::Historical)]+ #[case(DataType::ClientIngestionWarning, Pipeline::Warnings, Lane::Main)]+ #[case(DataType::HeatmapMain, Pipeline::Heatmaps, Lane::Main)]+ #[case(DataType::ExceptionErrorTracking, Pipeline::ErrorTracking, Lane::Main)]+ #[case(DataType::AiEvents, Pipeline::Ai, Lane::Main)]+ #[case(DataType::SnapshotMain, Pipeline::Replay, Lane::Main)]+ fn per_datatype_addresses(+ #[case] data_type: DataType,+ #[case] pipeline: Pipeline,+ #[case] expected_lane: Lane,+ ) {+ let m = meta(data_type);+ let d = resolve(&m, false).unwrap();+ assert_eq!(+ d.address,+ lane(pipeline, expected_lane),+ "wrong address for {data_type:?}"+ );+ }++ /// The single-lane pipelines have no overflow lane to give: stamped+ /// overflow intent (an error-tracking-scoped ForceOverflow restriction is+ /// the reachable case) must resolve to main, not to an overflow address+ /// no output backs.+ #[rstest]+ #[case(DataType::ClientIngestionWarning, Pipeline::Warnings)]+ #[case(DataType::HeatmapMain, Pipeline::Heatmaps)]+ #[case(DataType::ExceptionErrorTracking, Pipeline::ErrorTracking)]+ fn single_lane_pipelines_ignore_overflow_intent(+ #[case] data_type: DataType,+ #[case] pipeline: Pipeline,+ ) {+ let mut m = meta(data_type);+ m.force_overflow = true;+ m.overflow_reason = Some(OverflowReason::ForceLimited);+ assert_eq!(+ resolve(&m, true).unwrap().address,+ lane(pipeline, Lane::Main),+ "overflow intent must not move {data_type:?} off its main lane"+ );+ }++ #[test]+ fn analytics_main_overflow_ordering() {+ // force_overflow -> overflow lane; key policy follows skip_person.+ let mut m = meta(DataType::AnalyticsMain);+ m.force_overflow = true;+ assert_eq!(+ resolve(&m, false).unwrap().ordering,+ OrderingGuarantee::PerDistinctId+ );+ m.skip_person_processing = true;+ assert_eq!(+ resolve(&m, false).unwrap().ordering,+ OrderingGuarantee::None+ );+ assert_eq!(+ resolve(&m, false).unwrap().address,+ lane(Pipeline::Analytics, Lane::Overflow)+ );+ }++ #[test]+ fn analytics_main_overflow_reason_precedence() {+ let base = meta(DataType::AnalyticsMain);++ let mut force_limited = base.clone();+ force_limited.overflow_reason = Some(OverflowReason::ForceLimited);+ assert_eq!(+ resolve(&force_limited, false).unwrap(),+ AddressDecision {+ address: lane(Pipeline::Analytics, Lane::Overflow),+ ordering: OrderingGuarantee::None,+ }+ );++ let mut preserve = base.clone();+ preserve.overflow_reason = Some(OverflowReason::RateLimited {+ preserve_locality: true,+ });+ assert_eq!(+ resolve(&preserve, false).unwrap().ordering,+ OrderingGuarantee::PerDistinctId+ );+ assert_eq!(+ resolve(&preserve, false).unwrap().address,+ lane(Pipeline::Analytics, Lane::Overflow)+ );++ // The locality preference is irrelevant on the analytics lane: a+ // person-on burst keeps its key either way, because the overflow+ // consumer writes persons keyed on distinct id.+ let mut no_preserve = base.clone();+ no_preserve.overflow_reason = Some(OverflowReason::RateLimited {+ preserve_locality: false,+ });+ assert_eq!(+ resolve(&no_preserve, false).unwrap().ordering,+ OrderingGuarantee::PerDistinctId+ );+ assert_eq!(+ resolve(&no_preserve, false).unwrap().address,+ lane(Pipeline::Analytics, Lane::Overflow)+ );+ no_preserve.skip_person_processing = true;+ assert_eq!(+ resolve(&no_preserve, false).unwrap().ordering,+ OrderingGuarantee::None+ );++ // ReplayLimited cannot be stamped on analytics events (only the+ // recordings pipeline produces it); the impossible combination is+ // treated as unstamped.+ let mut replay = base;+ replay.overflow_reason = Some(OverflowReason::ReplayLimited);+ assert_eq!(+ resolve(&replay, false).unwrap().address,+ lane(Pipeline::Analytics, Lane::Main)+ );+ }++ /// The global rate limiter stamps `skip_person_processing` before the+ /// overflow limiter runs, and the overflow limiter overwrites the reason it+ /// stamped. Without this precedence a key the rate limiter declared too hot+ /// would go back to hashing onto a single overflow partition whenever the+ /// limiter preserves locality, which is how prod-US is configured.+ #[rstest]+ #[case::analytics(DataType::AnalyticsMain, Pipeline::Analytics)]+ #[case::ai(DataType::AiEvents, Pipeline::Ai)]+ fn person_processing_off_outranks_preserve_locality(+ #[case] data_type: DataType,+ #[case] expected_pipeline: Pipeline,+ ) {+ let armed = data_type == DataType::AiEvents;+ let mut m = meta(data_type);+ m.overflow_reason = Some(OverflowReason::RateLimited {+ preserve_locality: true,+ });++ assert_eq!(+ resolve(&m, armed).unwrap().ordering,+ OrderingGuarantee::PerDistinctId,+ "locality is preserved while person processing is on"+ );++ m.skip_person_processing = true;+ assert_eq!(+ resolve(&m, armed).unwrap(),+ AddressDecision {+ address: lane(expected_pipeline, Lane::Overflow),+ ordering: OrderingGuarantee::None,+ }+ );+ }++ #[test]+ fn ai_events_overflow_gated_on_valve() {+ // Valve unarmed: force_overflow and stamped reasons are ignored — the+ // AI lane never overflows and keeps its event key.+ let mut m = meta(DataType::AiEvents);+ m.force_overflow = true;+ assert_eq!(+ resolve(&m, false).unwrap(),+ AddressDecision {+ address: lane(Pipeline::Ai, Lane::Main),+ ordering: OrderingGuarantee::PerDistinctId,+ }+ );++ // Valve armed: mirrors the analytics main lane's overflow handling.+ assert_eq!(+ resolve(&m, true).unwrap().address,+ lane(Pipeline::Ai, Lane::Overflow)+ );+ assert_eq!(+ resolve(&m, true).unwrap().ordering,+ OrderingGuarantee::PerDistinctId+ );+ m.skip_person_processing = true;+ assert_eq!(resolve(&m, true).unwrap().ordering, OrderingGuarantee::None);++ let mut force_limited = meta(DataType::AiEvents);+ force_limited.overflow_reason = Some(OverflowReason::ForceLimited);+ assert_eq!(+ resolve(&force_limited, true).unwrap(),+ AddressDecision {+ address: lane(Pipeline::Ai, Lane::Overflow),+ ordering: OrderingGuarantee::None,+ }+ );+ assert_eq!(+ resolve(&force_limited, false).unwrap().address,+ lane(Pipeline::Ai, Lane::Main)+ );+ }++ #[test]+ fn ai_events_default_route_keeps_event_key() {+ // skip_person_processing must not null the key on the AI default+ // route: v1 only nulls keys for Main/Overflow-shaped destinations.+ let mut m = meta(DataType::AiEvents);+ m.skip_person_processing = true;+ for armed in [false, true] {+ assert_eq!(+ resolve(&m, armed).unwrap(),+ AddressDecision {+ address: lane(Pipeline::Ai, Lane::Main),+ ordering: OrderingGuarantee::PerDistinctId,+ },+ "armed={armed}"+ );+ }+ }++ #[test]+ fn snapshot_routing_keeps_per_session_ordering() {+ let mut m = meta(DataType::SnapshotMain);+ assert_eq!(+ resolve(&m, false).unwrap(),+ AddressDecision {+ address: lane(Pipeline::Replay, Lane::Main),+ ordering: OrderingGuarantee::PerSession,+ }+ );++ m.force_overflow = true;+ assert_eq!(+ resolve(&m, false).unwrap().address,+ lane(Pipeline::Replay, Lane::Overflow)+ );+ assert_eq!(+ resolve(&m, false).unwrap().ordering,+ OrderingGuarantee::PerSession+ );++ m.force_overflow = false;+ m.overflow_reason = Some(OverflowReason::ReplayLimited);+ assert_eq!(+ resolve(&m, false).unwrap().address,+ lane(Pipeline::Replay, Lane::Overflow)+ );+ }++ /// A replay event with no session id has no realizable address — the+ /// decision itself rejects, rather than handing the sink a `PerSession`+ /// guarantee it cannot key.+ #[test]+ fn snapshot_without_session_id_is_rejected() {+ let mut m = meta(DataType::SnapshotMain);+ m.session_id = None;+ assert!(matches!(+ resolve(&m, false),+ Err(CaptureError::MissingSessionId)+ ));++ // A dlq redirect keys on the event key, so it stays realizable+ // without a session id.+ m.redirect_to_dlq = true;+ assert_eq!(resolve(&m, false).unwrap().address, Address::Dlq);+ }+}diff --git a/rust/capture/src/server.rs b/rust/capture/src/server.rsindex d52286e722e9..99b3367433f9 100644--- a/rust/capture/src/server.rs+++ b/rust/capture/src/server.rs@@ -95,6 +95,7 @@ pub async fn serve(listener: TcpListener, components: CaptureComponents) {server_handle,sink,v1_sink_router,+ event_restriction_service: _,http1_header_read_timeout_ms,} = components;diff --git a/rust/capture/src/setup.rs b/rust/capture/src/setup.rsindex ea997687a947..1748121400bf 100644--- a/rust/capture/src/setup.rs+++ b/rust/capture/src/setup.rs@@ -130,6 +130,7 @@ pub struct CaptureComponents {pub server_handle: lifecycle::Handle,pub sink: Arc<dyn Event + Send + Sync>,pub v1_sink_router: Option<Arc<crate::v1::sinks::Router>>,+ pub event_restriction_service: Option<EventRestrictionService>,pub http1_header_read_timeout_ms: Option<u64>,}@@ -392,7 +393,7 @@ pub async fn build_components(global_rate_limiter_token_distinctid,quota_limiter,token_dropper,- event_restriction_service,+ event_restriction_service.clone(),recorder_handle,config.capture_mode,config.concurrency_limit,@@ -427,6 +428,7 @@ pub async fn build_components(server_handle: server,sink: sink_for_flush,v1_sink_router,+ event_restriction_service,http1_header_read_timeout_ms: config.http1_header_read_timeout_ms,}}diff --git a/rust/capture/src/sinks/kafka.rs b/rust/capture/src/sinks/kafka.rsindex e613b15cae7c..9a9f8ae890f0 100644--- a/rust/capture/src/sinks/kafka.rs+++ b/rust/capture/src/sinks/kafka.rs@@ -19,12 +19,13 @@//! + topics) rather than deep copies of limiter state.use crate::api::CaptureError;use crate::config::{EnvelopeCompression, KafkaConfig};-use crate::ordering::{person_ordering, OrderingGuarantee};+use crate::ordering::OrderingGuarantee;+use crate::pipeline::{self, Address, Lane, Pipeline};use crate::serialization::Serializer;use crate::sinks::producer::{KafkaProducer, ProduceRecord};use crate::sinks::registry::{Output, OutputRegistry};use crate::sinks::Event;-use crate::v0_request::{DataType, OverflowReason, ProcessedEvent, ProcessedEventMetadata};+use crate::v0_request::{DataType, ProcessedEvent};use async_trait::async_trait;use metrics::{counter, gauge, histogram};use rdkafka::producer::{FutureProducer, Producer};@@ -196,453 +197,43 @@ impl<P: KafkaProducer> Clone for KafkaSinkBase<P> {}}-/// The pure routing decision for a single event: which output, and which-/// ordering guarantee. Depends only on [`ProcessedEventMetadata`] (stamped-/// upstream by the pipeline) and the AI overflow valve — the one piece of-/// sink config that changes a routing decision rather than a topic name.-/// Side effects are not part of the decision: the dlq header set and the-/// reroute counters follow from the target, and the person-processing header-/// follows from [`ProcessedEventMetadata::person_processing_disabled`] —-/// the stamped flag, or a `ForceLimited` reason, which implies the skip on-/// its own.-#[derive(Debug, Clone, PartialEq, Eq)]-struct Route {- target: Output,- ordering: OrderingGuarantee,-}--/// Decide an event's route from its metadata. DLQ and custom-topic redirects-/// take priority over per-datatype and overflow routing. Consulted by the-/// sink, which resolves the target to a topic string and the ordering-/// guarantee to a partition key, and applies the target-implied side effects.-/// A replay event with no session id is rejected here, so every returned-/// `Route` is realizable by the sink.-fn route(- metadata: &ProcessedEventMetadata,- ai_events_overflow_armed: bool,-) -> Result<Route, CaptureError> {- // redirect_to_dlq takes priority over all other routing.- if metadata.redirect_to_dlq {- return Ok(Route {- target: Output::Dlq,- ordering: OrderingGuarantee::PerDistinctId,- });- }-- if let Some(ref topic) = metadata.redirect_to_topic {- return Ok(Route {- target: Output::Custom(topic.clone()),- ordering: OrderingGuarantee::PerDistinctId,- });+/// Map a lane address to the sink's configured [`Output`]. The sink owns+/// this mapping only until the outputs layer exists to own the address →+/// output table. Every `(pipeline, lane)` pair is spelled out so that a new+/// lane, or a change making an unbacked pair reachable, has to visit this+/// match instead of being absorbed by a wildcard. `None` marks a pair+/// [`pipeline::resolve`] never produces — no output backs it, and the caller+/// dlqs the event (the typed-per-pipeline-lanes step makes these pairs+/// unrepresentable).+fn lane_output(pipeline: Pipeline, lane: Lane) -> Option<Output> {+ match (pipeline, lane) {+ (Pipeline::Analytics, Lane::Main) => Some(Output::AnalyticsMain),+ (Pipeline::Analytics, Lane::Overflow) => Some(Output::AnalyticsOverflow),+ (Pipeline::Analytics, Lane::Historical) => Some(Output::AnalyticsHistorical),+ (Pipeline::Ai, Lane::Main) => Some(Output::AiMain),+ (Pipeline::Ai, Lane::Overflow) => Some(Output::AiOverflow),+ (Pipeline::Ai, Lane::Historical) => None,+ (Pipeline::Warnings, Lane::Main) => Some(Output::ClientWarningsMain),+ (Pipeline::Warnings, Lane::Overflow | Lane::Historical) => None,+ (Pipeline::Heatmaps, Lane::Main) => Some(Output::HeatmapsMain),+ (Pipeline::Heatmaps, Lane::Overflow | Lane::Historical) => None,+ (Pipeline::ErrorTracking, Lane::Main) => Some(Output::ErrorTrackingMain),+ (Pipeline::ErrorTracking, Lane::Overflow | Lane::Historical) => None,+ (Pipeline::Replay, Lane::Main) => Some(Output::SessionReplayMain),+ (Pipeline::Replay, Lane::Overflow) => Some(Output::SessionReplayOverflow),+ (Pipeline::Replay, Lane::Historical) => None,}-- Ok(match metadata.data_type {- DataType::AnalyticsHistorical => Route {- // Historical events never overflow — force_overflow and- // overflow_reason are deliberately ignored here.- target: Output::AnalyticsHistorical,- ordering: OrderingGuarantee::PerDistinctId,- },- DataType::AnalyticsMain => {- // Precedence: force_overflow (restrictions) -> overflow_reason- // (pipeline-stamped) -> default main-topic routing.- if metadata.force_overflow {- Route {- target: Output::AnalyticsOverflow,- ordering: person_ordering(metadata.person_processing_disabled()),- }- } else {- match &metadata.overflow_reason {- Some(OverflowReason::ForceLimited) => Route {- target: Output::AnalyticsOverflow,- ordering: OrderingGuarantee::None,- },- // The person flag alone decides the key here, in both- // directions. A burst keeps its key while person processing- // is on — the overflow consumer updates persons keyed on- // distinct id, so spreading one distinct id across- // partitions turns a hot key into contended person-row- // updates — which makes the locality preference irrelevant- // on this lane. And a key whose person processing is- // already off (the global rate limiter stamps its verdict- // before the overflow limiter overwrites the reason) must- // not get its partition back.- Some(OverflowReason::RateLimited { .. }) => Route {- target: Output::AnalyticsOverflow,- ordering: person_ordering(metadata.person_processing_disabled()),- },- // ReplayLimited is stamped only by the recordings pipeline,- // so an analytics event cannot carry it — the shared- // OverflowReason enum forces the arm, which treats the- // impossible stamp as unstamped.- Some(OverflowReason::ReplayLimited) | None => Route {- target: Output::AnalyticsMain,- ordering: person_ordering(metadata.person_processing_disabled()),- },- }- }- }- DataType::AiEvents => {- // Valve armed: the AI lanes route overflow like analytics, except- // that a burst may spread while person processing is on — the AI- // consumer reads persons without writing them, so keyless- // person-on records cause no person-update contention there.- // Valve unarmed: AI events never overflow —- // force_overflow and stamped reasons are deliberately ignored- // (the pipeline never stamps a reason on this lane anyway). The- // default route keeps the event key regardless of- // skip_person_processing (v1 only nulls keys for- // Main/Overflow-shaped destinations). AI events never reroute- // historical.- if ai_events_overflow_armed && metadata.force_overflow {- Route {- target: Output::AiOverflow,- ordering: person_ordering(metadata.person_processing_disabled()),- }- } else if ai_events_overflow_armed {- match &metadata.overflow_reason {- Some(OverflowReason::ForceLimited) => Route {- target: Output::AiOverflow,- ordering: OrderingGuarantee::None,- },- Some(OverflowReason::RateLimited {- preserve_locality: true,- }) => Route {- target: Output::AiOverflow,- // Same precedence as the analytics overflow lane above.- ordering: person_ordering(metadata.person_processing_disabled()),- },- Some(OverflowReason::RateLimited {- preserve_locality: false,- }) => Route {- target: Output::AiOverflow,- ordering: OrderingGuarantee::None,- },- // ReplayLimited cannot be stamped on the AI lane either;- // treated as unstamped, as above.- Some(OverflowReason::ReplayLimited) | None => Route {- target: Output::AiMain,- ordering: OrderingGuarantee::PerDistinctId,- },- }- } else {- Route {- target: Output::AiMain,- ordering: OrderingGuarantee::PerDistinctId,- }- }- }- DataType::ClientIngestionWarning => Route {- target: Output::ClientWarningsMain,- ordering: OrderingGuarantee::PerDistinctId,- },- DataType::HeatmapMain => Route {- target: Output::HeatmapsMain,- ordering: OrderingGuarantee::PerDistinctId,- },- DataType::ExceptionErrorTracking => Route {- target: Output::ErrorTrackingMain,- ordering: OrderingGuarantee::PerDistinctId,- },- DataType::SnapshotMain => {- // Precedence: force_overflow (restrictions) -> overflow_reason- // (pipeline-stamped ReplayLimited) -> default main-topic routing.- // Partition key is always session_id for replay to keep per-session- // ordering on the overflow topic; a missing id makes the decision- // unrealizable, so it is rejected as part of the decision.- if metadata.session_id.is_none() {- return Err(CaptureError::MissingSessionId);- }- let target = if metadata.force_overflow- || matches!(- metadata.overflow_reason,- Some(OverflowReason::ReplayLimited)- ) {- Output::SessionReplayOverflow- } else {- Output::SessionReplayMain- };- Route {- target,- ordering: OrderingGuarantee::PerSession,- }- }- })}-#[cfg(test)]-mod route_tests {- use super::*;- use rstest::rstest;-- fn meta(data_type: DataType) -> ProcessedEventMetadata {- ProcessedEventMetadata {- data_type,- session_id: Some("session123".to_string()),- computed_timestamp: None,- event_name: "test_event".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,- }- }-- #[test]- fn dlq_wins_over_custom_topic_and_datatype() {- // redirect_to_dlq set alongside redirect_to_topic and an overflow- // reason: DLQ still wins, keyed on the event key, with the DLQ effect.- let mut m = meta(DataType::AnalyticsMain);- m.redirect_to_dlq = true;- m.redirect_to_topic = Some("custom".to_string());- m.force_overflow = true;- assert_eq!(- route(&m, false).unwrap(),- Route {- target: Output::Dlq,- ordering: OrderingGuarantee::PerDistinctId,- }- );- }-- #[test]- fn custom_topic_wins_over_datatype() {- // Custom-topic redirect beats per-datatype/overflow routing (but not DLQ).- let mut m = meta(DataType::AnalyticsMain);- m.redirect_to_topic = Some("my_topic".to_string());- m.force_overflow = true;- assert_eq!(- route(&m, false).unwrap(),- Route {- target: Output::Custom("my_topic".to_string()),- ordering: OrderingGuarantee::PerDistinctId,- }- );- }-- #[test]- fn per_datatype_targets() {- for (dt, target) in [- (DataType::AnalyticsMain, Output::AnalyticsMain),- (DataType::AnalyticsHistorical, Output::AnalyticsHistorical),- (DataType::ClientIngestionWarning, Output::ClientWarningsMain),- (DataType::HeatmapMain, Output::HeatmapsMain),- (DataType::ExceptionErrorTracking, Output::ErrorTrackingMain),- (DataType::AiEvents, Output::AiMain),- (DataType::SnapshotMain, Output::SessionReplayMain),- ] {- let m = meta(dt);- let r = route(&m, false).unwrap();- assert_eq!(r.target, target, "wrong target for {dt:?}");- }- }-- #[test]- fn analytics_main_overflow_ordering() {- // force_overflow -> overflow topic; key policy follows skip_person.- let mut m = meta(DataType::AnalyticsMain);- m.force_overflow = true;- assert_eq!(- route(&m, false).unwrap().ordering,- OrderingGuarantee::PerDistinctId- );- m.skip_person_processing = true;- assert_eq!(route(&m, false).unwrap().ordering, OrderingGuarantee::None);- assert_eq!(route(&m, false).unwrap().target, Output::AnalyticsOverflow);- }-- #[test]- fn analytics_main_overflow_reason_precedence() {- let base = meta(DataType::AnalyticsMain);-- let mut force_limited = base.clone();- force_limited.overflow_reason = Some(OverflowReason::ForceLimited);- assert_eq!(- route(&force_limited, false).unwrap(),- Route {- target: Output::AnalyticsOverflow,- ordering: OrderingGuarantee::None,- }- );-- let mut preserve = base.clone();- preserve.overflow_reason = Some(OverflowReason::RateLimited {- preserve_locality: true,- });- assert_eq!(- route(&preserve, false).unwrap().ordering,- OrderingGuarantee::PerDistinctId- );- assert_eq!(- route(&preserve, false).unwrap().target,- Output::AnalyticsOverflow- );-- // The locality preference is irrelevant on the analytics lane: a- // person-on burst keeps its key either way, because the overflow- // consumer writes persons keyed on distinct id.- let mut no_preserve = base.clone();- no_preserve.overflow_reason = Some(OverflowReason::RateLimited {- preserve_locality: false,- });- assert_eq!(- route(&no_preserve, false).unwrap().ordering,- OrderingGuarantee::PerDistinctId- );- assert_eq!(- route(&no_preserve, false).unwrap().target,- Output::AnalyticsOverflow- );- no_preserve.skip_person_processing = true;- assert_eq!(- route(&no_preserve, false).unwrap().ordering,- OrderingGuarantee::None- );+/// The dlq output's contract: count the reroute and stamp the dlq header set.+fn dlq_reroute_effects(headers: &mut common_types::CapturedEventHeaders, reason: &'static str) {+ counter!("capture_events_rerouted_dlq", &[("reason", reason)]).increment(1);- // ReplayLimited cannot be stamped on analytics events (only the- // recordings pipeline produces it); the impossible combination is- // treated as unstamped.- let mut replay = base;- replay.overflow_reason = Some(OverflowReason::ReplayLimited);- assert_eq!(route(&replay, false).unwrap().target, Output::AnalyticsMain);- }-- /// The global rate limiter stamps `skip_person_processing` before the- /// overflow limiter runs, and the overflow limiter overwrites the reason it- /// stamped. Without this precedence a key the rate limiter declared too hot- /// would go back to hashing onto a single overflow partition whenever the- /// limiter preserves locality, which is how prod-US is configured.- #[rstest]- #[case::analytics(DataType::AnalyticsMain, Output::AnalyticsOverflow)]- #[case::ai(DataType::AiEvents, Output::AiOverflow)]- fn person_processing_off_outranks_preserve_locality(- #[case] data_type: DataType,- #[case] expected_target: Output,- ) {- let armed = data_type == DataType::AiEvents;- let mut m = meta(data_type);- m.overflow_reason = Some(OverflowReason::RateLimited {- preserve_locality: true,- });-- assert_eq!(- route(&m, armed).unwrap().ordering,- OrderingGuarantee::PerDistinctId,- "locality is preserved while person processing is on"- );-- m.skip_person_processing = true;- assert_eq!(- route(&m, armed).unwrap(),- Route {- target: expected_target,- ordering: OrderingGuarantee::None,- }- );- }-- #[test]- fn ai_events_overflow_gated_on_valve() {- // Valve unarmed: force_overflow and stamped reasons are ignored — the- // AI lane never overflows and keeps its event key.- let mut m = meta(DataType::AiEvents);- m.force_overflow = true;- assert_eq!(- route(&m, false).unwrap(),- Route {- target: Output::AiMain,- ordering: OrderingGuarantee::PerDistinctId,- }- );-- // Valve armed: mirrors the analytics main lane's overflow handling.- assert_eq!(route(&m, true).unwrap().target, Output::AiOverflow);- assert_eq!(- route(&m, true).unwrap().ordering,- OrderingGuarantee::PerDistinctId- );- m.skip_person_processing = true;- assert_eq!(route(&m, true).unwrap().ordering, OrderingGuarantee::None);-- let mut force_limited = meta(DataType::AiEvents);- force_limited.overflow_reason = Some(OverflowReason::ForceLimited);- assert_eq!(- route(&force_limited, true).unwrap(),- Route {- target: Output::AiOverflow,- ordering: OrderingGuarantee::None,- }- );- assert_eq!(route(&force_limited, false).unwrap().target, Output::AiMain);- }-- #[test]- fn ai_events_default_route_keeps_event_key() {- // skip_person_processing must not null the key on the AI default- // route: v1 only nulls keys for Main/Overflow-shaped destinations.- let mut m = meta(DataType::AiEvents);- m.skip_person_processing = true;- for armed in [false, true] {- assert_eq!(- route(&m, armed).unwrap(),- Route {- target: Output::AiMain,- ordering: OrderingGuarantee::PerDistinctId,- },- "armed={armed}"- );- }- }-- #[test]- fn snapshot_routing_uses_session_id_key() {- let mut m = meta(DataType::SnapshotMain);- assert_eq!(- route(&m, false).unwrap(),- Route {- target: Output::SessionReplayMain,- ordering: OrderingGuarantee::PerSession,- }- );-- m.force_overflow = true;- assert_eq!(- route(&m, false).unwrap().target,- Output::SessionReplayOverflow- );- assert_eq!(- route(&m, false).unwrap().ordering,- OrderingGuarantee::PerSession- );-- m.force_overflow = false;- m.overflow_reason = Some(OverflowReason::ReplayLimited);- assert_eq!(- route(&m, false).unwrap().target,- Output::SessionReplayOverflow- );- }-- /// A replay event with no session id has no realizable route — the- /// decision itself rejects, rather than handing the sink a `PerSession`- /// guarantee it cannot key.- #[test]- fn snapshot_without_session_id_is_rejected() {- let mut m = meta(DataType::SnapshotMain);- m.session_id = None;- assert!(matches!(- route(&m, false),- Err(CaptureError::MissingSessionId)- ));-- // A dlq redirect keys on the event key, so it stays realizable- // without a session id.- m.redirect_to_dlq = true;- assert_eq!(route(&m, false).unwrap().target, Output::Dlq);- }+ headers.set_dlq_reason(reason.to_string());+ // Unlike with our node code, DLQ step will always be static.+ headers.set_dlq_step("capture".to_string());+ headers+ .set_dlq_timestamp(chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true));}/// The default KafkaSink using rdkafka's FutureProducer@@ -869,17 +460,48 @@ impl<P: KafkaProducer> KafkaSinkBase<P> {headers.set_skip_heatmap_processing(true);}- // The routing decision is pure metadata policy; the sink resolves the- // target against its topic config, the key policy against the values- // it owns, and applies the target-implied side effects.- let decision = route(&metadata, self.topics.ai_events_overflow_armed())?;+ // The address decision is pure metadata policy, owned by the pipeline+ // layer; the sink bridges it to an output, resolves that against its+ // topic config, realizes the key policy against the values it owns,+ // and applies the address-implied side effects in the same match —+ // the dlq output's contract includes the dlq header set, and both+ // admin redirects count their reroutes.+ let decision = pipeline::resolve(&metadata, self.topics.ai_events_overflow_armed())?;+ let target = match decision.address {+ Address::Dlq => {+ dlq_reroute_effects(&mut headers, "event_restriction");+ Output::Dlq+ }+ Address::Custom(topic) => {+ counter!(+ "capture_events_rerouted_custom_topic",+ &[("reason", "event_restriction")]+ )+ .increment(1);+ Output::Custom(topic)+ }+ Address::Lane { pipeline, lane } => match lane_output(pipeline, lane) {+ Some(output) => output,+ // A pair `resolve` never produces: no output backs it, so+ // the event goes to the dlq — preserved and replayable —+ // instead of being processed through a lane with the wrong+ // semantics. Loud, because reaching this arm means a change+ // made the pair producible without giving it an output.+ None => {+ debug_assert!(false, "no output backs ({pipeline:?}, {lane:?})");+ error!("no output backs ({pipeline:?}, {lane:?}), publishing to the dlq");+ dlq_reroute_effects(&mut headers, "unbacked_lane");+ Output::Dlq+ }+ },+ };- let topic: &str = self.topics.topic_for(&decision.target);+ let topic: &str = self.topics.topic_for(&target);let partition_key: Option<&str> = match decision.ordering {OrderingGuarantee::PerDistinctId => Some(event_key.as_str()),OrderingGuarantee::None => None,- // route() rejects replay events without a session id, so the id+ // resolve() rejects replay events without a session id, so the id// is present whenever PerSession is decided.OrderingGuarantee::PerSession => Some(metadata@@ -889,34 +511,6 @@ impl<P: KafkaProducer> KafkaSinkBase<P> {),};- // Output-implied side effects: the dlq output's contract includes the- // dlq header set, and both redirect outputs count their reroutes.- match decision.target {- Output::Dlq => {- counter!(- "capture_events_rerouted_dlq",- &[("reason", "event_restriction")]- )- .increment(1);-- // DLQ reason cannot be known beyond being triggered by an event restriction.- headers.set_dlq_reason("event_restriction".to_string());- // Unlike with our node code, DLQ step will always be static.- headers.set_dlq_step("capture".to_string());- headers.set_dlq_timestamp(- chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true),- );- }- Output::Custom(_) => {- counter!(- "capture_events_rerouted_custom_topic",- &[("reason", "event_restriction")]- )- .increment(1);- }- _ => {}- }-if let Some(encoding) = serializer.content_encoding() {headers.set_content_encoding(encoding.to_string());}diff --git a/rust/capture/tests/common/utils.rs b/rust/capture/tests/common/utils.rsindex 94f5b6af11f5..b224e1fbf821 100644--- a/rust/capture/tests/common/utils.rs+++ b/rust/capture/tests/common/utils.rs@@ -211,6 +211,7 @@ pub struct ServerHandle {pub addr: SocketAddr,shutdown: tokio_util::sync::CancellationToken,client: reqwest::Client,+ event_restriction_service: Option<capture::event_restrictions::EventRestrictionService>,}impl ServerHandle {@@ -331,6 +332,7 @@ impl ServerHandle {let handles = setup::register_components(&mut manager, &config);let _monitor = manager.monitor_background();let components = setup::build_components(config, sink_env, handles).await;+ let event_restriction_service = components.event_restriction_service.clone();tokio::spawn(async move { serve(listener, components).await });@@ -343,6 +345,26 @@ impl ServerHandle {addr,shutdown: shutdown_token,client,+ event_restriction_service,+ }+ }++ /// Wait for the event restriction service's first successful load. Entries+ /// written to Redis before boot are guaranteed visible after this returns,+ /// because a refresh fetches every restriction type and swaps the manager+ /// atomically.+ pub async fn wait_for_restrictions_loaded(&self) {+ let service = self+ .event_restriction_service+ .as_ref()+ .expect("server booted without event restrictions enabled");+ let deadline = tokio::time::Instant::now() + Duration::from_secs(10);+ while !service.has_loaded() {+ assert!(+ tokio::time::Instant::now() < deadline,+ "event restrictions not loaded within 10s"+ );+ tokio::time::sleep(Duration::from_millis(10)).await;}}@@ -593,6 +615,19 @@ impl EphemeralTopic {pub fn next_message_with_headers(&self,) -> anyhow::Result<(serde_json::Value, std::collections::HashMap<String, String>)> {+ let (_key, event, headers) = self.next_message_full()?;+ Ok((event, headers))+ }++ /// Like `next_message_with_headers`, also returning the partition key, so+ /// one consumed message can assert key, payload, and headers together.+ pub fn next_message_full(+ &self,+ ) -> anyhow::Result<(+ Option<String>,+ serde_json::Value,+ std::collections::HashMap<String, String>,+ )> {use std::collections::HashMap;// Retry on transient Kafka errors like NotCoordinator@@ -602,11 +637,14 @@ impl EphemeralTopic {loop {match self.consumer.poll(self.read_timeout) {Some(Ok(message)) => {- // Parse the payload+ let key = match message.key() {+ Some(key) => Some(String::from_str(std::str::from_utf8(key)?)?),+ None => None,+ };+let body = message.payload().expect("empty kafka message");let event = serde_json::from_slice(body)?;- // Parse the headerslet mut headers = HashMap::new();if let Some(message_headers) = message.headers() {for header in message_headers.iter() {@@ -618,7 +656,7 @@ impl EphemeralTopic {}}- return Ok((event, headers));+ return Ok((key, event, headers));}Some(Err(err)) => {// Check if it's a transient error that should be retrieddiff --git a/rust/capture/tests/routing_e2e.rs b/rust/capture/tests/routing_e2e.rsnew file mode 100644index 000000000000..dfeddca10612--- /dev/null+++ b/rust/capture/tests/routing_e2e.rs@@ -0,0 +1,275 @@+//! End-to-end routing coverage over a real broker: HTTP request → pipeline+//! stamps → address resolution → a message on the addressed topic.+//!+//! The routing goldens (`sinks/kafka.rs`) pin the produce contract against a+//! capturing mock producer, and the restriction integration suites pin the+//! stamped metadata; each half is covered, but only a real-broker test+//! catches the two halves agreeing with each other while being wrong about+//! the wire. This suite covers the addresses no other real-broker test+//! consumes: the dlq and custom admin redirects and the AI lanes.++#[path = "common/utils.rs"]+mod utils;+use utils::*;++use anyhow::Result;+use assert_json_diff::assert_json_include;+use redis::Commands;+use reqwest::StatusCode;+use serde_json::json;+use std::num::NonZeroU32;++/// Writes restriction entries at the production Redis key for one restriction+/// type, deleting the key on drop. The production repository reads+/// unprefixed keys, so parallel safety comes from ownership discipline: each+/// test owns a distinct restriction type, and tokens are random, so another+/// concurrently booted server reading this key sees only inert entries.+struct RestrictionKey {+ key: String,+}++impl RestrictionKey {+ fn set(restriction_type: &str, entries: serde_json::Value) -> Self {+ let key = format!("event_ingestion_restriction_dynamic_config:{restriction_type}");+ let client = redis::Client::open(DEFAULT_CONFIG.redis_url.as_str())+ .expect("failed to create redis client");+ let mut conn = client.get_connection().expect("failed to connect to redis");+ conn.set::<_, _, ()>(&key, entries.to_string())+ .expect("failed to write restriction entries");+ Self { key }+ }+}++impl Drop for RestrictionKey {+ fn drop(&mut self) {+ if let Ok(client) = redis::Client::open(DEFAULT_CONFIG.redis_url.as_str()) {+ if let Ok(mut conn) = client.get_connection() {+ drop(conn.del::<_, ()>(&self.key));+ }+ }+ }+}++#[tokio::test]+async fn it_routes_dlq_redirected_events_to_the_dlq_topic() -> Result<()> {+ setup_tracing();+ let token = random_string("token", 16);+ let distinct_id = random_string("id", 16);++ let main_topic = EphemeralTopic::new().await;+ let dlq_topic = EphemeralTopic::new().await;++ let _restriction = RestrictionKey::set(+ "redirect_to_dlq",+ json!([{"version": 2, "token": token, "pipelines": ["analytics"]}]),+ );++ let mut config = DEFAULT_CONFIG.clone();+ config.kafka.kafka_topic = main_topic.topic_name().to_string();+ config.kafka.kafka_dlq_topic = dlq_topic.topic_name().to_string();+ config.event_restrictions_enabled = true;+ config.event_restrictions_redis_url = Some(config.redis_url.clone());+ // A failed first load (tight Redis timeout on a busy runner) retries on+ // the next tick; keep that tick close so the loaded-state wait recovers.+ config.event_restrictions_refresh_interval_secs = 1;+ let server = ServerHandle::for_config(config).await;+ server.wait_for_restrictions_loaded().await;++ let event = json!({+ "token": token,+ "event": "testing",+ "distinct_id": distinct_id+ });+ let res = server.capture_events(event.to_string()).await;+ assert_eq!(StatusCode::OK, res.status());++ let (key, event, headers) = dlq_topic.next_message_full()?;+ assert_eq!(+ key,+ Some(format!("{token}:{distinct_id}")),+ "dlq messages must keep the event key"+ );+ assert_json_include!(+ actual: event,+ expected: json!({+ "token": token,+ "distinct_id": distinct_id+ })+ );+ assert_eq!(+ headers.get("dlq_reason"),+ Some(&"event_restriction".to_string())+ );+ assert_eq!(headers.get("dlq_step"), Some(&"capture".to_string()));+ assert!(+ headers.contains_key("dlq_timestamp"),+ "dlq messages must carry a dlq_timestamp header"+ );++ main_topic.assert_empty();+ Ok(())+}++#[tokio::test]+async fn it_routes_custom_redirected_events_to_the_admin_topic() -> Result<()> {+ setup_tracing();+ let token = random_string("token", 16);+ let distinct_id = random_string("id", 16);++ let main_topic = EphemeralTopic::new().await;+ let custom_topic = EphemeralTopic::new().await;++ let _restriction = RestrictionKey::set(+ "redirect_to_topic",+ json!([{+ "version": 2,+ "token": token,+ "pipelines": ["analytics"],+ "args": {"topic": custom_topic.topic_name()}+ }]),+ );++ let mut config = DEFAULT_CONFIG.clone();+ config.kafka.kafka_topic = main_topic.topic_name().to_string();+ config.event_restrictions_enabled = true;+ config.event_restrictions_redis_url = Some(config.redis_url.clone());+ // A failed first load (tight Redis timeout on a busy runner) retries on+ // the next tick; keep that tick close so the loaded-state wait recovers.+ config.event_restrictions_refresh_interval_secs = 1;+ let server = ServerHandle::for_config(config).await;+ server.wait_for_restrictions_loaded().await;++ let event = json!({+ "token": token,+ "event": "testing",+ "distinct_id": distinct_id+ });+ let res = server.capture_events(event.to_string()).await;+ assert_eq!(StatusCode::OK, res.status());++ let (key, event, headers) = custom_topic.next_message_full()?;+ assert_eq!(+ key,+ Some(format!("{token}:{distinct_id}")),+ "custom-redirected messages must keep the event key"+ );+ assert_json_include!(+ actual: event,+ expected: json!({+ "token": token,+ "distinct_id": distinct_id+ })+ );+ assert!(+ !headers.contains_key("dlq_reason"),+ "a custom redirect is not a dlq: no dlq headers"+ );++ main_topic.assert_empty();+ Ok(())+}++#[tokio::test]+async fn it_routes_diverted_ai_events_to_the_ai_topic() -> Result<()> {+ setup_tracing();+ let token = random_string("token", 16);+ let distinct_id = random_string("id", 16);++ let main_topic = EphemeralTopic::new().await;+ let ai_topic = EphemeralTopic::new().await;++ let mut config = DEFAULT_CONFIG.clone();+ config.kafka.kafka_topic = main_topic.topic_name().to_string();+ config.kafka.capture_analytics_ai_events_topic = ai_topic.topic_name().to_string();+ let server = ServerHandle::for_config(config).await;++ let batch = json!([+ {+ "token": token,+ "event": "$ai_generation",+ "distinct_id": distinct_id+ },+ {+ "token": token,+ "event": "$pageview",+ "distinct_id": distinct_id+ }+ ]);+ let res = server.capture_events(batch.to_string()).await;+ assert_eq!(StatusCode::OK, res.status());++ // The diverted AI event lands on the AI topic, keyed on the event key.+ let (key, event, _headers) = ai_topic.next_message_full()?;+ assert_eq!(key, Some(format!("{token}:{distinct_id}")));+ assert_json_include!(+ actual: event,+ expected: json!({+ "token": token,+ "distinct_id": distinct_id+ })+ );+ ai_topic.assert_empty();++ // The non-AI event from the same batch stays on the main topic.+ let event = main_topic.next_event()?;+ assert_json_include!(+ actual: event,+ expected: json!({+ "token": token,+ "distinct_id": distinct_id+ })+ );+ main_topic.assert_empty();+ Ok(())+}++#[tokio::test]+async fn it_routes_forced_ai_events_to_ai_overflow_when_the_valve_is_armed() -> Result<()> {+ setup_tracing();+ let token = random_string("token", 16);+ let distinct_id = random_string("id", 16);++ let main_topic = EphemeralTopic::new().await;+ let ai_topic = EphemeralTopic::new().await;+ let ai_overflow_topic = EphemeralTopic::new().await;++ let mut config = DEFAULT_CONFIG.clone();+ config.kafka.kafka_topic = main_topic.topic_name().to_string();+ config.kafka.capture_analytics_ai_events_topic = ai_topic.topic_name().to_string();+ config.kafka.capture_analytics_ai_events_overflow_topic =+ Some(ai_overflow_topic.topic_name().to_string());+ config.overflow_enabled = true;+ config.overflow_burst_limit = NonZeroU32::new(10).unwrap();+ config.overflow_per_second_limit = NonZeroU32::new(10).unwrap();+ config.ingestion_force_overflow_by_token_distinct_id = Some(token.clone());+ let server = ServerHandle::for_config(config).await;++ let event = json!({+ "token": token,+ "event": "$ai_generation",+ "distinct_id": distinct_id+ });+ let res = server.capture_events(event.to_string()).await;+ assert_eq!(StatusCode::OK, res.status());++ // A force-limited AI key overflows to the AI overflow topic — never the+ // analytics overflow — with the key dropped and person processing off.+ let (key, event, headers) = ai_overflow_topic.next_message_full()?;+ assert_eq!(key, None, "force-limited overflow must drop the event key");+ assert_json_include!(+ actual: event,+ expected: json!({+ "token": token,+ "distinct_id": distinct_id+ })+ );+ assert_eq!(+ headers.get("force_disable_person_processing"),+ Some(&"true".to_string()),+ "a force-limited key implies person processing off"+ );++ ai_topic.assert_empty();+ main_topic.assert_empty();+ Ok(())+}