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): arm ai overflow with AI_EVENTS_OVERFLOW_ENABLED (#117144)

Paweł Ledwońc95f33fc31ba
diff --git a/rust/capture/src/config.rs b/rust/capture/src/config.rs
index 9c3d89cd6880..fd2bca6e35a0 100644
--- a/rust/capture/src/config.rs
+++ b/rust/capture/src/config.rs
@@ -11,13 +11,11 @@ pub enum CaptureMode {
Events,
Recordings,
Ai,
- /// Analytics ingestion dedicated to historical backfills (the
- /// batch-import-worker). Like `Events` for the batch/event paths, but with
- /// three differences: it never applies the global rate limiter, it drops any
- /// batch not flagged `historical_migration: true`, and it does not register
- /// the AI or OTEL routes (those handlers hardcode `historical_migration:
- /// false` and would bypass both gates). See `applies_global_rate_limit`,
- /// `requires_historical_migration`, and the router's per-mode arm.
+ /// Analytics ingestion for historical backfills (the batch-import-worker).
+ /// Unlike `Events`, it skips the global rate limiter, drops batches not
+ /// flagged `historical_migration: true`, serves no AI or OTEL routes (their
+ /// handlers hardcode `historical_migration: false`), and has no AI overflow
+ /// lane.
Import,
}
@@ -48,6 +46,11 @@ impl CaptureMode {
pub fn requires_historical_migration(&self) -> bool {
matches!(self, CaptureMode::Import)
}
+
+ /// Import has no AI overflow lane: imports must never overflow.
+ pub fn has_ai_overflow_lane(&self) -> bool {
+ !matches!(self, CaptureMode::Import)
+ }
}
impl std::str::FromStr for CaptureMode {
@@ -271,6 +274,11 @@ pub struct Config {
#[envconfig(default = "false")]
pub overflow_enabled: bool,
+ /// Builds the AI lane's overflow limiter when `overflow_enabled` is also
+ /// set. Restriction overflow does not need it.
+ #[envconfig(default = "false")]
+ pub ai_events_overflow_enabled: bool,
+
#[envconfig(default = "false")]
pub overflow_preserve_partition_locality: bool,
@@ -310,7 +318,7 @@ pub struct Config {
#[envconfig(default = "capture")]
pub otel_service_name: String,
- // Used for integration tests
+ /// Install the Prometheus recorder and the limiters' metric tasks.
#[envconfig(default = "true")]
pub export_prometheus: bool,
pub redis_key_prefix: Option<String>,
@@ -418,14 +426,10 @@ pub struct Config {
pub capture_v1_scatter_gather_min_batch: usize,
// --- Ingestion warnings emitter (fire-and-forget, best-effort) ---
- // Warnings are emitted as `$$client_ingestion_warning` events onto the
- // existing `client_ingestion_warning` topic, by default on the main event
- // cluster: absent the warnings-cluster overrides below, the producer
- // reuses the main cluster's hosts/TLS — but it gets its OWN dedicated
- // `common_kafka::config::KafkaConfig` (below) with fire-and-forget
- // acks/retries and a small queue, so a saturated or slow warnings topic
- // can never behave like — or contend with — the main event producer.
- // Defaults off (fail open).
+ // Warnings go out as `$$client_ingestion_warning` events through a
+ // dedicated `common_kafka::config::KafkaConfig` with fire-and-forget
+ // acks/retries and a small queue, so a slow warnings topic cannot contend
+ // with the main event producer. Defaults off (fail open).
#[envconfig(default = "false")]
pub capture_ingestion_warnings_enabled: bool,
@@ -586,12 +590,11 @@ pub struct OutputsConfig {
pub ai_main_topic: String,
#[envconfig(from = "CAPTURE_OUTPUT_AI_MAIN_PRODUCER", default = "INGESTION")]
pub ai_main_producer: ProducerName,
- /// Unset means AI events never overflow. When set, the AI lane uses the
- /// analytics main lane's overflow limiter and restriction-driven
- /// force_overflow, and reroutes here. Import mode refuses it at boot
- /// because imports must never overflow.
- #[envconfig(from = "CAPTURE_OUTPUT_AI_OVERFLOW_TOPIC")]
- pub ai_overflow_topic: Option<String>,
+ #[envconfig(
+ from = "CAPTURE_OUTPUT_AI_OVERFLOW_TOPIC",
+ default = "events_plugin_ingestion_ai_overflow"
+ )]
+ pub ai_overflow_topic: String,
#[envconfig(from = "CAPTURE_OUTPUT_AI_OVERFLOW_PRODUCER", default = "INGESTION")]
pub ai_overflow_producer: ProducerName,
/// Carries event-restriction redirects to an admin-supplied topic.
@@ -683,7 +686,11 @@ mod tests {
let config: Config =
envconfig::Envconfig::init_from_hashmap(&required_config_env()).unwrap();
assert_eq!(config.outputs.ai_main_topic, "events_plugin_ingestion_ai");
- assert_eq!(config.outputs.ai_overflow_topic, None);
+ assert_eq!(
+ config.outputs.ai_overflow_topic,
+ "events_plugin_ingestion_ai_overflow"
+ );
+ assert!(!config.ai_events_overflow_enabled);
assert_eq!(
config.outputs.session_replay_main_topic,
"session_recording_snapshot_item_events"
@@ -705,7 +712,7 @@ mod tests {
#[case("CAPTURE_OUTPUT_ERROR_TRACKING_TOPIC", |c: &Config| c.outputs.error_tracking_topic.clone())]
#[case("CAPTURE_OUTPUT_DLQ_TOPIC", |c: &Config| c.outputs.dlq_topic.clone())]
#[case("CAPTURE_OUTPUT_AI_MAIN_TOPIC", |c: &Config| c.outputs.ai_main_topic.clone())]
- #[case("CAPTURE_OUTPUT_AI_OVERFLOW_TOPIC", |c: &Config| c.outputs.ai_overflow_topic.clone().unwrap_or_default())]
+ #[case("CAPTURE_OUTPUT_AI_OVERFLOW_TOPIC", |c: &Config| c.outputs.ai_overflow_topic.clone())]
fn topic_env_var_binds_to_its_field(
#[case] env_var: &str,
#[case] field: fn(&Config) -> String,
@@ -743,7 +750,7 @@ mod tests {
outputs.error_tracking_topic.as_str(),
outputs.dlq_topic.as_str(),
outputs.ai_main_topic.as_str(),
- outputs.ai_overflow_topic.as_deref().unwrap_or_default(),
+ outputs.ai_overflow_topic.as_str(),
];
assert!(!topics.contains(&"legacy_topic"), "{env_var} is still read");
}
diff --git a/rust/capture/src/events/analytics.rs b/rust/capture/src/events/analytics.rs
index 0dbb79821cba..ae7f48142165 100644
--- a/rust/capture/src/events/analytics.rs
+++ b/rust/capture/src/events/analytics.rs
@@ -231,14 +231,9 @@ pub fn process_single_event(
/// (resolved into `DataType::AiEvents` at classification time), event
/// restrictions, the AI lane's per-project byte budget, 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
-/// (`ai_endpoint::ai_handler`) and OTEL (`otel::otel_handler`) paths also
-/// call so every `DataType::AnalyticsMain` event gets identical limiter
-/// semantics regardless of entry point. The kafka sink is a pure mechanism
-/// layer — it reads `ProcessedEventMetadata::data_type`,
-/// `overflow_reason`, `force_overflow`, `redirect_to_dlq`, and
-/// `redirect_to_topic` to decide which topic and key to produce to.
+/// overflow rerouting via [`OverflowLimiter`]. Overflow stamping goes through
+/// [`stamp_overflow_reason`], shared with the AI and OTEL handlers. The sink
+/// maps the stamped metadata to an address through [`crate::pipeline::resolve`].
#[instrument(skip_all, fields(events = events.len(), request_id))]
#[allow(clippy::too_many_arguments)]
pub async fn process_events(
@@ -434,10 +429,10 @@ async fn process_events_inner(
// selects which slice of restrictions applies to each event. A DropEvent
// tagged only for `analytics` will never silently drop an exception event
// on the way to the error tracking topic, and vice versa. Snapshots have
- // no pipeline here and flow through unrestricted. `AiEvents` looks up the `ai` pipeline: a diverted
- // AI event is governed by ai-scoped restrictions (drop/DLQ/redirect still
- // win over the lane, redirect_to_topic beats the AI topic in the sink,
- // force_overflow keeps it on the AI lane) -- mirroring v1.
+ // no pipeline here and flow through unrestricted. `AiEvents` looks up the
+ // `ai` pipeline, so ai-scoped restrictions govern a diverted AI event.
+ // `force_overflow` sends it to the AI overflow lane where the deployment
+ // has one, never to analytics overflow.
if let Some(ref service) = restriction_service {
let mut filtered_events = Vec::with_capacity(events.len());
let now_ts = context.now.timestamp();
@@ -518,10 +513,9 @@ async fn process_events_inner(
if limited {
event.metadata.skip_person_processing = true;
- // Reroute the hot key to overflow. AnalyticsMain only: historical
- // never overflows, the AI lane keeps its dedicated topic (v1
- // gates the same way on Destination::AnalyticsMain), and only
- // AnalyticsMain acts on overflow_reason.
+ // Reroute the hot key to overflow on AnalyticsMain only. Historical
+ // never overflows. An AI hot key loses person processing but stays
+ // on its lane.
if event.metadata.data_type == DataType::AnalyticsMain {
event.metadata.overflow_reason = Some(OverflowReason::ForceLimited);
}
@@ -2403,26 +2397,22 @@ mod tests {
);
}
- struct AiValveCase {
+ struct AiLimiterCase {
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_OUTPUT_AI_OVERFLOW_TOPIC` is
- /// configured), and keeps its AI lane either way.
#[rstest]
- #[case::limiter_present(AiValveCase {
+ #[case::limiter_present(AiLimiterCase {
ai_limiter_present: true,
expected_reason: Some(OverflowReason::ForceLimited),
})]
- #[case::limiter_absent(AiValveCase {
+ #[case::limiter_absent(AiLimiterCase {
ai_limiter_present: false,
expected_reason: None,
})]
#[tokio::test]
- async fn test_ai_events_overflow_stamp_gated_on_limiter_presence(#[case] case: AiValveCase) {
+ async fn test_ai_events_overflow_stamp_gated_on_limiter_presence(#[case] case: AiLimiterCase) {
let now = DateTime::parse_from_rfc3339("2023-01-01T12:00:00Z")
.unwrap()
.with_timezone(&Utc);
diff --git a/rust/capture/src/events/overflow_stamping.rs b/rust/capture/src/events/overflow_stamping.rs
index c5d22c6f6dd3..45162fda5f8c 100644
--- a/rust/capture/src/events/overflow_stamping.rs
+++ b/rust/capture/src/events/overflow_stamping.rs
@@ -1,23 +1,8 @@
-//! Shared overflow-reason stamping for analytics + AI + OTEL pipelines.
-//!
-//! The in-process `OverflowLimiter` (governor-backed, keyed on
-//! `token:distinct_id`) used to live inside `KafkaSinkBase::prepare_record`,
-//! which meant every `DataType::AnalyticsMain` event reaching the sink was
-//! checked uniformly regardless of which handler produced it. After the
-//! sink became a pure mechanism layer, the check was moved upstream into
-//! `events::analytics::process_events`. That covers the `/e/`, `/batch/`,
-//! `/capture` etc. endpoints but NOT the AI (`/i/v0/ai`) or OTEL
-//! (`/i/v0/ai/otel`) endpoints, which build `ProcessedEvent`s of their own
-//! and call `state.sink.send` / `state.sink.send_batch` directly.
-//!
-//! [`stamp_overflow_reason`] is the single source of truth for that check
-//! so all three call sites — analytics, AI, OTEL — get identical semantics
-//! and metric labels. Triplicating the loop would invite drift; routing
-//! the call through one helper keeps the contract testable in one place.
-//!
-//! The helper is sync because the `OverflowLimiter` governor check is sync
-//! (unlike the replay redis limiter, which still lives in the recordings
-//! pipeline as an async call).
+//! Overflow-reason stamping shared by the analytics, AI (`/i/v0/ai`) and OTEL
+//! (`/i/v0/ai/otel`) handlers. The AI and OTEL handlers bypass
+//! `events::analytics::process_events`, so each one calls
+//! [`stamp_overflow_reason`] itself. The helper is sync because the
+//! `OverflowLimiter` check is sync.
use std::sync::Arc;
@@ -30,34 +15,25 @@ use crate::v0_request::{DataType, OverflowReason, ProcessedEvent};
/// event in `events`, consulting the lane's limiter and the pre-existing
/// `force_overflow` flag stamped by event restrictions.
///
-/// Two lanes can overflow: `AnalyticsMain` always, and `AiEvents` only when
-/// its limiter is present — setup builds `ai_limiter` exactly when the AI
-/// overflow valve (`CAPTURE_OUTPUT_AI_OVERFLOW_TOPIC`) is armed and
-/// overflow is enabled, so limiter presence IS the valve here; the kafka sink
-/// independently ignores overflow stamps on the AI lane when the topic is
-/// unset. Each lane consults its own limiter instance — `analytics_limiter`
-/// for `AnalyticsMain`, `ai_limiter` for `AiEvents` — so per-key budgets are
+/// Two lanes can overflow: `AnalyticsMain` and `AiEvents`. Each lane consults
+/// its own limiter instance — `analytics_limiter` for `AnalyticsMain`, `ai_limiter` for `AiEvents` — so per-key budgets are
/// isolated: analytics volume never pushes a key's AI events into AI overflow
/// and vice versa. The stamp carries no topic; the kafka sink maps it to the
/// lane's own overflow topic, so an overflowing AI event lands on AI
/// overflow, never analytics overflow.
///
-/// Behavior (matches the pre-refactor sink semantics byte-for-byte):
+/// Behavior:
/// * Events on non-overflowing lanes are skipped (heatmaps, exceptions,
/// client-ingestion-warnings, etc. never overflow).
/// * `force_overflow = true` (set upstream by event restrictions) emits the
/// `event_restriction` counter and short-circuits — the limiter is NOT
-/// consulted, matching the pre-refactor sink ordering. This runs on both
+/// consulted. This runs on both
/// overflowing lanes regardless of limiter presence: the sink honors
/// `force_overflow` on its own (restriction rerouting must survive
/// `OVERFLOW_ENABLED=false`). The counter can over-report in one corner —
-/// a forced AI event with the valve unarmed is counted here but ignored by
-/// the sink; only the sink knows the valve.
-/// * If the lane's limiter is `None`, only the `event_restriction`
-/// short-circuit can stamp anything; otherwise the event passes through
-/// untouched. The AI lane's limiter exists exactly when the AI overflow
-/// valve is armed and overflow is enabled, so absence keeps AI events out
-/// of rate-limit overflow.
+/// a forced AI event on Import is counted here but ignored by the sink;
+/// only the sink knows the deployment's lanes.
+/// * If the lane's limiter is `None`, the event passes through untouched.
/// * If the lane's limiter is `Some`, `is_limited(event.key())` is consulted
/// and the resulting [`OverflowReason`] is stamped, plus the matching
/// counter. `ForceLimited` additionally sets `skip_person_processing =
@@ -65,9 +41,8 @@ use crate::v0_request::{DataType, OverflowReason, ProcessedEvent};
/// `force_disable_person_processing` header from the reason itself, so
/// the header does not depend on this stamp.
///
-/// Counter labels are intentionally identical to the pre-refactor sink so
-/// existing dashboards (filtering on `capture_events_rerouted_overflow`'s
-/// `reason` label) keep working without dashboard-side changes.
+/// Dashboards filter on the `reason` label of `capture_events_rerouted_overflow`,
+/// so keep its values stable.
pub fn stamp_overflow_reason(
events: &mut [ProcessedEvent],
analytics_limiter: Option<&Arc<OverflowLimiter>>,
@@ -287,11 +262,6 @@ mod tests {
#[test]
fn non_analytics_main_events_are_skipped() {
- // SnapshotMain has its own (replay) overflow path; HeatmapMain,
- // ExceptionErrorTracking, ClientIngestionWarning, AnalyticsHistorical,
- // and AiEvents (with the AI overflow valve unarmed) never overflow.
- // Even with a limiter that would otherwise force-route their key, the
- // helper must leave them untouched.
let limiter = build_limiter(10, 10, Some("phc_t:u".to_string()), false);
let mut events = vec![
build_event(DataType::SnapshotMain, "phc_t", "u", false),
@@ -377,9 +347,6 @@ mod tests {
);
}
- /// The AI lane joins overflow stamping only when its limiter is present
- /// (setup builds it exactly when the AI overflow valve is armed); absent
- /// keeps today's never-overflows behavior even for a force-routed key.
#[rstest::rstest]
#[case::limiter_present(true, Some(OverflowReason::ForceLimited), true)]
#[case::limiter_absent(false, None, false)]
@@ -472,7 +439,7 @@ mod tests {
}
#[test]
- fn ai_events_force_overflow_short_circuits_when_armed() {
+ fn ai_events_force_overflow_short_circuits() {
// Identical to the analytics lane: a restriction-driven
// force_overflow bypasses the limiter and leaves the reason unset;
// the sink routes on the flag alone.
diff --git a/rust/capture/src/pipeline.rs b/rust/capture/src/pipeline.rs
index 8dd7989eab92..89ea9d5ac0e6 100644
--- a/rust/capture/src/pipeline.rs
+++ b/rust/capture/src/pipeline.rs
@@ -61,9 +61,10 @@ pub enum Address {
/// 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
+/// upstream by the pipeline) and whether the deployment has an AI overflow
+/// lane — 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,
@@ -101,7 +102,7 @@ impl AddressDecision {
/// returned decision is realizable by the sink.
pub fn resolve(
metadata: &ProcessedEventMetadata,
- ai_events_overflow_armed: bool,
+ has_ai_overflow_lane: bool,
) -> Result<AddressDecision, CaptureError> {
if metadata.redirect_to_dlq {
return Ok(AddressDecision::redirect(Address::Dlq));
@@ -156,21 +157,16 @@ pub fn resolve(
}
}
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.
- if ai_events_overflow_armed && metadata.force_overflow {
+ // 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.
+ if has_ai_overflow_lane && metadata.force_overflow {
AddressDecision::lane(
PipelineLane::Ai(AiLane::Overflow),
person_ordering(metadata.person_processing_disabled()),
)
- } else if ai_events_overflow_armed {
+ } else if has_ai_overflow_lane {
match &metadata.overflow_reason {
Some(OverflowReason::ForceLimited) => AddressDecision::lane(
PipelineLane::Ai(AiLane::Overflow),
@@ -441,21 +437,21 @@ mod tests {
#[case] data_type: DataType,
#[case] overflow: PipelineLane,
) {
- let armed = data_type == DataType::AiEvents;
+ let has_ai_overflow_lane = 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,
+ resolve(&m, has_ai_overflow_lane).unwrap().ordering,
OrderingGuarantee::PerDistinctId,
"locality is preserved while person processing is on"
);
m.skip_person_processing = true;
assert_eq!(
- resolve(&m, armed).unwrap(),
+ resolve(&m, has_ai_overflow_lane).unwrap(),
AddressDecision {
address: lane(overflow),
ordering: OrderingGuarantee::None,
@@ -464,9 +460,7 @@ mod tests {
}
#[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.
+ fn ai_events_overflow_needs_an_overflow_lane() {
let mut m = meta(DataType::AiEvents);
m.force_overflow = true;
assert_eq!(
@@ -477,7 +471,6 @@ mod tests {
}
);
- // Valve armed: mirrors the analytics main lane's overflow handling.
assert_eq!(
resolve(&m, true).unwrap().address,
lane(PipelineLane::Ai(AiLane::Overflow))
@@ -510,14 +503,14 @@ mod tests {
// 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] {
+ for has_ai_overflow_lane in [false, true] {
assert_eq!(
- resolve(&m, armed).unwrap(),
+ resolve(&m, has_ai_overflow_lane).unwrap(),
AddressDecision {
address: lane(PipelineLane::Ai(AiLane::Main)),
ordering: OrderingGuarantee::PerDistinctId,
},
- "armed={armed}"
+ "has_ai_overflow_lane={has_ai_overflow_lane}"
);
}
}
diff --git a/rust/capture/src/router.rs b/rust/capture/src/router.rs
index d589eefb4c9a..10a0367e816c 100644
--- a/rust/capture/src/router.rs
+++ b/rust/capture/src/router.rs
@@ -94,8 +94,9 @@ pub struct State {
/// separate governor instance, so per-key budgets are isolated: analytics
/// volume never pushes a key's AI events into AI overflow and AI volume
/// never burns the analytics budget. Only built when both
- /// `OVERFLOW_ENABLED` and the AI overflow valve are set; `None` leaves
- /// the AI lane subject to restriction-driven `force_overflow` only.
+ /// `OVERFLOW_ENABLED` and `AI_EVENTS_OVERFLOW_ENABLED` are set; `None` leaves
+ /// only restriction overflow, which reaches AI overflow on every deployment
+ /// with that lane (not Import).
pub ai_events_overflow_limiter: Option<Arc<OverflowLimiter>>,
/// AI-lane per-token byte budget; `None` when disabled. A second instance
/// of the same global rate limiter the `token:distinct_id` field holds,
@@ -108,10 +109,6 @@ pub struct State {
/// the kafka sink can route to the replay overflow topic. Same rationale
/// as `overflow_limiter` above.
pub replay_overflow_limiter: Option<Arc<RedisLimiter>>,
- /// Whether the AI overflow valve is armed (`CAPTURE_OUTPUT_AI_OVERFLOW_TOPIC` is
- /// set). Gates overflow stamping for the AI lane in both pipelines: when
- /// false, AI events never overflow (pre-overflow behavior).
- pub ai_events_overflow_enabled: bool,
pub capture_v1_scatter_gather_min_batch: usize,
pub ai_gateway_signing_secret: Option<String>,
/// Best-effort v2 ingestion warnings emitter (fire-and-forget Kafka
@@ -193,7 +190,6 @@ pub fn router<TZ: TimeSource + Send + Sync + 'static, R: Client + Send + Sync +
replay_overflow_limiter: Option<Arc<RedisLimiter>>,
capture_v1_scatter_gather_min_batch: usize,
ai_gateway_signing_secret: Option<String>,
- ai_events_overflow_enabled: bool,
ingestion_warning_emitter: Option<Arc<dyn WarningEmitter>>,
) -> Router {
let state = State {
@@ -223,7 +219,6 @@ pub fn router<TZ: TimeSource + Send + Sync + 'static, R: Client + Send + Sync +
replay_overflow_limiter,
capture_v1_scatter_gather_min_batch,
ai_gateway_signing_secret,
- ai_events_overflow_enabled,
ingestion_warning_emitter,
capture_mode,
};
diff --git a/rust/capture/src/setup.rs b/rust/capture/src/setup.rs
index 610bc0e0284d..4edee6a302c6 100644
--- a/rust/capture/src/setup.rs
+++ b/rust/capture/src/setup.rs
@@ -289,10 +289,10 @@ pub async fn build_components(
!config.outputs.ai_main_topic.is_empty(),
"invalid configuration: CAPTURE_OUTPUT_AI_MAIN_TOPIC must not be empty",
);
- let ai_events_overflow_enabled = ai_events_overflow_valve(&config);
+ let ai_events_overflow_enabled = ai_events_overflow_limiter_enabled(&config);
info!(
ai_main_topic = %config.outputs.ai_main_topic,
- ai_overflow_topic = ?config.outputs.ai_overflow_topic,
+ ai_overflow_topic = %config.outputs.ai_overflow_topic,
ai_events_overflow_enabled,
"AI events topic routing"
);
@@ -378,7 +378,6 @@ pub async fn build_components(
replay_overflow_limiter,
config.capture_v1_scatter_gather_min_batch,
config.ai_gateway_signing_secret.clone(),
- ai_events_overflow_enabled,
ingestion_warning_emitter,
);
@@ -396,24 +395,13 @@ pub async fn build_components(
}
}
-/// The AI overflow valve: an unset or empty
-/// `CAPTURE_OUTPUT_AI_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
- .outputs
- .ai_overflow_topic
- .as_deref()
- .is_some_and(|topic| !topic.is_empty());
+fn ai_events_overflow_limiter_enabled(config: &Config) -> bool {
+ let enabled = config.ai_events_overflow_enabled;
assert!(
- !(armed && matches!(config.capture_mode, CaptureMode::Import)),
- "invalid configuration: CAPTURE_OUTPUT_AI_OVERFLOW_TOPIC must be unset in import mode; imports must never overflow"
+ !(enabled && matches!(config.capture_mode, CaptureMode::Import)),
+ "invalid configuration: AI_EVENTS_OVERFLOW_ENABLED must be false in import mode; imports must never overflow"
);
- armed
+ enabled
}
/// The AI byte budget this deployment enforces, or `0` to skip building the
@@ -500,7 +488,7 @@ async fn create_output(
// Runs before any producer connects, so a blank topic refuses boot
// immediately instead of after a broker connect attempt.
- let outputs = OutputTable::from(&config.outputs);
+ let outputs = OutputTable::new(&config.outputs, config.capture_mode.has_ai_overflow_lane());
if config.outputs_completeness_check_enabled {
outputs.check_complete()?;
} else {
@@ -576,9 +564,9 @@ const WARNINGS_KAFKA_MESSAGE_TIMEOUT_MS: u32 = 5_000;
const WARNINGS_TYPE_BUDGET_PERIOD: Duration = Duration::from_secs(1);
const WARNINGS_TYPE_BUDGET_BURST: NonZeroU32 = NonZeroU32::new(60).unwrap();
-/// Build the dedicated, warnings-only Kafka config. Reuses only the
-/// destination cluster (`hosts`/`tls`) from capture's main Kafka config;
-/// everything else is the fixed fire-and-forget policy (client id, acks,
+/// Build the dedicated, warnings-only Kafka config. `hosts`/`tls` come from
+/// `CAPTURE_INGESTION_WARNINGS_KAFKA_{HOSTS,TLS}`; everything else is the
+/// fixed fire-and-forget policy (client id, acks,
/// retries, linger, queue depth, message timeout) plus the two tunable limits
/// (`queue_mib`, `message_max_bytes`). `..Default::default()` supplies the
/// shared-crate defaults (compression codec, empty client rack) and — critically
@@ -613,9 +601,8 @@ fn build_warnings_kafka_config(
/// dedicated, warnings-only `common_kafka::config::KafkaConfig` (fire-and-forget
/// acks/retries, a small queue) with `observe_delivery` as its delivery
/// callback. Its destination (hosts/TLS/topic) comes entirely from
-/// `CAPTURE_INGESTION_WARNINGS_KAFKA_{HOSTS,TLS,TOPIC}`; it no longer borrows
-/// anything from capture's main event config (the v0 `KAFKA_*` block), so
-/// retiring that block cannot silently misroute or mute it. When built, a
+/// `CAPTURE_INGESTION_WARNINGS_KAFKA_{HOSTS,TLS,TOPIC}`, never from capture's
+/// main event config. When built, a
/// background task heartbeats the advisory lifecycle handle, sweeps the
/// throttle's per-key state, and flushes the producer once at shutdown.
///
@@ -861,12 +848,13 @@ mod tests {
.expect("runtime")
}
- struct AiValveInput {
+ struct AiLimiterInput {
capture_mode: &'static str,
+ enabled: Option<&'static str>,
overflow_topic: Option<&'static str>,
}
- fn ai_valve_config(input: &AiValveInput) -> Config {
+ fn ai_limiter_config(input: &AiLimiterInput) -> Config {
let mut cfg_env: HashMap<String, String> = [
("REDIS_URL", "redis://localhost:6379/"),
("CAPTURE_MODE", input.capture_mode),
@@ -878,6 +866,12 @@ mod tests {
.into_iter()
.map(|(k, v)| (k.to_string(), v.to_string()))
.collect();
+ if let Some(enabled) = input.enabled {
+ cfg_env.insert(
+ "AI_EVENTS_OVERFLOW_ENABLED".to_string(),
+ enabled.to_string(),
+ );
+ }
if let Some(topic) = input.overflow_topic {
cfg_env.insert(
"CAPTURE_OUTPUT_AI_OVERFLOW_TOPIC".to_string(),
@@ -888,41 +882,37 @@ mod tests {
}
#[rstest]
- #[case::events_set(
- AiValveInput {
+ #[case::events_enabled(
+ AiLimiterInput {
capture_mode: "events",
- overflow_topic: Some("events_plugin_ingestion_ai_overflow"),
+ enabled: Some("true"),
+ overflow_topic: None,
},
true
)]
- #[case::events_unset(
- AiValveInput {
+ #[case::events_topic_without_flag(
+ AiLimiterInput {
capture_mode: "events",
- overflow_topic: None,
- },
- false
- )]
- #[case::import_unset(
- AiValveInput {
- capture_mode: "import",
- overflow_topic: None,
+ enabled: None,
+ overflow_topic: Some("events_plugin_ingestion_ai_overflow"),
},
false
)]
- #[case::import_empty(
- AiValveInput {
+ #[case::import_disabled(
+ AiLimiterInput {
capture_mode: "import",
- overflow_topic: Some(""),
+ enabled: Some("false"),
+ overflow_topic: Some("events_plugin_ingestion_ai_overflow"),
},
false
)]
- fn ai_events_overflow_valve_arms_only_on_a_set_topic(
- #[case] input: AiValveInput,
- #[case] expected_armed: bool,
+ fn ai_events_overflow_limiter_follows_only_the_flag(
+ #[case] input: AiLimiterInput,
+ #[case] expected_enabled: bool,
) {
assert_eq!(
- ai_events_overflow_valve(&ai_valve_config(&input)),
- expected_armed
+ ai_events_overflow_limiter_enabled(&ai_limiter_config(&input)),
+ expected_enabled
);
}
@@ -997,20 +987,23 @@ mod tests {
"the error must name the AI byte knob, not the shared one, got: {err}"
);
- // The shared window is valid here, so the token+distinct_id limiter is
- // unaffected by the AI byte knob being wrong.
+ let err = match GlobalRateLimiter::new_token_distinct_id(&config, vec![]) {
+ Ok(_) => panic!("an empty redis instance list must not build a limiter"),
+ Err(err) => err,
+ };
assert!(
- GlobalRateLimiter::new_token_distinct_id(&config, vec![]).is_err(),
- "an empty redis instance list still fails, but not on the window"
+ !err.to_string().contains("WINDOW_INTERVAL_SECS"),
+ "the token+distinct_id limiter must not fail on a window, got: {err}"
);
}
#[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 {
+ fn ai_events_overflow_limiter_is_refused_in_import_mode() {
+ ai_events_overflow_limiter_enabled(&ai_limiter_config(&AiLimiterInput {
capture_mode: "import",
- overflow_topic: Some("events_plugin_ingestion_ai_overflow"),
+ enabled: Some("true"),
+ overflow_topic: None,
}));
}
@@ -1018,7 +1011,6 @@ mod tests {
fn warnings_kafka_config_is_isolated_from_main_producer_tuning() {
let cfg = build_warnings_kafka_config("broker:9092".to_string(), true, 16, 1_048_576);
- // Reuses only the destination cluster from the main config.
assert_eq!(cfg.kafka_hosts, "broker:9092");
assert!(cfg.kafka_tls);
diff --git a/rust/capture/src/sinks/kafka.rs b/rust/capture/src/sinks/kafka.rs
index 496ab0ff01f6..0d4d9a6956d2 100644
--- a/rust/capture/src/sinks/kafka.rs
+++ b/rust/capture/src/sinks/kafka.rs
@@ -3,14 +3,10 @@
//! This sink is pure mechanism: it produces to Kafka with `rdkafka`.
//! `KafkaSinkBase::prepare_record` serializes a `ProcessedEvent` and maps the
//! metadata the pipeline stamped to a [`Destination`] and partition key; v1's
-//! prepared events arrive serialized and carry their own address. All routing
-//! *policy* (overflow, DLQ and custom-topic redirects, person-processing
-//! headers) is decided *upstream*. Enqueue resolves the destination to a topic
-//! and producer.
-//!
-//! Keeping routing policy out of the sink keeps the clone-per-spawned-task
-//! cost in the scatter-gather batch path at one `Arc::clone` call (the output
-//! table) rather than deep copies of limiter state.
+//! prepared events arrive serialized and carry their own address. Routing
+//! policy lives in `pipeline::resolve`, which reads the stamped metadata and
+//! the output table's `has_ai_overflow_lane`. Enqueue resolves the destination
+//! to a topic and producer.
use crate::api::CaptureError;
use crate::config::EnvelopeCompression;
use crate::ordering::OrderingGuarantee;
@@ -289,7 +285,7 @@ impl<P: KafkaProducer> KafkaSinkBase<P> {
// effects live in the same match that maps it to an output, so a new
// address cannot skip them: dlq sets the dlq headers, and both admin
// redirects count their reroutes.
- let decision = pipeline::resolve(&metadata, self.outputs.ai_events_overflow_armed())?;
+ let decision = pipeline::resolve(&metadata, self.outputs.has_ai_overflow_lane())?;
let target = match decision.address {
Address::Dlq => {
dlq_reroute_effects(&mut headers, "event_restriction");
@@ -464,10 +460,7 @@ impl<P: KafkaProducer + 'static> KafkaSinkBase<P> {
Err(err) => {
counter!("capture_kafka_prep_panic_total").increment(1);
error!("join error while preparing Kafka record: {err:#}");
- // Drain remaining prep tasks before returning so they can't
- // leak records into librdkafka after we've already failed.
- // Record the histogram on the error path too so prep-duration
- // stays observable during failures (not just happy path).
+ // Record prep duration on the error path too.
prep_set.abort_all();
histogram!("capture_kafka_batch_prep_duration_seconds")
.record(prep_start.elapsed().as_secs_f64());
@@ -2078,11 +2071,6 @@ mod tests {
}
// ==================== AiEvents ====================
- // The dedicated $ai_* lane routes to its own topic, keyed on the
- // event key. test_outputs() arms the AI overflow valve
- // (CAPTURE_OUTPUT_AI_OVERFLOW_TOPIC), so overflow handling mirrors the
- // AnalyticsMain arm onto the AI topics; the unarmed tests below
- // override the valve off.
#[tokio::test]
async fn ai_events_normal() {
@@ -2107,9 +2095,7 @@ mod tests {
}
#[tokio::test]
- async fn ai_events_force_overflow_reroutes_when_armed() {
- // With the valve armed, restriction-driven force_overflow behaves
- // exactly like the analytics main lane: rerouted, key kept.
+ async fn ai_events_force_overflow_reroutes() {
assert_routing(
EventInput {
data_type: DataType::AiEvents,
@@ -2202,13 +2188,11 @@ mod tests {
}
#[tokio::test]
- async fn ai_events_unarmed_never_overflows() {
- // Without CAPTURE_OUTPUT_AI_OVERFLOW_TOPIC the lane never
- // overflows: force_overflow and any stamped reason (which the
- // gated pipeline would not produce anyway) are ignored.
+ async fn ai_events_without_overflow_lane_never_overflow() {
+ // Import has no AI overflow lane, so every overflow stamp is ignored.
let producer = MockKafkaProducer::new();
let mut topics = test_outputs();
- topics.ai_overflow = None;
+ topics.has_ai_overflow_lane = false;
let sink = KafkaSinkBase::with_producer(producer.clone(), topics);
let mut event = create_test_event(&EventInput {
@@ -2452,12 +2436,6 @@ mod tests {
}
// ==================== overflow_reason routing tests ====================
- // The pipeline stamps ProcessedEventMetadata::overflow_reason upstream;
- // the sink is a pure mechanism layer that switches on it. These cover
- // each variant: ForceLimited, RateLimited { preserve_locality }, and
- // ReplayLimited. `force_overflow` coexistence is covered by the
- // analytics_main_force_overflow / snapshot_main_force_overflow cases
- // above (force_overflow short-circuits the overflow_reason branch).
/// `ForceLimited` implies person processing is off on its own: the
/// header is set whether or not the stamping site also set the flag,
diff --git a/rust/capture/src/sinks/registry.rs b/rust/capture/src/sinks/registry.rs
index 42f27c66d6e1..9d900ad630d2 100644
--- a/rust/capture/src/sinks/registry.rs
+++ b/rust/capture/src/sinks/registry.rs
@@ -22,7 +22,6 @@ pub enum Destination {
Dlq,
ErrorTrackingMain,
AiMain,
- /// Only routed to when the AI overflow valve is armed.
AiOverflow,
/// Admin-configured topic copied from `redirect_to_topic`.
Custom(String),
@@ -31,7 +30,7 @@ pub enum Destination {
impl Destination {
/// 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: [Destination; 10] = [
+ const REGISTERED: [Destination; 11] = [
Destination::AnalyticsMain,
Destination::AnalyticsOverflow,
Destination::AnalyticsHistorical,
@@ -42,6 +41,7 @@ impl Destination {
Destination::Dlq,
Destination::ErrorTrackingMain,
Destination::AiMain,
+ Destination::AiOverflow,
];
pub(crate) fn for_lane(lane: PipelineLane) -> Destination {
@@ -85,10 +85,10 @@ impl Destination {
| Destination::SessionReplayOverflow
| Destination::Dlq
| Destination::ErrorTrackingMain
- | Destination::AiMain => true,
- // The opt-in AI overflow valve and per-event custom topics sit
- // outside the check.
- Destination::AiOverflow | Destination::Custom(_) => false,
+ | Destination::AiMain
+ | Destination::AiOverflow => true,
+ // A custom redirect carries its own topic per event.
+ Destination::Custom(_) => false,
}
}
@@ -133,7 +133,8 @@ pub struct OutputTable<R = ProducerName> {
pub(crate) dlq: OutputTarget<R>,
pub(crate) error_tracking: OutputTarget<R>,
pub(crate) ai_main: OutputTarget<R>,
- pub(crate) ai_overflow: Option<OutputTarget<R>>,
+ pub(crate) ai_overflow: OutputTarget<R>,
+ pub(crate) has_ai_overflow_lane: bool,
pub(crate) custom_producer: R,
}
@@ -150,12 +151,7 @@ impl<R> OutputTable<R> {
Destination::Dlq => Some(&self.dlq),
Destination::ErrorTrackingMain => Some(&self.error_tracking),
Destination::AiMain => Some(&self.ai_main),
- Destination::AiOverflow => match &self.ai_overflow {
- Some(target) if !target.topic.is_empty() => Some(target),
- // Callers select this output only when the valve is armed,
- // i.e. exactly when the topic is set.
- _ => Some(&self.ai_main),
- },
+ Destination::AiOverflow => Some(&self.ai_overflow),
Destination::Custom(_) => None,
}
}
@@ -195,20 +191,18 @@ impl<R> OutputTable<R> {
dlq: target(&self.dlq),
error_tracking: target(&self.error_tracking),
ai_main: target(&self.ai_main),
- ai_overflow: self.ai_overflow.as_ref().map(&mut target),
+ ai_overflow: target(&self.ai_overflow),
+ has_ai_overflow_lane: self.has_ai_overflow_lane,
custom_producer,
}
}
- pub fn ai_events_overflow_armed(&self) -> bool {
- self.ai_overflow
- .as_ref()
- .is_some_and(|target| !target.topic.is_empty())
+ pub fn has_ai_overflow_lane(&self) -> bool {
+ self.has_ai_overflow_lane
}
/// Every registered output must resolve to a non-empty topic. `Custom` is
- /// excluded because it carries its own topic per event, and the opt-in
- /// `AiOverflow` valve because unset means routing never selects it.
+ /// excluded because it carries its own topic per event.
pub fn check_complete(&self) -> anyhow::Result<()> {
for output in &Destination::REGISTERED {
anyhow::ensure!(
@@ -222,8 +216,8 @@ impl<R> OutputTable<R> {
}
}
-impl From<&OutputsConfig> for OutputTable {
- fn from(config: &OutputsConfig) -> Self {
+impl OutputTable {
+ pub fn new(config: &OutputsConfig, has_ai_overflow_lane: bool) -> Self {
let target = |topic: &String, producer: ProducerName| OutputTarget {
topic: Arc::from(topic.as_str()),
producer,
@@ -254,10 +248,8 @@ impl From<&OutputsConfig> for OutputTable {
dlq: target(&config.dlq_topic, config.dlq_producer),
error_tracking: target(&config.error_tracking_topic, config.error_tracking_producer),
ai_main: target(&config.ai_main_topic, config.ai_main_producer),
- ai_overflow: config
- .ai_overflow_topic
- .as_ref()
- .map(|topic| target(topic, config.ai_overflow_producer)),
+ ai_overflow: target(&config.ai_overflow_topic, config.ai_overflow_producer),
+ has_ai_overflow_lane,
custom_producer: config.custom_producer,
}
}
@@ -280,7 +272,8 @@ pub(crate) fn test_outputs() -> OutputTable {
dlq: target("events_plugin_ingestion_dlq"),
error_tracking: target("error_tracking_events"),
ai_main: target("ai_events"),
- ai_overflow: Some(target("ai_events_overflow")),
+ ai_overflow: target("ai_events_overflow"),
+ has_ai_overflow_lane: true,
custom_producer: ProducerName::Ingestion,
}
}
@@ -315,17 +308,6 @@ mod tests {
);
}
- /// An unarmed overflow valve carries no completeness requirement and never
- /// disarms the AI main lane.
- #[test]
- fn unset_ai_overflow_valve_is_unarmed() {
- let mut registry = test_outputs();
- registry.ai_overflow = None;
- assert!(registry.check_complete().is_ok());
- assert!(!registry.ai_events_overflow_armed());
- assert_eq!(registry.topic_for(&Destination::AiMain), "ai_events");
- }
-
#[test]
fn session_replay_main_does_not_share_analytics_main() {
let mut registry = test_outputs();
@@ -404,6 +386,7 @@ mod tests {
#[case("dlq", |r: &mut OutputTable| r.dlq.topic = Arc::from(""))]
#[case("errortracking-main", |r: &mut OutputTable| r.error_tracking.topic = Arc::from(""))]
#[case("ai-main", |r: &mut OutputTable| r.ai_main.topic = Arc::from(""))]
+ #[case("ai-overflow", |r: &mut OutputTable| r.ai_overflow.topic = Arc::from(""))]
fn check_complete_rejects_empty_topic(
#[case] output_name: &str,
#[case] blank: fn(&mut OutputTable),
diff --git a/rust/capture/src/v1/analytics/process.rs b/rust/capture/src/v1/analytics/process.rs
index 14a8f3cb6dae..73563b03ded4 100644
--- a/rust/capture/src/v1/analytics/process.rs
+++ b/rust/capture/src/v1/analytics/process.rs
@@ -145,7 +145,7 @@ async fn run_pipeline(
service,
&context.api_token,
context.server_received_at.timestamp(),
- state.ai_events_overflow_enabled,
+ state.capture_mode.has_ai_overflow_lane(),
&mut events,
)
.await;
@@ -763,10 +763,7 @@ fn apply_overflow_stamping(
// Each overflowing lane keeps its own overflow destination AND its
// own limiter instance, so an overflowing AI event lands on AI
// overflow (never analytics overflow) and the per-key budgets are
- // isolated between the lanes. The AI lane only participates when its
- // limiter exists — setup builds it exactly when the AI overflow valve
- // (CAPTURE_OUTPUT_AI_OVERFLOW_TOPIC) is armed, so limiter
- // presence encodes the valve here.
+ // isolated between the lanes.
let (overflow_destination, lane_limiter) = match event.destination {
Destination::AnalyticsMain => (Destination::AnalyticsOverflow, analytics_limiter),
Destination::AiMain => (Destination::AiOverflow, ai_limiter),
@@ -815,7 +812,7 @@ async fn apply_restrictions(
service: &EventRestrictionService,
token: &str,
now_ts: i64,
- ai_events_overflow_enabled: bool,
+ has_ai_overflow_lane: bool,
events: &mut [WrappedEvent],
) {
for event in events.iter_mut() {
@@ -853,7 +850,7 @@ async fn apply_restrictions(
// Priority: overflow < custom topic < DLQ (DLQ wins, applied last)
let force_overflow_destination = match event.destination {
Destination::AnalyticsMain => Some(Destination::AnalyticsOverflow),
- Destination::AiMain if ai_events_overflow_enabled => Some(Destination::AiOverflow),
+ Destination::AiMain if has_ai_overflow_lane => Some(Destination::AiOverflow),
_ => None,
};
if applied.force_overflow() {
@@ -2111,18 +2108,14 @@ mod tests {
assert_eq!(ev.destination, Destination::AnalyticsOverflow);
}
- /// A diverted AI event consults ai-scoped restrictions: an ai-scoped
- /// ForceOverflow reroutes it to the AI overflow destination when the
- /// valve is armed and leaves it untouched when not, while an
- /// analytics-scoped ForceOverflow never crosses into the AI lane.
#[rstest::rstest]
- #[case::armed(Pipeline::Ai, true, Destination::AiOverflow)]
- #[case::unarmed(Pipeline::Ai, false, Destination::AiMain)]
+ #[case::with_lane(Pipeline::Ai, true, Destination::AiOverflow)]
+ #[case::without_lane(Pipeline::Ai, false, Destination::AiMain)]
#[case::analytics_scoped_does_not_cross(Pipeline::Analytics, true, Destination::AiMain)]
#[tokio::test]
- async fn restrictions_force_overflow_ai_events_gated_on_valve(
+ async fn restrictions_force_overflow_ai_events_need_an_overflow_lane(
#[case] restriction_pipeline: Pipeline,
- #[case] ai_events_overflow_enabled: bool,
+ #[case] has_ai_overflow_lane: bool,
#[case] expected_destination: Destination,
) {
let service = restriction_service_for_pipeline(
@@ -2144,7 +2137,7 @@ mod tests {
&service,
"phc_token",
now_ts,
- ai_events_overflow_enabled,
+ has_ai_overflow_lane,
&mut events,
)
.await;
@@ -2184,8 +2177,6 @@ mod tests {
);
}
- /// A ceiling of `0` disables the check, so a deployment that never sets
- /// `AI_MAX_EVENT_BYTES` keeps publishing whatever its producer accepts.
#[tokio::test]
async fn a_zero_ai_size_ceiling_disables_the_check() {
let mut oversized = wrapped_event("$ai_generation", "user-big");
@@ -3470,10 +3461,6 @@ mod tests {
assert_eq!(events[0].destination, Destination::AnalyticsMain);
}
- /// The AI lane converts to its own overflow destination under the same
- /// conditions as AnalyticsMain, but only when its limiter is present
- /// (setup builds it exactly when the AI overflow valve is armed); absent
- /// it is never touched.
#[rstest::rstest]
#[case::limiter_present(true, Destination::AiOverflow, true)]
#[case::limiter_absent(false, Destination::AiMain, false)]
@@ -3894,14 +3881,8 @@ mod tests {
assert_eq!(&*records[0].topic, "ai_events");
}
- /// process_batch wiring: overflow stamping must run when only the AI-lane
- /// limiter is armed (analytics limiter unset), with the state's AI limiter
- /// governing the AI lane — a bursting key's second AI event lands on
- /// the AI overflow topic while an analytics event on the same key stays on
- /// the main topic (it would overflow instead if the limiter arguments were
- /// ever swapped).
#[tokio::test]
- async fn process_batch_routes_ai_overflow_with_only_ai_limiter_armed() {
+ async fn process_batch_routes_ai_overflow_with_only_ai_limiter() {
let ts = TestStateBuilder::new()
.with_ai_events_overflow_limiter(1, 1)
.build();
@@ -4269,10 +4250,6 @@ mod tests {
.with_overflow_limiter(1, 1)
.with_restriction_service(restrictions)
.build();
- assert!(
- !ts.state.ai_events_overflow_enabled,
- "capture-import leaves the AI valve unarmed"
- );
let mut ctx = test_utils::test_analytics_context();
let batch = historical_batch(vec![
Event {
@@ -4306,12 +4283,7 @@ mod tests {
#[tokio::test]
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.
+ // AI wins over historical: only the AI lane has AI processing.
let ts = TestStateBuilder::new()
.with_capture_mode(crate::config::CaptureMode::Import)
.build();
diff --git a/rust/capture/src/v1/quota_limiter_shim.rs b/rust/capture/src/v1/quota_limiter_shim.rs
index a428966c70cb..51c50ddfae59 100644
--- a/rust/capture/src/v1/quota_limiter_shim.rs
+++ b/rust/capture/src/v1/quota_limiter_shim.rs
@@ -159,6 +159,7 @@ mod tests {
event_restrictions_refresh_interval_secs: 30,
event_restrictions_fail_open_after_secs: 300,
overflow_enabled: false,
+ ai_events_overflow_enabled: false,
overflow_preserve_partition_locality: false,
overflow_burst_limit: NonZeroU32::new(5).unwrap(),
overflow_per_second_limit: NonZeroU32::new(10).unwrap(),
@@ -191,7 +192,7 @@ mod tests {
dlq_producer: ProducerName::Ingestion,
ai_main_topic: "events_plugin_ingestion_ai".to_string(),
ai_main_producer: ProducerName::Ingestion,
- ai_overflow_topic: None,
+ ai_overflow_topic: "events_plugin_ingestion_ai_overflow".to_string(),
ai_overflow_producer: ProducerName::Ingestion,
custom_producer: ProducerName::Ingestion,
},
diff --git a/rust/capture/src/v1/test_utils.rs b/rust/capture/src/v1/test_utils.rs
index d9e875da3b5c..cd5b59ae0d59 100644
--- a/rust/capture/src/v1/test_utils.rs
+++ b/rust/capture/src/v1/test_utils.rs
@@ -364,8 +364,8 @@ pub fn realistic_dup_uuid_pair() -> (Event, Event) {
(first, second)
}
-/// One Ok event per `Destination` variant + one pre-marked Drop, with
-/// ordinal `user-dest-{0..5}` distinct_ids.
+/// One Ok event per analytics destination plus Dlq and Custom, and one
+/// pre-marked Drop.
pub fn realistic_spread_destinations() -> Vec<WrappedEvent> {
let main = realistic_pageview("user-dest-0").with_destination(Destination::AnalyticsMain);
let historical =
@@ -436,7 +436,6 @@ pub fn assert_round_trip(
// Payload generators for batch-level tests
// ---------------------------------------------------------------------------
-/// Serialize a list of Events into a valid V1 batch JSON payload.
/// A non-historical batch wrapping `events`, the shape `process_batch` takes.
pub fn valid_batch(events: Vec<Event>) -> crate::v1::analytics::types::Batch {
crate::v1::analytics::types::Batch {
@@ -447,6 +446,7 @@ pub fn valid_batch(events: Vec<Event>) -> crate::v1::analytics::types::Batch {
}
}
+/// Serialize a list of Events into a valid V1 batch JSON payload.
pub fn batch_payload(events: &[Event]) -> Vec<u8> {
let batch_json = serde_json::json!({
"created_at": "2026-03-19T14:30:00.000Z",
@@ -657,9 +657,6 @@ impl TestStateBuilder {
self
}
- /// Arm the AI overflow valve: a dedicated AI-lane limiter with the given
- /// rate and burst. Also sets `ai_events_overflow_enabled`, mirroring
- /// production where both derive from the same overflow-topic config.
pub fn with_ai_events_overflow_limiter(mut self, per_second: u32, burst: u32) -> Self {
self.ai_events_overflow_limiter = Some((
NonZeroU32::new(per_second).expect("per_second must be > 0"),
@@ -777,12 +774,14 @@ impl TestStateBuilder {
self.overflow_preserve_locality,
))
});
- let ai_events_overflow_enabled = ai_events_overflow_limiter.is_some();
let mock_producer = self.mock_producer.unwrap_or_default();
let outputs = Arc::new(OutputRegistry::single(KafkaSinkBase::with_producer(
mock_producer.clone(),
- OutputTable::from(&test_outputs_config()),
+ OutputTable::new(
+ &test_outputs_config(),
+ self.capture_mode.has_ai_overflow_lane(),
+ ),
)));
let timesource: Arc<dyn TimeSource + Send + Sync> = Arc::new(crate::time::SystemTime {});
@@ -811,7 +810,6 @@ impl TestStateBuilder {
replay_overflow_limiter: None,
capture_v1_scatter_gather_min_batch: 8,
ai_gateway_signing_secret: self.ai_gateway_signing_secret,
- 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.rs
index 2a4f594e400c..7b8cc5987f29 100644
--- a/rust/capture/tests/common/integration_utils.rs
+++ b/rust/capture/tests/common/integration_utils.rs
@@ -1117,7 +1117,7 @@ fn build_router_for_mode_at(mode: CaptureMode, fixed_time: &str) -> (Router, Mem
is_mirror_deploy,
verbose_sample_percent,
26_214_400, // 25MB default for AI endpoint
- 983_040, // ai_max_event_bytes (960KB, the previous hardcoded limit)
+ 983_040, // ai_max_event_bytes (960KB)
None, // body_chunk_read_timeout_ms
256, // body_read_chunk_size_kb
10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
@@ -1128,7 +1128,6 @@ fn build_router_for_mode_at(mode: CaptureMode, fixed_time: &str) -> (Router, Mem
None, // replay_overflow_limiter
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.rs
index e9be12c9f2f0..f69a6b22c67f 100644
--- a/rust/capture/tests/common/utils.rs
+++ b/rust/capture/tests/common/utils.rs
@@ -94,6 +94,7 @@ pub static DEFAULT_CONFIG: Lazy<Config> = Lazy::new(|| Config {
event_restrictions_refresh_interval_secs: 30,
event_restrictions_fail_open_after_secs: 300,
overflow_enabled: false,
+ ai_events_overflow_enabled: false,
overflow_preserve_partition_locality: false,
overflow_burst_limit: NonZeroU32::new(5).unwrap(),
overflow_per_second_limit: NonZeroU32::new(10).unwrap(),
@@ -125,7 +126,7 @@ pub static DEFAULT_CONFIG: Lazy<Config> = Lazy::new(|| Config {
dlq_producer: ProducerName::Ingestion,
ai_main_topic: "events_plugin_ingestion_ai".to_string(),
ai_main_producer: ProducerName::Ingestion,
- ai_overflow_topic: None,
+ ai_overflow_topic: "events_plugin_ingestion_ai_overflow".to_string(),
ai_overflow_producer: ProducerName::Ingestion,
custom_producer: ProducerName::Ingestion,
},
@@ -165,8 +166,9 @@ pub static DEFAULT_CONFIG: Lazy<Config> = Lazy::new(|| Config {
ai_byte_limit_local_cache_max_entries: 300_000,
});
-/// Points every non-AI output at one (ephemeral) topic, so a consumer of that
-/// topic sees whichever lane the v1 pipeline picks.
+/// Points the analytics (main, historical, overflow), DLQ, error tracking,
+/// heatmaps and client warnings outputs at one topic. AI and session replay
+/// outputs keep their config values.
pub fn point_outputs_at(config: &mut Config, topic: &str) {
let outputs = &mut config.outputs;
for field in [
@@ -246,7 +248,7 @@ impl ServerHandle {
Self::for_config(config).await
}
- /// Boots a server with every non-AI output pointed at `topic`. The topics live on the config rather than in
+ /// Boots a server with the outputs [`point_outputs_at`] covers pointed at `topic`. The topics live on the config rather than in
/// `std::env`, so parallel tests don't race on distinct ephemeral topics.
pub async fn for_v1_topic(topic: &EphemeralTopic) -> Self {
let mut config = DEFAULT_CONFIG.clone();
diff --git a/rust/capture/tests/integration_ai_endpoint.rs b/rust/capture/tests/integration_ai_endpoint.rs
index 44c07d103f43..96b6c497e181 100644
--- a/rust/capture/tests/integration_ai_endpoint.rs
+++ b/rust/capture/tests/integration_ai_endpoint.rs
@@ -183,7 +183,7 @@ fn setup_ai_test_router() -> Router {
false,
0.0_f32,
26_214_400, // 25MB default for AI endpoint
- 983_040, // ai_max_event_bytes (960KB, the previous hardcoded limit)
+ 983_040, // ai_max_event_bytes (960KB)
None, // body_chunk_read_timeout_ms
256, // body_read_chunk_size_kb
10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
@@ -194,7 +194,6 @@ fn setup_ai_test_router() -> Router {
None, // replay_overflow_limiter
8, // capture_v1_scatter_gather_min_batch
None, // ai_gateway_signing_secret
- false, // ai_events_overflow_enabled
None, // ingestion_warning_emitter
)
}
@@ -239,7 +238,7 @@ fn setup_ai_router_collecting_warnings() -> (Router, Arc<CollectingEmitter>) {
false,
0.0_f32,
26_214_400,
- 983_040, // ai_max_event_bytes (960KB, the previous hardcoded limit)
+ 983_040, // ai_max_event_bytes (960KB)
None,
256,
10 * 1024 * 1024,
@@ -250,7 +249,6 @@ fn setup_ai_router_collecting_warnings() -> (Router, Arc<CollectingEmitter>) {
None,
8,
None,
- false,
warning_emitter,
);
@@ -1150,10 +1148,8 @@ async fn test_request_body_exceeds_110_percent_limit_returns_413() {
"$ai_model": "test"
});
- // Create a blob that's just barely over 25MB
- // This will result in a request body that exceeds 27.5MB (110% limit)
- // once multipart overhead is added
- let large_blob = vec![0u8; (25 * 1024 * 1024) + (3 * 1024 * 1024)]; // 28MB
+ // 28 MiB alone exceeds the 27.5 MiB body limit (110% of 25 MiB).
+ let large_blob = vec![0u8; (25 * 1024 * 1024) + (3 * 1024 * 1024)];
let form = Form::new()
.part(
@@ -1182,7 +1178,6 @@ async fn test_request_body_exceeds_110_percent_limit_returns_413() {
)
.await;
- // Axum's DefaultBodyLimit returns 413 Payload Too Large when the body exceeds the limit
assert_eq!(response.status(), StatusCode::PAYLOAD_TOO_LARGE);
}
@@ -1288,7 +1283,7 @@ fn setup_ai_test_router_with_capturing_sink() -> (Router, CapturingSink) {
false,
0.0_f32,
26_214_400, // 25MB default for AI endpoint
- 983_040, // ai_max_event_bytes (960KB, the previous hardcoded limit)
+ 983_040, // ai_max_event_bytes (960KB)
None, // body_chunk_read_timeout_ms
256, // body_read_chunk_size_kb
10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
@@ -1299,7 +1294,6 @@ fn setup_ai_test_router_with_capturing_sink() -> (Router, CapturingSink) {
None, // replay_overflow_limiter
8, // capture_v1_scatter_gather_min_batch
None, // ai_gateway_signing_secret
- false, // ai_events_overflow_enabled
None, // ingestion_warning_emitter
);
@@ -1957,7 +1951,7 @@ fn setup_ai_test_router_with_token_dropper(token_dropper: TokenDropper) -> (Rout
false, // is_mirror_deploy
0.0, // verbose_sample_percent
26_214_400, // ai_max_sum_of_parts_bytes
- 983_040, // ai_max_event_bytes (960KB, the previous hardcoded limit)
+ 983_040, // ai_max_event_bytes (960KB)
None, // body_chunk_read_timeout_ms
256, // body_read_chunk_size_kb
10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
@@ -1968,7 +1962,6 @@ fn setup_ai_test_router_with_token_dropper(token_dropper: TokenDropper) -> (Rout
None, // replay_overflow_limiter
8, // capture_v1_scatter_gather_min_batch
None, // ai_gateway_signing_secret
- false, // ai_events_overflow_enabled
None, // ingestion_warning_emitter
);
@@ -2023,7 +2016,7 @@ fn setup_ai_test_router_with_byte_limiter() -> (Router, CapturingSink) {
false, // is_mirror_deploy
0.0, // verbose_sample_percent
26_214_400, // ai_max_sum_of_parts_bytes
- 983_040, // ai_max_event_bytes (960KB, the previous hardcoded limit)
+ 983_040, // ai_max_event_bytes (960KB)
None, // body_chunk_read_timeout_ms
256, // body_read_chunk_size_kb
10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
@@ -2031,11 +2024,10 @@ fn setup_ai_test_router_with_byte_limiter() -> (Router, CapturingSink) {
None, // overflow_limiter
None, // ai_events_overflow_limiter
Some(byte_limiter),
- None, // replay_overflow_limiter
- 8, // capture_v1_scatter_gather_min_batch
- None, // ai_gateway_signing_secret
- false, // ai_events_overflow_enabled
- None, // ingestion_warning_emitter
+ None, // replay_overflow_limiter
+ 8, // capture_v1_scatter_gather_min_batch
+ None, // ai_gateway_signing_secret
+ None, // ingestion_warning_emitter
);
(router, sink_clone)
@@ -2285,7 +2277,7 @@ fn setup_ai_test_router_with_llm_quota_limited(token: &str) -> (Router, Capturin
false,
0.0_f32,
26_214_400,
- 983_040, // ai_max_event_bytes (960KB, the previous hardcoded limit)
+ 983_040, // ai_max_event_bytes (960KB)
None, // body_chunk_read_timeout_ms
256, // body_read_chunk_size_kb
10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
@@ -2296,7 +2288,6 @@ fn setup_ai_test_router_with_llm_quota_limited(token: &str) -> (Router, Capturin
None, // replay_overflow_limiter
8, // capture_v1_scatter_gather_min_batch
None, // ai_gateway_signing_secret
- false, // ai_events_overflow_enabled
None, // ingestion_warning_emitter
);
@@ -2389,21 +2380,11 @@ async fn test_ai_endpoint_quota_limiter_returns_billing_limit_error_message() {
// ============================================================================
// OverflowLimiter coverage for the AI endpoint
// ============================================================================
-//
-// These tests exercise the shared `stamp_overflow_reason` helper invoked in
-// `ai_handler` immediately after `build_kafka_event`. Pre-refactor the
-// OverflowLimiter check happened inside the kafka sink; now it's a pipeline
-// concern stamped into `ProcessedEventMetadata::overflow_reason`. Since AI
-// bypasses `events::analytics::process_events`, these tests are the
-// regression guard for `capture-ai-prod-us` (which runs with
-// `OVERFLOW_ENABLED=true` + `OVERFLOW_PRESERVE_PARTITION_LOCALITY=true`).
+// `ai_handler` calls `stamp_overflow_reason` with the AI lane's limiter, which setup builds only when both `OVERFLOW_ENABLED` and `AI_EVENTS_OVERFLOW_ENABLED` are set.
const AI_OVERFLOW_TEST_TOKEN: &str = "phc_VXRzc3poSG9GZm1JenRianJ6TTJFZGh4OWY2QXzx9f3";
-/// Variant of `setup_ai_test_router_with_capturing_sink` that wires a real
-/// `OverflowLimiter` into the router's AI lane — where AI-endpoint events land,
-/// so it is the limiter they consult. Existing helpers still pass `None`; this
-/// one opts in to exercise the governor path.
+/// AI-mode router with `ai_events_overflow_limiter` as the AI lane's limiter.
fn setup_ai_test_router_with_overflow_limiter(
ai_events_overflow_limiter: Arc<OverflowLimiter>,
) -> (Router, CapturingSink) {
@@ -2443,7 +2424,7 @@ fn setup_ai_test_router_with_overflow_limiter(
false,
0.0_f32,
26_214_400,
- 983_040, // ai_max_event_bytes (960KB, the previous hardcoded limit)
+ 983_040, // ai_max_event_bytes (960KB)
None,
256,
10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
@@ -2454,7 +2435,6 @@ fn setup_ai_test_router_with_overflow_limiter(
None, // replay_overflow_limiter
8, // capture_v1_scatter_gather_min_batch
None, // ai_gateway_signing_secret
- true, // ai_events_overflow_enabled
None, // ingestion_warning_emitter
);
@@ -2463,17 +2443,13 @@ fn setup_ai_test_router_with_overflow_limiter(
#[tokio::test]
async fn test_ai_event_with_hot_key_stamps_force_limited_reason() {
- // Configure the OverflowLimiter to force-route the specific
- // `token:distinct_id` key. `per_second`/`burst` are generous so only the
- // explicit `keys_to_reroute` entry triggers — this isolates the
- // ForceLimited branch from the RateLimited branch.
let hot_distinct_id = "user_hot_key";
let hot_key = format!("{AI_OVERFLOW_TEST_TOKEN}:{hot_distinct_id}");
let overflow_limiter = Arc::new(OverflowLimiter::new(
NonZeroU32::new(1_000).unwrap(),
NonZeroU32::new(1_000).unwrap(),
Some(hot_key),
- true, // preserve_locality (matches capture-ai-prod-us config)
+ true,
));
let (router, sink) = setup_ai_test_router_with_overflow_limiter(overflow_limiter);
@@ -2502,8 +2478,6 @@ async fn test_ai_event_with_hot_key_stamps_force_limited_reason() {
#[tokio::test]
async fn test_ai_event_with_cold_key_leaves_overflow_reason_none() {
- // Governor is wide open and no keys_to_reroute — the helper must leave
- // `overflow_reason` as None so the sink uses the default topic.
let overflow_limiter = Arc::new(OverflowLimiter::new(
NonZeroU32::new(1_000).unwrap(),
NonZeroU32::new(1_000).unwrap(),
@@ -2527,10 +2501,7 @@ async fn test_ai_event_with_cold_key_leaves_overflow_reason_none() {
}
#[tokio::test]
-async fn test_ai_endpoint_without_overflow_limiter_is_parity_with_pre_refactor() {
- // `capture-ai-*` with `OVERFLOW_ENABLED=false` (or setups without a
- // limiter configured at all) must behave exactly as before: reason stays
- // None. This pins the `None` short-circuit inside `stamp_overflow_reason`.
+async fn test_ai_endpoint_without_ai_limiter_stamps_no_reason() {
let (router, sink) = setup_ai_test_router_with_capturing_sink();
let test_client = TestClient::new(router);
@@ -2584,7 +2555,7 @@ fn ai_router(
false,
0.0_f32,
26_214_400,
- 983_040, // ai_max_event_bytes (960KB, the previous hardcoded limit)
+ 983_040, // ai_max_event_bytes (960KB)
None,
256,
10 * 1024 * 1024,
@@ -2595,8 +2566,7 @@ fn ai_router(
None,
8,
Some(GW_SECRET.to_string()),
- false, // ai_events_overflow_enabled
- None, // ingestion_warning_emitter
+ None, // ingestion_warning_emitter
);
(router, sink_clone)
}
diff --git a/rust/capture/tests/integration_ai_restrictions.rs b/rust/capture/tests/integration_ai_restrictions.rs
index 76abb1340cc9..bb4bb5f379e9 100644
--- a/rust/capture/tests/integration_ai_restrictions.rs
+++ b/rust/capture/tests/integration_ai_restrictions.rs
@@ -176,7 +176,7 @@ async fn setup_ai_router_with_restriction(
false,
0.0_f32,
26_214_400,
- 983_040, // ai_max_event_bytes (960KB, the previous hardcoded limit)
+ 983_040, // ai_max_event_bytes (960KB)
None,
256, // body_read_chunk_size_kb
10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
@@ -187,7 +187,6 @@ async fn setup_ai_router_with_restriction(
None, // replay_overflow_limiter
8, // capture_v1_scatter_gather_min_batch
None, // ai_gateway_signing_secret
- false, // ai_events_overflow_enabled
None, // ingestion_warning_emitter
);
@@ -497,7 +496,7 @@ async fn setup_ai_router_with_redirect_to_topic(
false,
0.0_f32,
26_214_400,
- 983_040, // ai_max_event_bytes (960KB, the previous hardcoded limit)
+ 983_040, // ai_max_event_bytes (960KB)
None,
256, // body_read_chunk_size_kb
10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
@@ -508,7 +507,6 @@ async fn setup_ai_router_with_redirect_to_topic(
None, // replay_overflow_limiter
8, // capture_v1_scatter_gather_min_batch
None, // ai_gateway_signing_secret
- false, // ai_events_overflow_enabled
None, // ingestion_warning_emitter
);
@@ -524,7 +522,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_events_overflow_enabled: bool,
) -> (Router, CapturingSink) {
let (readiness, liveness, _monitor) = test_lifecycle_handlers();
@@ -576,7 +573,7 @@ async fn setup_ai_router_with_force_overflow_and_limiter(
false,
0.0_f32,
26_214_400,
- 983_040, // ai_max_event_bytes (960KB, the previous hardcoded limit)
+ 983_040, // ai_max_event_bytes (960KB)
None,
256,
10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
@@ -587,8 +584,7 @@ async fn setup_ai_router_with_force_overflow_and_limiter(
None, // replay_overflow_limiter
8, // capture_v1_scatter_gather_min_batch
None, // ai_gateway_signing_secret
- ai_events_overflow_enabled,
- None, // ingestion_warning_emitter
+ None, // ingestion_warning_emitter
);
(router, sink_clone)
@@ -614,8 +610,7 @@ async fn test_ai_force_overflow_restriction_wins_over_overflow_limiter() {
));
let (router, sink) =
- setup_ai_router_with_force_overflow_and_limiter(restricted_token, overflow_limiter, false)
- .await;
+ setup_ai_router_with_force_overflow_and_limiter(restricted_token, overflow_limiter).await;
let test_client = TestClient::new(router);
let properties = json!({"$ai_model": "gpt-4"});
@@ -668,12 +663,9 @@ async fn test_ai_endpoint_keeps_events_on_the_ai_lane() {
));
// Restriction is registered for a different token, so only the limiter acts.
- let (router, sink) = setup_ai_router_with_force_overflow_and_limiter(
- "phc_some_other_token",
- overflow_limiter,
- true,
- )
- .await;
+ let (router, sink) =
+ setup_ai_router_with_force_overflow_and_limiter("phc_some_other_token", overflow_limiter)
+ .await;
let test_client = TestClient::new(router);
let properties = json!({"$ai_model": "gpt-4"});
@@ -692,7 +684,7 @@ async fn test_ai_endpoint_keeps_events_on_the_ai_lane() {
assert_eq!(
events[0].metadata.overflow_reason,
Some(OverflowReason::ForceLimited),
- "the AI lane's own limiter must apply once the valve is armed"
+ "the AI lane's own limiter must apply"
);
}
diff --git a/rust/capture/tests/integration_analytics_ai_routing.rs b/rust/capture/tests/integration_analytics_ai_routing.rs
index 578ce5321f52..0708c687971b 100644
--- a/rust/capture/tests/integration_analytics_ai_routing.rs
+++ b/rust/capture/tests/integration_analytics_ai_routing.rs
@@ -1,9 +1,9 @@
//! Endpoint-level coverage for AI event 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 (capture mode /
-//! `ai_events_overflow_enabled` not reaching the pipeline) or in the
-//! endpoint-level batch handling of mixed AI / non-AI payloads.
+//! cannot catch a regression in the router wiring (capture mode or the AI
+//! limiter not reaching the pipeline) or in the endpoint-level batch handling
+//! of mixed AI / non-AI payloads.
#[path = "common/integration_utils.rs"]
mod integration_utils;
@@ -77,13 +77,11 @@ impl PublishPrepared for CapturingSink {
}
fn setup_analytics_router(
- ai_events_overflow_enabled: bool,
overflow_limiter: Option<Arc<OverflowLimiter>>,
ai_events_overflow_limiter: Option<Arc<OverflowLimiter>>,
) -> (Router, CapturingSink) {
setup_router_for_mode(
CaptureMode::Events,
- ai_events_overflow_enabled,
overflow_limiter,
ai_events_overflow_limiter,
)
@@ -91,7 +89,6 @@ fn setup_analytics_router(
fn setup_router_for_mode(
capture_mode: CaptureMode,
- ai_events_overflow_enabled: bool,
overflow_limiter: Option<Arc<OverflowLimiter>>,
ai_events_overflow_limiter: Option<Arc<OverflowLimiter>>,
) -> (Router, CapturingSink) {
@@ -131,7 +128,7 @@ fn setup_router_for_mode(
false,
0.0_f32,
26_214_400,
- 983_040, // ai_max_event_bytes (960KB, the previous hardcoded limit)
+ 983_040, // ai_max_event_bytes (960KB)
None,
256, // body_read_chunk_size_kb
10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
@@ -142,7 +139,6 @@ fn setup_router_for_mode(
None, // replay_overflow_limiter
8, // capture_v1_scatter_gather_min_batch
None, // ai_gateway_signing_secret
- ai_events_overflow_enabled,
None, // ingestion_warning_emitter
);
@@ -227,7 +223,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(false, None, None);
+ let (router, sink) = setup_analytics_router(None, None);
let client = TestClient::new(router);
let event = json!({
"event": "$ai_span",
@@ -270,14 +266,9 @@ async fn legacy_routes_strip_forged_gateway_properties(#[case] path: &str) {
/// 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::valve_unarmed(false)]
-#[case::valve_armed(true)]
#[tokio::test]
-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);
+async fn mixed_batch_diverts_only_ai_events() {
+ let (router, sink) = setup_analytics_router(None, None);
let client = TestClient::new(router);
post_batch(&client, mixed_batch_payload()).await;
@@ -311,7 +302,7 @@ async fn mixed_batch_diverts_only_ai_events(#[case] ai_events_overflow_enabled:
/// half of the old version of this test now lives below.
#[tokio::test]
async fn ai_mode_diverts_ai_events_like_every_other_mode() {
- let (router, sink) = setup_router_for_mode(CaptureMode::Ai, false, None, None);
+ let (router, sink) = setup_router_for_mode(CaptureMode::Ai, None, None);
let client = TestClient::new(router);
let response = client
@@ -336,7 +327,7 @@ async fn ai_mode_diverts_ai_events_like_every_other_mode() {
/// Any `$ai_`-prefixed name lands on the AI lane, end to end through `/batch`.
#[tokio::test]
async fn any_ai_prefixed_name_diverts_to_the_ai_lane() {
- let (router, sink) = setup_router_for_mode(CaptureMode::Events, false, None, None);
+ let (router, sink) = setup_router_for_mode(CaptureMode::Events, None, None);
let client = TestClient::new(router);
let payload = json!({
@@ -370,7 +361,7 @@ async fn any_ai_prefixed_name_diverts_to_the_ai_lane() {
/// rejection is reachable through the router and surfaces as a 400.
#[tokio::test]
async fn ai_mode_rejects_a_mixed_batch_through_the_endpoint() {
- let (router, sink) = setup_router_for_mode(CaptureMode::Ai, false, None, None);
+ let (router, sink) = setup_router_for_mode(CaptureMode::Ai, None, None);
let client = TestClient::new(router);
let response = client
@@ -398,26 +389,17 @@ fn force_keyed_limiter() -> Arc<OverflowLimiter> {
))
}
-/// With `secondary` routing, a force-limited key on the AI limiter
-/// overflow-stamps the diverted AI event only when the AI overflow
-/// valve is armed (setup wires the AI limiter exactly then, so the test
-/// mirrors that coupling), while the `$pageview` on the same hot key
-/// (force-limited on the analytics limiter) stamps in both cases (the
-/// analytics lane is valve-independent). Catches the router failing to
-/// thread the AI limiter into the pipeline, which the process-level tests
-/// cannot see.
#[rstest]
-#[case::valve_armed(true, Some(OverflowReason::ForceLimited))]
-#[case::valve_unarmed(false, None)]
+#[case::limiter_present(true, Some(OverflowReason::ForceLimited))]
+#[case::limiter_absent(false, None)]
#[tokio::test]
-async fn ai_lane_overflow_stamping_gated_on_valve(
- #[case] ai_events_overflow_enabled: bool,
+async fn ai_lane_limiter_overflow_follows_the_ai_limiter(
+ #[case] ai_limiter_present: bool,
#[case] expected_ai_reason: Option<OverflowReason>,
) {
let (router, sink) = setup_analytics_router(
- ai_events_overflow_enabled,
Some(force_keyed_limiter()),
- ai_events_overflow_enabled.then(force_keyed_limiter),
+ ai_limiter_present.then(force_keyed_limiter),
);
let client = TestClient::new(router);
@@ -441,7 +423,7 @@ async fn ai_lane_overflow_stamping_gated_on_valve(
assert_eq!(
pageview.metadata.overflow_reason,
Some(OverflowReason::ForceLimited),
- "the analytics lane must keep overflowing regardless of the AI valve"
+ "the analytics lane must keep overflowing regardless of the AI limiter"
);
}
@@ -458,11 +440,8 @@ async fn ai_lane_overflow_isolated_from_analytics_limiter() {
false, // preserve_locality
));
- let (router, sink) = setup_analytics_router(
- true, // valve armed
- Some(force_keyed_limiter()),
- Some(clean_ai_limiter),
- );
+ let (router, sink) =
+ setup_analytics_router(Some(force_keyed_limiter()), Some(clean_ai_limiter));
let client = TestClient::new(router);
post_batch(&client, mixed_batch_payload()).await;
@@ -490,20 +469,10 @@ async fn ai_lane_overflow_isolated_from_analytics_limiter() {
);
}
-/// 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,
- false,
- Some(force_keyed_limiter()),
- None,
- );
+ let (router, sink) =
+ setup_router_for_mode(CaptureMode::Import, Some(force_keyed_limiter()), None);
let client = TestClient::new(router);
post_batch(&client, historical_mixed_batch_payload()).await;
@@ -528,7 +497,7 @@ async fn import_mode_historical_batch_never_overflows() {
);
assert_eq!(
event.metadata.overflow_reason, None,
- "no lane may overflow in Import mode with the AI valve unset ({})",
+ "no lane may overflow in Import mode ({})",
event.metadata.event_name,
);
}
diff --git a/rust/capture/tests/integration_analytics_restrictions.rs b/rust/capture/tests/integration_analytics_restrictions.rs
index 9818a6938f8b..d2b667736c60 100644
--- a/rust/capture/tests/integration_analytics_restrictions.rs
+++ b/rust/capture/tests/integration_analytics_restrictions.rs
@@ -71,7 +71,6 @@ async fn setup_analytics_router_with_restriction(
restriction_type: RestrictionType,
restriction_pipeline: Pipeline,
token: &str,
- ai_events_overflow_enabled: bool,
) -> (Router, CapturingSink) {
let (readiness, liveness, _monitor) = test_lifecycle_handlers();
@@ -126,7 +125,7 @@ async fn setup_analytics_router_with_restriction(
false,
0.0_f32,
26_214_400,
- 983_040, // ai_max_event_bytes (960KB, the previous hardcoded limit)
+ 983_040, // ai_max_event_bytes (960KB)
None,
256, // body_read_chunk_size_kb
10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
@@ -137,8 +136,7 @@ async fn setup_analytics_router_with_restriction(
None, // replay_overflow_limiter
8, // capture_v1_scatter_gather_min_batch
None, // ai_gateway_signing_secret
- ai_events_overflow_enabled,
- None, // ingestion_warning_emitter
+ None, // ingestion_warning_emitter
);
(router, sink_clone)
@@ -221,7 +219,6 @@ async fn test_analytics_drop_event_restriction() {
RestrictionType::DropEvent,
Pipeline::Analytics,
restricted_token,
- false,
)
.await;
let test_client = TestClient::new(router);
@@ -257,7 +254,6 @@ async fn test_analytics_redirect_to_dlq_restriction() {
RestrictionType::RedirectToDlq,
Pipeline::Analytics,
restricted_token,
- false,
)
.await;
let test_client = TestClient::new(router);
@@ -303,7 +299,6 @@ async fn test_analytics_force_overflow_restriction() {
RestrictionType::ForceOverflow,
Pipeline::Analytics,
restricted_token,
- false,
)
.await;
let test_client = TestClient::new(router);
@@ -344,22 +339,11 @@ async fn test_analytics_force_overflow_restriction() {
#[tokio::test]
async fn test_analytics_force_overflow_restriction_applies_to_diverted_ai_event() {
- // An AI event diverted onto the AI lane is governed by ai-scoped
- // 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 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
- // events, which the process-level tests can't see end-to-end.
let restricted_token = "phc_restricted_overflow_ai_token";
let (router, sink) = setup_analytics_router_with_restriction(
RestrictionType::ForceOverflow,
Pipeline::Ai,
restricted_token,
- true,
)
.await;
let test_client = TestClient::new(router);
@@ -409,7 +393,6 @@ async fn test_analytics_skip_person_processing_restriction() {
RestrictionType::SkipPersonProcessing,
Pipeline::Analytics,
restricted_token,
- false,
)
.await;
let test_client = TestClient::new(router);
@@ -455,7 +438,6 @@ async fn test_analytics_restriction_does_not_apply_to_other_tokens() {
RestrictionType::DropEvent,
Pipeline::Analytics,
restricted_token,
- false,
)
.await;
let test_client = TestClient::new(router);
@@ -552,7 +534,7 @@ async fn setup_analytics_router_with_redirect_to_topic(
false,
0.0_f32,
26_214_400,
- 983_040, // ai_max_event_bytes (960KB, the previous hardcoded limit)
+ 983_040, // ai_max_event_bytes (960KB)
None,
256, // body_read_chunk_size_kb
10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
@@ -563,7 +545,6 @@ async fn setup_analytics_router_with_redirect_to_topic(
None, // replay_overflow_limiter
8, // capture_v1_scatter_gather_min_batch
None, // ai_gateway_signing_secret
- false, // ai_events_overflow_enabled
None, // ingestion_warning_emitter
);
diff --git a/rust/capture/tests/integration_otel_endpoint.rs b/rust/capture/tests/integration_otel_endpoint.rs
index b87a7ce21af6..05d803c0e390 100644
--- a/rust/capture/tests/integration_otel_endpoint.rs
+++ b/rust/capture/tests/integration_otel_endpoint.rs
@@ -135,17 +135,13 @@ struct TestClientOptions {
event_restriction_service: Option<EventRestrictionService>,
quota_limiter: Option<CaptureQuotaLimiter>,
ai_gateway_signing_secret: Option<String>,
- // Opt-in OverflowLimiter wiring, on the AI lane where OTEL spans land.
- // `None` (default) matches production configs without
- // `OVERFLOW_ENABLED=true` and exercises the no-op branch of
- // `stamp_overflow_reason`.
+ // `None` matches deploys without both `OVERFLOW_ENABLED` and `AI_EVENTS_OVERFLOW_ENABLED`.
ai_events_overflow_limiter: Option<Arc<OverflowLimiter>>,
// Opt-in warnings emitter. `None` (default) matches deploys without
// `CAPTURE_INGESTION_WARNINGS_ENABLED` and exercises the no-op branch of
// every emit site.
ingestion_warning_emitter: Option<Arc<dyn WarningEmitter>>,
- // Per-event AI size ceiling. `None` keeps the 960KB the multipart
- // endpoint enforced before it became configurable.
+ // `None` uses 960KB (983_040).
ai_max_event_bytes: Option<u64>,
// Opt-in AI byte budget. `None` (default) matches deploys with
// `AI_BYTE_LIMIT_PER_SECOND=0`, where setup builds no limiter.
@@ -206,7 +202,6 @@ fn make_test_client_with_options(sink: &CapturingSink, options: TestClientOption
None, // replay_overflow_limiter
8, // capture_v1_scatter_gather_min_batch
options.ai_gateway_signing_secret,
- true, // ai_events_overflow_enabled
options.ingestion_warning_emitter, // ingestion_warning_emitter
);
@@ -1681,17 +1676,7 @@ async fn test_filtered_drop_restriction_rejects_otel_batch() {
// ============================================================================
// OverflowLimiter coverage for the OTEL endpoint
// ============================================================================
-//
-// `otel_handler` bypasses `events::analytics::process_events` and produces
-// `DataType::AiEvents` spans directly, so the shared `stamp_overflow_reason`
-// helper is what preserves OverflowLimiter parity for `capture-ai-prod-us`.
-// These tests exercise the helper end-to-end across the OTEL batch path.
-//
-// Note on OTEL batching semantics: `otel::identity::extract_distinct_id`
-// returns a single distinct_id for the entire request (derived from
-// ResourceSpan attributes), so all spans in one request share the same
-// `token:distinct_id` key. The helper still evaluates per-event — the tests
-// below reflect the realistic per-request shape.
+// `make_three_span_request` sets `posthog.distinct_id` only on the resource, so all its spans share one `token:distinct_id` key.
fn make_three_span_request() -> ExportTraceServiceRequest {
ExportTraceServiceRequest {
@@ -1837,9 +1822,6 @@ async fn test_otel_batch_rate_limited_key_stamps_overbudget_spans() {
#[tokio::test]
async fn test_otel_batch_without_overflow_limiter_leaves_reason_none() {
- // Baseline: no limiter wired (deploy without `OVERFLOW_ENABLED=true`) —
- // overflow_reason must stay None across the batch, matching pre-refactor
- // behavior.
let sink = CapturingSink::new();
let request = make_three_span_request();
diff --git a/rust/capture/tests/integration_person_processing_matrix.rs b/rust/capture/tests/integration_person_processing_matrix.rs
index dbfc8ec22446..faa7833d3d56 100644
--- a/rust/capture/tests/integration_person_processing_matrix.rs
+++ b/rust/capture/tests/integration_person_processing_matrix.rs
@@ -227,7 +227,10 @@ async fn run_v0(inputs: Inputs, distinct_ids: &[&str]) -> Batch {
let service = build_restrictions(inputs).await;
let producer = MockKafkaProducer::new();
- let sink = KafkaSinkBase::with_producer(producer.clone(), OutputTable::from(&cfg.outputs));
+ let sink = KafkaSinkBase::with_producer(
+ producer.clone(),
+ OutputTable::new(&cfg.outputs, cfg.capture_mode.has_ai_overflow_lane()),
+ );
let quota_limiter =
CaptureQuotaLimiter::new(&cfg, redis.clone(), Duration::from_secs(60 * 60 * 24 * 7));
@@ -254,7 +257,7 @@ async fn run_v0(inputs: Inputs, distinct_ids: &[&str]) -> Batch {
false,
0.0_f32,
26_214_400,
- 983_040, // ai_max_event_bytes (960KB, the previous hardcoded limit)
+ 983_040, // ai_max_event_bytes (960KB)
None,
256,
10 * 1024 * 1024,
@@ -265,7 +268,6 @@ async fn run_v0(inputs: Inputs, distinct_ids: &[&str]) -> Batch {
None,
8,
None,
- false,
None,
);
diff --git a/rust/capture/tests/integration_replay_restrictions.rs b/rust/capture/tests/integration_replay_restrictions.rs
index da810ef15cfb..461d036547cf 100644
--- a/rust/capture/tests/integration_replay_restrictions.rs
+++ b/rust/capture/tests/integration_replay_restrictions.rs
@@ -123,7 +123,7 @@ async fn setup_recordings_router_with_restriction(
false,
0.0_f32,
26_214_400,
- 983_040, // ai_max_event_bytes (960KB, the previous hardcoded limit)
+ 983_040, // ai_max_event_bytes (960KB)
None,
256, // body_read_chunk_size_kb
10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
@@ -134,7 +134,6 @@ async fn setup_recordings_router_with_restriction(
None, // replay_overflow_limiter
8, // capture_v1_scatter_gather_min_batch
None, // ai_gateway_signing_secret
- false, // ai_events_overflow_enabled
None, // ingestion_warning_emitter
);
@@ -495,7 +494,7 @@ async fn setup_recordings_router_with_redirect_to_topic(
false,
0.0_f32,
26_214_400,
- 983_040, // ai_max_event_bytes (960KB, the previous hardcoded limit)
+ 983_040, // ai_max_event_bytes (960KB)
None,
256, // body_read_chunk_size_kb
10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
@@ -506,7 +505,6 @@ async fn setup_recordings_router_with_redirect_to_topic(
None, // replay_overflow_limiter
8, // capture_v1_scatter_gather_min_batch
None, // ai_gateway_signing_secret
- false, // ai_events_overflow_enabled
None, // ingestion_warning_emitter
);
diff --git a/rust/capture/tests/integration_wire_body_limits.rs b/rust/capture/tests/integration_wire_body_limits.rs
index a25b996c8c90..62e883c2c3a3 100644
--- a/rust/capture/tests/integration_wire_body_limits.rs
+++ b/rust/capture/tests/integration_wire_body_limits.rs
@@ -110,7 +110,6 @@ fn make_test_client(mode: CaptureMode) -> (TestClient, CapturingSink) {
None, // replay_overflow_limiter
8,
None,
- false,
None,
);
diff --git a/rust/capture/tests/quota_limiters.rs b/rust/capture/tests/quota_limiters.rs
index a2cb1fb5e36c..b0809eeebf3b 100644
--- a/rust/capture/tests/quota_limiters.rs
+++ b/rust/capture/tests/quota_limiters.rs
@@ -145,7 +145,7 @@ async fn setup_router_with_limits(
false, // is_mirror_deploy
0.0, // verbose_sample_percent
26_214_400, // ai_max_sum_of_parts_bytes (25MB)
- 983_040, // ai_max_event_bytes (960KB, the previous hardcoded limit)
+ 983_040, // ai_max_event_bytes (960KB)
None, // body_chunk_read_timeout_ms
256, // body_read_chunk_size_kb
10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
@@ -156,7 +156,6 @@ async fn setup_router_with_limits(
None, // replay_overflow_limiter
8, // capture_v1_scatter_gather_min_batch
None, // ai_gateway_signing_secret
- false, // ai_events_overflow_enabled
None, // ingestion_warning_emitter
);
@@ -350,7 +349,6 @@ async fn test_billing_limit_retains_only_scoped_limiter_events() {
// Should return OK even when billing limited (legacy behavior)
assert_eq!(response.status(), StatusCode::OK);
- // Check that only exception events were retained
let captured_events = sink.events();
assert_eq!(captured_events.len(), 3);
@@ -502,7 +500,6 @@ async fn test_billing_limit_retains_scoped_limiter_events_iv0e_endpoint() {
// Should return OK even when billing limited
assert_eq!(response.status(), StatusCode::OK);
- // Check that only $exception events were retained
let captured_events = sink.events();
// all but the exception, AI, and survey events should be dropped from the input batch
@@ -546,22 +543,18 @@ async fn test_exception_limiter_filters_only_exception_events() {
.send()
.await;
- // Should return OK even when survey limited
assert_eq!(response.status(), StatusCode::OK);
- // ALL survey events should be filtered out when quota exceeded, other events should be captured
let captured_events = sink.events();
- assert_eq!(captured_events.len(), 4); // pageview, click, $exception
+ assert_eq!(captured_events.len(), 4);
let event_names: Vec<String> = extract_captured_event_names(&captured_events);
- // Non-survey events should be present
assert!(event_names.contains(&"pageview".to_string()));
assert!(event_names.contains(&"click".to_string()));
assert!(event_names.contains(&"$ai_your_absolutely_right".to_string()));
assert!(event_names.contains(&"survey sent".to_string()));
- // All survey events should be filtered out when quota exceeded
assert!(!event_names.contains(&"$exception".to_string()));
}
@@ -577,7 +570,6 @@ async fn test_exception_limiter_returns_ok_when_only_exception_events() {
.await;
let client = TestClient::new(router);
- // Only survey events in the payload
let events = ["$exception", "$exception", "$exception"];
let payload = create_batch_payload_with_token(&events, token);
@@ -592,7 +584,6 @@ async fn test_exception_limiter_returns_ok_when_only_exception_events() {
// Should return OK (legacy behavior - errors are converted to OK for v0 endpoints)
assert_eq!(response.status(), StatusCode::OK);
- // When quota exceeded, ALL survey events should be filtered out
let captured_events = sink.events();
assert_eq!(captured_events.len(), 0);
}
@@ -606,7 +597,7 @@ async fn test_exception_limiter_allows_exception_events_when_not_limited() {
true,
vec![QuotaResource::Surveys, QuotaResource::LLMEvents],
)
- .await; // Not survey limited
+ .await;
let client = TestClient::new(router);
let events = [
@@ -630,7 +621,6 @@ async fn test_exception_limiter_allows_exception_events_when_not_limited() {
// Should return OK
assert_eq!(response.status(), StatusCode::OK);
- // All events should be captured when not survey limited
let captured_events = sink.events();
assert_eq!(captured_events.len(), 2);
@@ -652,7 +642,7 @@ async fn test_both_billing_and_exception_limits_applied() {
true,
vec![QuotaResource::Exceptions],
)
- .await; // Both billing and survey limited
+ .await;
let client = TestClient::new(router);
let events = [
@@ -675,9 +665,6 @@ async fn test_both_billing_and_exception_limits_applied() {
// Should return OK
assert_eq!(response.status(), StatusCode::OK);
- // First billing limit is applied (retains only $exception and survey events)
- // Then survey limit is applied (filters out survey events)
- // So only $exception should remain
let captured_events = sink.events();
assert_eq!(captured_events.len(), 2);
@@ -847,9 +834,6 @@ async fn test_both_billing_and_survey_limits_applied() {
// Should return OK
assert_eq!(response.status(), StatusCode::OK);
- // First billing limit is applied (retains only $exception and survey events)
- // Then survey limit is applied (filters out survey events)
- // So only $exception should remain
let captured_events = sink.events();
assert_eq!(captured_events.len(), 2);
@@ -1199,7 +1183,7 @@ async fn test_survey_quota_cross_batch_first_submission_allowed() {
false,
0.0,
26_214_400,
- 983_040, // ai_max_event_bytes (960KB, the previous hardcoded limit)
+ 983_040, // ai_max_event_bytes (960KB)
None, // body_chunk_read_timeout_ms
256, // body_read_chunk_size_kb
10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
@@ -1210,7 +1194,6 @@ async fn test_survey_quota_cross_batch_first_submission_allowed() {
None, // replay_overflow_limiter
8, // capture_v1_scatter_gather_min_batch
None, // ai_gateway_signing_secret
- false, // ai_events_overflow_enabled
None, // ingestion_warning_emitter
);
@@ -1291,7 +1274,7 @@ async fn test_survey_quota_cross_batch_duplicate_submission_dropped() {
false,
0.0,
26_214_400,
- 983_040, // ai_max_event_bytes (960KB, the previous hardcoded limit)
+ 983_040, // ai_max_event_bytes (960KB)
None, // body_chunk_read_timeout_ms
256, // body_read_chunk_size_kb
10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
@@ -1302,7 +1285,6 @@ async fn test_survey_quota_cross_batch_duplicate_submission_dropped() {
None, // replay_overflow_limiter
8, // capture_v1_scatter_gather_min_batch
None, // ai_gateway_signing_secret
- false, // ai_events_overflow_enabled
None, // ingestion_warning_emitter
);
@@ -1387,7 +1369,7 @@ async fn test_survey_quota_cross_batch_redis_error_fail_open() {
false,
0.0,
26_214_400,
- 983_040, // ai_max_event_bytes (960KB, the previous hardcoded limit)
+ 983_040, // ai_max_event_bytes (960KB)
None, // body_chunk_read_timeout_ms
256, // body_read_chunk_size_kb
10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
@@ -1398,7 +1380,6 @@ async fn test_survey_quota_cross_batch_redis_error_fail_open() {
None, // replay_overflow_limiter
8, // capture_v1_scatter_gather_min_batch
None, // ai_gateway_signing_secret
- false, // ai_events_overflow_enabled
None, // ingestion_warning_emitter
);
@@ -1444,10 +1425,10 @@ async fn test_survey_and_global_limited_drops_all_events_when_only_matching_even
// Mix of all survey event types - when quota exceeded, ALL survey events should be dropped
let events = [
- ("survey sent", Some("submission_123")), // This should be dropped due to quota
- ("survey shown", Some("submission_123")), // This should also be dropped when quota exceeded
- ("survey dismissed", Some("submission_123")), // This should also be dropped when quota exceeded
- ("pageview", None), // Non-survey event
+ ("survey sent", Some("submission_123")),
+ ("survey shown", Some("submission_123")),
+ ("survey dismissed", Some("submission_123")),
+ ("pageview", None),
];
let payload = create_survey_events_with_submission_ids(&events, token);
@@ -1463,7 +1444,7 @@ async fn test_survey_and_global_limited_drops_all_events_when_only_matching_even
// When survey quota is exceeded, ALL survey events should be dropped
let captured_events = sink.events();
- assert_eq!(captured_events.len(), 0); // only pageview
+ assert_eq!(captured_events.len(), 0);
}
#[tokio::test]
@@ -1820,7 +1801,7 @@ async fn test_ai_quota_cross_batch_redis_error_fail_open() {
false,
0.0,
26_214_400,
- 983_040, // ai_max_event_bytes (960KB, the previous hardcoded limit)
+ 983_040, // ai_max_event_bytes (960KB)
None, // body_chunk_read_timeout_ms
256, // body_read_chunk_size_kb
10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
@@ -1831,7 +1812,6 @@ async fn test_ai_quota_cross_batch_redis_error_fail_open() {
None, // replay_overflow_limiter
8, // capture_v1_scatter_gather_min_batch
None, // ai_gateway_signing_secret
- false, // ai_events_overflow_enabled
None, // ingestion_warning_emitter
);
diff --git a/rust/capture/tests/routing_e2e.rs b/rust/capture/tests/routing_e2e.rs
index bc346e6d6f9e..a5d5ebe1e898 100644
--- a/rust/capture/tests/routing_e2e.rs
+++ b/rust/capture/tests/routing_e2e.rs
@@ -224,7 +224,7 @@ async fn it_routes_diverted_ai_events_to_the_ai_topic() -> Result<()> {
}
#[tokio::test]
-async fn it_routes_forced_ai_events_to_ai_overflow_when_the_valve_is_armed() -> Result<()> {
+async fn it_routes_limiter_overflowed_ai_events_to_ai_overflow() -> Result<()> {
setup_tracing();
let token = random_string("token", 16);
let distinct_id = random_string("id", 16);
@@ -232,11 +232,14 @@ async fn it_routes_forced_ai_events_to_ai_overflow_when_the_valve_is_armed() ->
let main_topic = EphemeralTopic::new().await;
let ai_topic = EphemeralTopic::new().await;
let ai_overflow_topic = EphemeralTopic::new().await;
+ let analytics_overflow_topic = EphemeralTopic::new().await;
let mut config = DEFAULT_CONFIG.clone();
config.outputs.analytics_main_topic = main_topic.topic_name().to_string();
+ config.outputs.analytics_overflow_topic = analytics_overflow_topic.topic_name().to_string();
config.outputs.ai_main_topic = ai_topic.topic_name().to_string();
- config.outputs.ai_overflow_topic = Some(ai_overflow_topic.topic_name().to_string());
+ config.outputs.ai_overflow_topic = ai_overflow_topic.topic_name().to_string();
+ config.ai_events_overflow_enabled = true;
config.overflow_enabled = true;
config.overflow_burst_limit = NonZeroU32::new(10).unwrap();
config.overflow_per_second_limit = NonZeroU32::new(10).unwrap();
@@ -251,8 +254,6 @@ async fn it_routes_forced_ai_events_to_ai_overflow_when_the_valve_is_armed() ->
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!(
@@ -270,5 +271,6 @@ async fn it_routes_forced_ai_events_to_ai_overflow_when_the_valve_is_armed() ->
ai_topic.assert_empty();
main_topic.assert_empty();
+ analytics_overflow_topic.assert_empty();
Ok(())
}
diff --git a/rust/capture/tests/v1_publish.rs b/rust/capture/tests/v1_publish.rs
index 3cf2ba77ac72..4cea2b5bf0e4 100644
--- a/rust/capture/tests/v1_publish.rs
+++ b/rust/capture/tests/v1_publish.rs
@@ -17,7 +17,7 @@ use std::collections::HashMap;
use anyhow::Result;
use common_types::{CapturedEvent, RawEvent};
-use capture::config::EnvelopeCompression;
+use capture::config::{Config, EnvelopeCompression};
use capture::outputs::OutputRegistry;
use capture::producers::{self, ProducerRegistry};
use capture::sinks::kafka::KafkaSink;
@@ -34,6 +34,13 @@ fn v1_test_context() -> RequestContext {
}
async fn v1_outputs(topic: &str) -> OutputRegistry {
+ v1_outputs_with(topic, |_| {}).await
+}
+
+async fn v1_outputs_with(
+ topic: &str,
+ override_outputs: impl FnOnce(&mut Config),
+) -> OutputRegistry {
let producer_configs =
producers::load_all(&test_producer_env()).expect("failed to load producer config");
let producers = ProducerRegistry::build(&producer_configs, HashMap::new())
@@ -41,7 +48,9 @@ async fn v1_outputs(topic: &str) -> OutputRegistry {
let mut config = DEFAULT_CONFIG.clone();
point_outputs_at(&mut config, topic);
- let table = OutputTable::from(&config.outputs).map_producers(|name| producers.get(*name));
+ override_outputs(&mut config);
+ let table = OutputTable::new(&config.outputs, config.capture_mode.has_ai_overflow_lane())
+ .map_producers(|name| producers.get(*name));
OutputRegistry::single(KafkaSink::new(table, EnvelopeCompression::None))
}
@@ -213,14 +222,18 @@ async fn v1_dropped_event_not_published() -> Result<()> {
}
// ---------------------------------------------------------------------------
-// Exception event routes to exception topic
+// Exception event routes to the error tracking topic
// ---------------------------------------------------------------------------
#[tokio::test]
async fn v1_exception_event_round_trip() -> Result<()> {
setup_tracing();
let topic = EphemeralTopic::new().await;
- let outputs = v1_outputs(topic.topic_name()).await;
+ let exception_topic = EphemeralTopic::new().await;
+ let outputs = v1_outputs_with(topic.topic_name(), |config| {
+ config.outputs.error_tracking_topic = exception_topic.topic_name().to_string();
+ })
+ .await;
let ctx = v1_test_context();
let uuid = uuid::Uuid::new_v4();
@@ -235,12 +248,13 @@ async fn v1_exception_event_round_trip() -> Result<()> {
assert_eq!(results.len(), 1);
assert!(matches!(results[0].outcome, Outcome::Published));
- let event_json = topic.next_event()?;
+ let event_json = exception_topic.next_event()?;
let captured: CapturedEvent = serde_json::from_value(event_json)?;
assert_eq!(captured.event, "$exception");
assert_eq!(captured.uuid, uuid);
assert_eq!(captured.distinct_id, "integ-user-exception");
+ exception_topic.assert_empty();
topic.assert_empty();
Ok(())
}
@@ -364,14 +378,22 @@ async fn v1_empty_options_no_injection() -> Result<()> {
}
// ---------------------------------------------------------------------------
-// Multi-destination batch — events route correctly
+// Multi-destination batch — each event lands on its destination's topic
// ---------------------------------------------------------------------------
#[tokio::test]
async fn v1_multi_destination_batch() -> Result<()> {
setup_tracing();
let topic = EphemeralTopic::new().await;
- let outputs = v1_outputs(topic.topic_name()).await;
+ let main_topic = EphemeralTopic::new().await;
+ let historical_topic = EphemeralTopic::new().await;
+ let overflow_topic = EphemeralTopic::new().await;
+ let outputs = v1_outputs_with(topic.topic_name(), |config| {
+ config.outputs.analytics_main_topic = main_topic.topic_name().to_string();
+ config.outputs.analytics_historical_topic = historical_topic.topic_name().to_string();
+ config.outputs.analytics_overflow_topic = overflow_topic.topic_name().to_string();
+ })
+ .await;
let ctx = v1_test_context();
let main_ev = test_utils::realistic_pageview("integ-dest-main");
@@ -387,17 +409,15 @@ async fn v1_multi_destination_batch() -> Result<()> {
assert!(matches!(r.outcome, Outcome::Published));
}
- let mut distinct_ids = Vec::new();
- for _ in 0..3 {
- let json = topic.next_event()?;
- let captured: CapturedEvent = serde_json::from_value(json)?;
- distinct_ids.push(captured.distinct_id.clone());
+ for (dest_topic, expected_distinct_id) in [
+ (&main_topic, "integ-dest-main"),
+ (&historical_topic, "integ-dest-hist"),
+ (&overflow_topic, "integ-dest-overflow"),
+ ] {
+ let captured: CapturedEvent = serde_json::from_value(dest_topic.next_event()?)?;
+ assert_eq!(captured.distinct_id, expected_distinct_id);
+ dest_topic.assert_empty();
}
- distinct_ids.sort();
- assert_eq!(
- distinct_ids,
- vec!["integ-dest-hist", "integ-dest-main", "integ-dest-overflow"]
- );
topic.assert_empty();
Ok(())