:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(aio): cap AI-lane bytes per project, fleet-wide (#83680)
Paweł Ledwoń48f924706d5e
diff --git a/rust/capture/OUTPUTS_REFACTOR_PLAN.md b/rust/capture/OUTPUTS_REFACTOR_PLAN.mdindex b0bfb3d75fe9..4abe831b4616 100644--- a/rust/capture/OUTPUTS_REFACTOR_PLAN.md+++ b/rust/capture/OUTPUTS_REFACTOR_PLAN.md@@ -199,7 +199,7 @@ Goal: v1 endpoints publish through `dyn Outputs` like every other ingress, so fa### AI pipeline and Import mode-- **AI pipeline membership is stamp-based, not name-based.** The divert decision is a capture-mode property: on modes that route AI events (`CaptureMode::routes_ai_events` — Events and Import), `$ai_*` events stamp `DataType::AiEvents` during processing, mirroring v1's `Destination::AiEvents`; `Pipeline::from_metadata` maps the stamp. There is no per-batch routing config — the rollout-era `AiRouting` mode/allowlist/percentage machinery is retired. A `$ai_*` event on a non-routing mode is a plain analytics event on the analytics lanes, and the multipart/OTEL AI ingress stamps `AnalyticsMain` and publishes to the analytics rows. `AI_EVENT_PREFIX` remains only for the quota predicate and the stamping decision.+- **AI pipeline membership is a name allowlist, resolved once into a stamp.** `AI_EVENT_NAMES` lists the event names on the lane; `DataType::from_event_name` resolves a name against it and stamps `DataType::AiEvents`, on every capture mode, mirroring v1's `Destination::AiEvents`. Everything downstream reads the stamp — `Pipeline::from_metadata` maps it, and the multipart and OTEL AI ingress stamp the same lane at the handler. The allowlist is deliberately not an `$ai_` prefix match: the Node AI pipeline DLQs anything it receives off its own `AI_EVENT_TYPES` list, so a prefixed-but-unlisted name like `$ai_call` must stay on the analytics lane. (The quota predicate `is_llm_event` is separate and *is* prefix-based.) There is no per-batch routing config and no per-deployment divert switch — the rollout-era `AiRouting` mode/allowlist/percentage machinery is retired, and so is the capture-mode predicate that replaced it. A deployment that wants AI traffic on a given topic points `CAPTURE_ANALYTICS_AI_EVENTS_TOPIC` at it.- **The AI lanes own dedicated topics.** `TopicTable` grows an `ai_events` row (`CAPTURE_ANALYTICS_AI_EVENTS_TOPIC`, required with default `events_plugin_ingestion_ai`) and an optional `ai_events_overflow` row (`..._OVERFLOW_TOPIC`); there is no `AiLane::Historical` — the divert decision wins over historical, matching v1. The AI overflow valve (overflow topic set) rides `PrepSpec` into `resolve`, so an unarmed deployment never routes the AI lane to overflow, force_overflow included.- **Import mode** is an analytics-family deployment on `router::router`; it mounts `/i/v0/ai/batch` (gated batch handler) but not the ai/otel handlers, and shares the Events topic requirements.diff --git a/rust/capture/src/ai_endpoint.rs b/rust/capture/src/ai_endpoint.rsindex 69e06d66b5c5..6c0f08e6b517 100644--- a/rust/capture/src/ai_endpoint.rs+++ b/rust/capture/src/ai_endpoint.rs@@ -23,6 +23,7 @@ use crate::api::{CaptureError, CaptureResponse, CaptureResponseCode};use crate::event_restrictions::{AppliedRestrictions, EventContext as RestrictionEventContext, Pipeline,};+use crate::events::ai_byte_limit::charge_ai_bytes;use crate::events::overflow_stamping::stamp_overflow_reason;use crate::extractors::extract_body_with_timeout;use crate::ingestion_warnings::ai::emit_ai_failure_warning;@@ -32,7 +33,9 @@ use crate::prometheus::{report_dropped_events, report_internal_error_metrics};use crate::router::State as AppState;use crate::timestamp;use crate::token::validate_token;-use crate::v0_request::{DataType, ProcessedEvent, ProcessedEventMetadata};+use crate::v0_request::{+ exceeds_max_ai_event_bytes, DataType, ProcessedEvent, ProcessedEventMetadata,+};use crate::v1::gateway_provenance as gp;#[derive(Debug, Clone, Serialize, Deserialize)]@@ -303,7 +306,8 @@ async fn ai_handler_inner(};// Step 5: Retrieve and validate remaining multipart parts (continues parsing from multipart)- let parts = retrieve_multipart_parts(&mut multipart, event_metadata).await?;+ let parts =+ retrieve_multipart_parts(&mut multipart, event_metadata, state.ai_max_event_bytes).await?;// Step 6: Parse the partslet mut parsed = parse_multipart_data(parts)?;@@ -356,6 +360,29 @@ async fn ai_handler_inner(let (accepted_parts, mut processed_event) =build_kafka_event(parsed, token, &client_ip, &state, &applied_restrictions)?;+ // Step 8a: Charge the AI lane's per-project byte budget. This endpoint+ // builds its event at the handler and reaches the sink through neither+ // analytics pipeline, so without this a sender could spend an unbounded+ // number of bytes here while the same bytes on `/i/v0/ai/batch` are capped.+ //+ // Charged on the serialized event the sink would produce, which is the+ // measure the legacy path charges, and after restrictions, quota, and the+ // combined-size ceiling — nothing that was never going to publish spends+ // the project's budget.+ //+ // An over-budget event answers 200 with no accepted parts, the shape this+ // handler already uses for the token dropper and for a `DropEvent`+ // restriction. A rate drop is ops-imposed, so it is reported to the client+ // only as "nothing was accepted", never as a request failure.+ if let Some(ref limiter) = state.ai_byte_rate_limiter {+ if charge_ai_bytes(limiter, token, processed_event.event.data.len()).await {+ report_dropped_events("ai_byte_rate_limited", 1);+ return Ok(Json(AIEndpointResponse {+ accepted_parts: vec![],+ }));+ }+ }+// Step 8b: Apply the in-process OverflowLimiter governor. The analytics// pipeline stamps overflow reasons inside `process_events`, but AI// bypasses that path, so we invoke the shared helper here to preserve@@ -556,7 +583,7 @@ fn build_kafka_event(// Create metadatalet metadata = ProcessedEventMetadata {- data_type: DataType::AnalyticsMain,+ data_type: DataType::AiEvents,session_id: None,computed_timestamp: Some(computed_timestamp),event_name: parsed.event_name,@@ -644,10 +671,8 @@ fn process_properties_part(async fn retrieve_multipart_parts(multipart: &mut Multipart<'_>,event_metadata: EventMetadata,+ max_event_bytes: u64,) -> Result<RetrievedMultipartParts, AiRejection> {- // Size limits- const MAX_COMBINED_SIZE: usize = 1024 * 1024 - 64 * 1024; // 1MB - 64KB = 960KB-let mut part_count = 0;let mut accepted_parts = Vec::new();let mut properties_json: Option<Value> = None;@@ -702,12 +727,15 @@ async fn retrieve_multipart_parts(}}- // Check combined size limit+ // The event and its properties are merged into one event downstream, so the+ // deployment's per-event ceiling applies to their sum. Rejecting here keeps+ // an oversized event off the producer, whose own cap would refuse it only+ // after the whole body had been read.let combined_size = event_size + properties_size;- if combined_size > MAX_COMBINED_SIZE {+ if exceeds_max_ai_event_bytes(combined_size, max_event_bytes) {return Err(AiRejection::EventAndPropertiesTooBig {size: combined_size,- max: MAX_COMBINED_SIZE,+ max: max_event_bytes as usize,});}diff --git a/rust/capture/src/api.rs b/rust/capture/src/api.rsindex fb4b6c46961c..171d2d0e9641 100644--- a/rust/capture/src/api.rs+++ b/rust/capture/src/api.rs@@ -70,6 +70,14 @@ pub enum CaptureError {RetryableSinkError,#[error("maximum event size exceeded: {0}")]EventTooBig(String),+ /// An AI-lane event over the deployment's per-event ceiling, raised by+ /// `process_events` before the sink. Separate from [`Self::EventTooBig`]+ /// because the two differ in what has already happened when they fire: the+ /// sink raises `EventTooBig` for one message after earlier events in the+ /// batch were enqueued, while this one refuses the whole request with+ /// nothing sent. Warning counts and drop metrics both depend on that.+ #[error("maximum AI event size exceeded: {0}")]+ AiEventTooBig(String),#[error("invalid event could not be processed")]NonRetryableSinkError,@@ -85,6 +93,9 @@ pub enum CaptureError {#[error("payload empty after filtering invalid event types")]EmptyPayloadFiltered,+ #[error("event {0} is not an AI event; send it to the analytics endpoint")]+ NonAiEventOnAiLane(String),+#[error("service unavailable: {0}")]ServiceUnavailable(String),@@ -122,11 +133,13 @@ impl CaptureError {CaptureError::TokenValidationError(_) => "invalid_token",CaptureError::RetryableSinkError => "retryable_sink",CaptureError::EventTooBig(_) => "oversize_event",+ CaptureError::AiEventTooBig(_) => "ai_event_too_big",CaptureError::NonRetryableSinkError => "non_retry_sink",CaptureError::BillingLimit => "billing_limit",CaptureError::RateLimited => "rate_limited",CaptureError::GlobalRateLimitExceeded() => "global_rate_limit",CaptureError::EmptyPayloadFiltered => "empty_filtered_payload",+ CaptureError::NonAiEventOnAiLane(_) => "non_ai_event_on_ai_lane",CaptureError::ServiceUnavailable(_) => "service_unavailable",CaptureError::BodyReadTimeout => "body_read_timeout",CaptureError::InternalError(_) => "internal_error",@@ -151,9 +164,12 @@ impl IntoResponse for CaptureError {| CaptureError::MissingWindowId| CaptureError::InvalidSessionId| CaptureError::EmptyPayloadFiltered+ | CaptureError::NonAiEventOnAiLane(_)| CaptureError::MissingSnapshotData => (StatusCode::BAD_REQUEST, self.to_string()),- CaptureError::EventTooBig(_) => (StatusCode::PAYLOAD_TOO_LARGE, self.to_string()),+ CaptureError::EventTooBig(_) | CaptureError::AiEventTooBig(_) => {+ (StatusCode::PAYLOAD_TOO_LARGE, self.to_string())+ }CaptureError::NoTokenError| CaptureError::MultipleTokensErrordiff --git a/rust/capture/src/config.rs b/rust/capture/src/config.rsindex 58bfde7fc275..18bf2642f117 100644--- a/rust/capture/src/config.rs+++ b/rust/capture/src/config.rs@@ -46,19 +46,6 @@ impl CaptureMode {pub fn requires_historical_migration(&self) -> bool {matches!(self, CaptureMode::Import)}-- /// Whether the analytics pipelines divert `$ai_*` events to the dedicated- /// AI topic (`CAPTURE_ANALYTICS_AI_EVENTS_TOPIC`). `Events` and `Import` do — the AI- /// lane is the only pipeline with AI processing (cost enrichment, the- /// ai_events double-write), so historical backfills must divert too or- /// their `$ai_*` events import incorrectly. `Ai` deployments don't: they- /// already produce to the AI lane as their main topic. Import deployments- /// keep their no-overflow guarantee in code: setup refuses to boot import- /// mode with the AI overflow valve- /// (`CAPTURE_ANALYTICS_AI_EVENTS_OVERFLOW_TOPIC`) set.- pub fn routes_ai_events(&self) -> bool {- matches!(self, CaptureMode::Events | CaptureMode::Import)- }}impl std::str::FromStr for CaptureMode {@@ -334,6 +321,44 @@ pub struct Config {#[envconfig(default = "26214400")] // 25MB in bytespub ai_max_sum_of_parts_bytes: usize,+ /// Largest single AI-lane event this deployment accepts. Measured on the+ /// serialized event body, except on v1, which measures the properties blob+ /// — see [`crate::v0_request::exceeds_max_ai_event_bytes`]. `0` disables+ /// the ceiling.+ ///+ /// Set it below what the deployment's broker accepts, leaving room for the+ /// `CapturedEvent` envelope and the JSON-escaping of `data`:+ /// `KAFKA_PRODUCER_MESSAGE_MAX_BYTES` bounds the produced message, not the+ /// event inside it. capture-analytics needs a smaller value than capture-ai+ /// because its AI topic is on MSK.+ ///+ /// What an over-ceiling event gets back differs by path, because each one+ /// keeps its own convention:+ ///+ /// * `/i/v0/ai/batch` and the diverted legacy path — 413, whole request+ /// refused, like every other oversize check there.+ /// * `/i/v1/analytics/events` — the one event is dropped and reported as+ /// `ai_event_too_big` in the 200 body; the rest of the batch publishes.+ /// * `/i/v0/ai` (multipart) — 413, the endpoint's pre-existing behavior.+ /// * `/i/v0/ai/otel` — the span is shed and the export still succeeds. A+ /// collector retries a rejected export, so refusing would stall every+ /// span behind one that can never fit. That loss is invisible in the+ /// response, so it raises a `MessageSizeTooLarge` ingestion warning.+ ///+ /// The legacy, v1, and OTEL paths count the loss under `ai_event_too_big`,+ /// on `capture_events_dropped_total` or `capture_v1_events_dropped`. The+ /// legacy path charges the whole batch, because the refusal loses every+ /// event in it, not just the offender. The multipart handler counts no+ /// drop at all: like every other error it raises, the refusal shows up+ /// only on `capture_error_by_stage_and_type`.+ /// Keep this under the deployment's `KAFKA_PRODUCER_MESSAGE_MAX_BYTES`.+ /// Above it the ceiling stops being a guard: capture reads the body, builds+ /// the event, and the producer refuses it anyway. A deployment that has not+ /// raised its producer cap wants a lower value than this default; the boot+ /// warning says so when the two are out of order.+ #[envconfig(default = "8388608")] // 8MiB+ pub ai_max_event_bytes: u64,+// HMAC-SHA256 key shared with the AI gateway. When set, $ai_generation events// carrying a valid PostHog-Ai-Gateway-* signature are stamped verified and// exempted from the llm_events quota limiter. Unset disables verification@@ -424,6 +449,31 @@ pub struct Config {pub capture_ingestion_warnings_kafka_hosts: String,#[envconfig(default = "false")]pub capture_ingestion_warnings_kafka_tls: bool,++ /// Per-token byte/second budget for the AI lane. `0` disables the limiter.+ ///+ /// The budget is enforced fleet-wide by the global rate limiter, over the+ /// shared `GLOBAL_RATE_LIMIT_WINDOW_INTERVAL_SECS` sliding window, so the+ /// cap a token actually sees is this value times the window length. Within+ /// a window the token may spend the whole budget at once.+ #[envconfig(default = "0")]+ pub ai_byte_limit_per_second: u64,++ /// CSV list of `token=bytesPerSecond` pairs raising specific tokens' budgets.+ /// Same unit as `ai_byte_limit_per_second`.+ pub ai_byte_limit_overrides_csv: Option<String>,++ /// When true, the AI byte limiter evaluates and reports but does not drop.+ /// Separate from `global_rate_limit_dry_run` so this rollout and the+ /// token+distinct_id limiter's can move independently.+ #[envconfig(default = "false")]+ pub ai_byte_limit_dry_run: bool,++ /// Max local cache entries for the AI byte limiter. Keyed per token, so this+ /// is bounded by the number of projects sending AI traffic — far smaller+ /// than the per-(token, distinct_id) limiter's key space.+ #[envconfig(default = "300000")]+ pub ai_byte_limit_local_cache_max_entries: u64,}#[derive(Envconfig, Clone)]@@ -472,12 +522,12 @@ pub struct KafkaConfig {pub kafka_replay_overflow_topic: String,#[envconfig(default = "events_plugin_ingestion_dlq")]pub kafka_dlq_topic: String,- /// Dedicated Kafka topic for `$ai_*` events (env: `CAPTURE_ANALYTICS_AI_EVENTS_TOPIC`).- /// On deployments whose capture mode routes AI events- /// (`CaptureMode::routes_ai_events`), both the v0 pipeline (via- /// `DataType::AiEvents`) and the v1 pipeline (via `Destination::AiEvents`)- /// divert `$ai_*` events here instead of the analytics main topic. Setup- /// also injects it into every v1 sink config.+ /// Dedicated Kafka topic for AI events (env: `CAPTURE_ANALYTICS_AI_EVENTS_TOPIC`).+ /// Both the v0 pipeline (via `DataType::AiEvents`) and the v1 pipeline+ /// (via `Destination::AiEvents`) divert AI events here instead of the+ /// analytics main topic, on every deployment that accepts them — including+ /// capture-ai, whose main topic used to double as the AI topic. Setup also+ /// injects it into every v1 sink config.#[envconfig(default = "events_plugin_ingestion_ai")]pub capture_analytics_ai_events_topic: String,/// Optional overflow topic for the AI lane (env: `CAPTURE_ANALYTICS_AI_EVENTS_OVERFLOW_TOPIC`).@@ -647,19 +697,4 @@ mod tests {);}}-- #[test]- fn capture_mode_ai_routing_policy() {- // Events and Import divert $ai_* events to the AI topic — only the AI- // lane has AI processing, so imports must divert too. Ai deployments- // already produce to the AI lane as their main topic.- assert!(CaptureMode::Events.routes_ai_events());- assert!(CaptureMode::Import.routes_ai_events());- for mode in [CaptureMode::Recordings, CaptureMode::Ai] {- assert!(- !mode.routes_ai_events(),- "{mode:?} must not route AI events"- );- }- }}diff --git a/rust/capture/src/event_restrictions/types.rs b/rust/capture/src/event_restrictions/types.rsindex a4849a00c1ed..25385d454184 100644--- a/rust/capture/src/event_restrictions/types.rs+++ b/rust/capture/src/event_restrictions/types.rs@@ -45,16 +45,26 @@ impl Pipeline {/// Pipelines a given capture deployment produces events to. The events/// deployment writes to `analytics` (normal events), `errortracking`/// (`$exception` events split off in `process_single_event`), and `ai`- /// (`$ai_*` events diverted by `CaptureMode::routes_ai_events`), so its- /// restriction service must serve restrictions for all three pipelines.- /// `Import` is an events deployment restricted to backfills, so it serves- /// the same three. Other deployments serve their single pipeline.+ /// (names on the `AI_EVENT_NAMES` allowlist), so its restriction service+ /// must serve restrictions for all three pipelines. `Import` is an events+ /// deployment restricted to backfills, so it serves the same three.+ ///+ /// `Ai` serves only `ai`. That deployment registers no analytics route,+ /// and `process_events` rejects a batch carrying anything off the AI lane,+ /// so no event there resolves to another pipeline. Both halves have to+ /// hold: serving fewer pipelines than a deployment can produce to leaves+ /// those lookups matching an unloaded slice, which returns an empty+ /// `RestrictionSet` — silently unrestricted.pub fn for_capture_mode(mode: CaptureMode) -> Vec<Pipeline> {match mode {CaptureMode::Events | CaptureMode::Import => {vec![Self::Analytics, Self::ErrorTracking, Self::Ai]}CaptureMode::Recordings => vec![Self::SessionRecordings],+ // capture-ai registers only the AI routes, and `process_events`+ // rejects a batch carrying anything off the AI lane, so no event+ // there ever resolves to another pipeline. Loading the analytics+ // and error-tracking slices would only cost memory.CaptureMode::Ai => vec![Self::Ai],}}@@ -389,7 +399,7 @@ mod tests {);// Import is an events deployment restricted to backfills, so it must// serve the identical pipeline set -- a backfill can carry $exception- // and $ai_* events too.+ // and AI events too.assert_eq!(Pipeline::for_capture_mode(CaptureMode::Import),Pipeline::for_capture_mode(CaptureMode::Events)@@ -398,6 +408,10 @@ mod tests {Pipeline::for_capture_mode(CaptureMode::Recordings),vec![Pipeline::SessionRecordings]);+ // Ai serves only the AI lane: its routes are AI-only and its batch path+ // rejects anything off the allowlist, so every event it processes+ // resolves to Pipeline::Ai. Widening this would load slices nothing+ // looks up; narrowing it below is only safe while both of those hold.assert_eq!(Pipeline::for_capture_mode(CaptureMode::Ai),vec![Pipeline::Ai]diff --git a/rust/capture/src/events/ai_byte_limit.rs b/rust/capture/src/events/ai_byte_limit.rsnew file mode 100644index 000000000000..91eab37a7a20--- /dev/null+++ b/rust/capture/src/events/ai_byte_limit.rs@@ -0,0 +1,285 @@+//! The AI lane's per-project byte budget. The lane is the whole gate: every+//! event on the `AI_EVENT_NAMES` allowlist is bound for the AI Kafka topic on+//! every deployment, stamped `DataType::AiEvents` in v0 and+//! `Destination::AiEvents` in v1. Import deployments are exempt — backfills+//! are never throttled, matching the other limiters — which setup enforces by+//! not building the limiter at all in import mode.+//!+//! The budget is per project token and fleet-wide: the shared global rate+//! limiter is charged an event's payload size instead of `1`, so a token's+//! bytes count against one window no matter which pod, which capture+//! deployment, or which pipeline ingests them.+//!+//! Every ingress onto the lane charges through [`charge_ai_bytes`] and acts on+//! the verdict in its own idiom, so no path is a way to spend bytes the others+//! are capped on:+//!+//! * the legacy batch path drops the event from the batch here in+//! [`drop_ai_byte_limited`],+//! * v1 marks it `EventResult::Drop` in+//! `v1::analytics::process::apply_ai_byte_limits`, which reports the reason+//! to the SDK in the 200 body,+//! * `/i/v0/ai` answers 200 with no accepted parts, the shape that handler+//! already uses for its other silent drops,+//! * `/i/v0/ai/otel` sheds the span through [`drop_ai_byte_limited`] and still+//! accepts the export, because a collector retries a rejected one.+//!+//! All four charge after event restrictions and after the per-event size+//! ceiling, so nothing that was never going to publish spends the project's+//! budget. None of them raises an ingestion warning: a rate drop is+//! ops-imposed, and capture surfaces those through billing and ops channels+//! rather than the customer-facing warnings table.+use std::sync::Arc;++use crate::global_rate_limiter::GlobalRateLimiter;+use crate::prometheus::report_dropped_events;+use crate::v0_request::{DataType, ProcessedEvent};++/// Flat allowance for the `CapturedEvent` envelope fields not in `data`.+const ENVELOPE_WEIGHT_BYTES: usize = 512;++/// Charge `payload_bytes` against `token`'s AI budget and report whether the+/// event is over it.+///+/// Events with an empty token are never charged: keying on `""` would pool+/// unrelated senders into one bucket. Over-budget events are still charged —+/// that sheds a flood, and the bytes crossed the wire whether or not we+/// forward them.+pub async fn charge_ai_bytes(+ limiter: &GlobalRateLimiter,+ token: &str,+ payload_bytes: usize,+) -> bool {+ if token.is_empty() {+ return false;+ }+ // Approximate wire size: the payload plus a flat allowance for the fixed+ // envelope fields and JSON-escaping. The budget is a coarse abuse guard,+ // not an exact byte accountant, so the two pipelines' slightly different+ // payload measures do not need reconciling.+ let weight = (payload_bytes + ENVELOPE_WEIGHT_BYTES) as u64;+ limiter.is_limited(token, weight).await.is_some()+}++pub async fn drop_ai_byte_limited(+ events: &mut Vec<ProcessedEvent>,+ limiter: Option<&Arc<GlobalRateLimiter>>,+) {+ let Some(limiter) = limiter else {+ return;+ };++ // `retain` is the natural fit but its predicate is synchronous and the+ // charge is not, so the batch is compacted by hand: the same read/write+ // walk `retain` performs internally, with the await hoisted into the loop.+ // Rebuilding into a second `Vec` would be the shorter spelling and costs a+ // batch-sized allocation plus a move of every survivor, paid whether or not+ // anything is over budget. Nothing moves here until the first drop, which+ // is the steady state: the budget sheds nothing for a project inside it.+ let mut write = 0usize;+ let mut dropped: u64 = 0;++ for read in 0..events.len() {+ let event = &events[read];+ let over_budget = event.metadata.data_type == DataType::AiEvents+ && charge_ai_bytes(limiter, &event.event.token, event.event.data.len()).await;+ if over_budget {+ dropped += 1;+ continue;+ }+ if write != read {+ events.swap(write, read);+ }+ write += 1;+ }++ // The tail past `write` holds the dropped events and the stale slots the+ // swaps left behind; truncating drops them. No-op when nothing was shed.+ events.truncate(write);++ if dropped > 0 {+ report_dropped_events("ai_byte_rate_limited", dropped);+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::utils::uuid_v7_from_datetime;+ use crate::v0_request::{DataType, ProcessedEvent, ProcessedEventMetadata};+ use common_types::CapturedEvent;+ use std::sync::Arc;++ fn event_of(data_type: DataType, token: &str, data: &str) -> ProcessedEvent {+ let timestamp = chrono::Utc::now();+ let event = CapturedEvent {+ uuid: uuid_v7_from_datetime(timestamp),+ distinct_id: "u".to_string(),+ session_id: None,+ ip: "127.0.0.1".to_string(),+ data: data.to_string(),+ now: "2026-04-20T00:00:00Z".to_string(),+ sent_at: None,+ token: token.to_string(),+ event: "test".to_string(),+ timestamp,+ is_cookieless_mode: false,+ historical_migration: false,+ };+ let metadata = ProcessedEventMetadata {+ data_type,+ session_id: None,+ computed_timestamp: None,+ event_name: "test".to_string(),+ force_overflow: false,+ skip_person_processing: false,+ redirect_to_dlq: false,+ redirect_to_topic: None,+ skip_heatmap_processing: false,+ overflow_reason: None,+ distinct_id_truncated_from: None,+ };+ ProcessedEvent { event, metadata }+ }++ /// A budget of `bytes` for every token, charged the same weights the+ /// production call site charges, with strict accounting: an event drops as+ /// soon as the running total crosses the budget.+ fn limiter(bytes: u64) -> Arc<GlobalRateLimiter> {+ Arc::new(GlobalRateLimiter::mock_budget(bytes))+ }++ /// One enveloped event of this size weighs ~517 B, so a 1000-byte budget+ /// admits the first and rejects the second.+ fn small_ai_event(token: &str) -> ProcessedEvent {+ event_of(DataType::AiEvents, token, &"x".repeat(5))+ }++ #[tokio::test]+ async fn none_limiter_is_a_no_op() {+ let mut events = vec![event_of(DataType::AiEvents, "t", "xxxxxxxxxx")];+ drop_ai_byte_limited(&mut events, None).await;+ assert_eq!(events.len(), 1);+ }++ #[tokio::test]+ async fn under_budget_ai_events_are_kept() {+ let l = limiter(1_000_000);+ let mut events = vec![small_ai_event("t"), small_ai_event("t")];+ drop_ai_byte_limited(&mut events, Some(&l)).await;+ assert_eq!(events.len(), 2);+ }++ #[tokio::test]+ async fn over_budget_ai_events_are_dropped() {+ let l = limiter(1_000);+ let mut events = vec![small_ai_event("t"), small_ai_event("t")];+ drop_ai_byte_limited(&mut events, Some(&l)).await;+ assert_eq!(events.len(), 1, "the over-budget AI event must be dropped");+ }++ /// The real limiter reads a cache miss as no prior data and fails open, so+ /// a token's first event is admitted however far over budget it is. That+ /// recurs on every moka eviction and every new pod, which is what makes it+ /// worth pinning rather than assuming: under a sustained flood it costs one+ /// event per pod per window.+ #[tokio::test]+ async fn a_cold_key_is_admitted_however_far_over_budget_it_is() {+ let l = Arc::new(GlobalRateLimiter::mock_budget_admitting_cold_keys(1));+ let mut events = vec![small_ai_event("t"), small_ai_event("t")];+ drop_ai_byte_limited(&mut events, Some(&l)).await;+ assert_eq!(+ events.len(),+ 1,+ "the cold key's first event is admitted; the second is not"+ );+ }++ #[tokio::test]+ async fn non_ai_lanes_are_never_dropped_by_this_helper() {+ let l = limiter(1);+ let mut events = vec![+ event_of(DataType::AnalyticsMain, "t", &"x".repeat(40)),+ event_of(DataType::AnalyticsMain, "t", &"x".repeat(40)),+ ];+ drop_ai_byte_limited(&mut events, Some(&l)).await;+ assert_eq!(events.len(), 2, "AnalyticsMain must not be touched");+ }++ #[tokio::test]+ async fn tokenless_events_are_kept() {+ // An empty token is not a budget: keying on it would pool unrelated+ // senders into one bucket.+ let l = limiter(1);+ let mut events = vec![+ event_of(DataType::AiEvents, "", &"x".repeat(40)),+ event_of(DataType::AiEvents, "", &"x".repeat(40)),+ ];+ drop_ai_byte_limited(&mut events, Some(&l)).await;+ assert_eq!(events.len(), 2);+ }++ #[tokio::test]+ async fn the_budget_is_charged_in_bytes_not_events() {+ // Three events, each ~517 B, against a 1000-byte budget: an+ // event-counting limiter of the same size would admit all three.+ let l = limiter(1_000);+ let mut events = vec![+ small_ai_event("t"),+ small_ai_event("t"),+ small_ai_event("t"),+ ];+ drop_ai_byte_limited(&mut events, Some(&l)).await;+ assert_eq!(events.len(), 1);+ }++ #[tokio::test]+ async fn each_token_draws_on_its_own_budget() {+ // tok_a exhausts its budget; tok_b's events are unaffected.+ let l = limiter(1_000);+ let mut events = vec![+ small_ai_event("tok_a"),+ small_ai_event("tok_a"),+ small_ai_event("tok_b"),+ small_ai_event("tok_b"),+ ];+ drop_ai_byte_limited(&mut events, Some(&l)).await;+ assert_eq!(events.len(), 2);+ }++ /// Survivors keep their submitted order. The interleaving is the point: a+ /// kept event *after* a dropped one is the only case where the in-place+ /// compaction moves anything, so a walk that reordered the batch — a+ /// `swap_remove`, say — would show up here and nowhere else.+ #[tokio::test]+ async fn survivors_keep_their_order_across_drops() {+ // Equal-length payloads, so each AI event weighs the same 517 B and+ // only position decides who survives.+ let l = limiter(1_000);+ let mut events = vec![+ event_of(DataType::AiEvents, "t", "aaaaa"), // first: admitted+ event_of(DataType::AiEvents, "t", "bbbbb"), // over budget+ event_of(DataType::AnalyticsMain, "t", "ccccc"), // never charged+ event_of(DataType::AiEvents, "t", "ddddd"), // over budget+ event_of(DataType::AnalyticsMain, "t", "eeeee"), // never charged+ ];+ drop_ai_byte_limited(&mut events, Some(&l)).await;+ let kept: Vec<&str> = events.iter().map(|e| e.event.data.as_str()).collect();+ assert_eq!(kept, ["aaaaa", "ccccc", "eeeee"]);+ }++ #[tokio::test]+ async fn mixed_batch_drops_only_over_budget_ai_events() {+ let l = limiter(1_000);+ let mut events = vec![+ small_ai_event("t"), // first: admitted+ event_of(DataType::AnalyticsMain, "t", &"x".repeat(99)), // untouched+ small_ai_event("t"), // exceeds remaining+ ];+ drop_ai_byte_limited(&mut events, Some(&l)).await;+ assert_eq!(events.len(), 2);+ assert!(events+ .iter()+ .any(|e| e.metadata.data_type == DataType::AnalyticsMain));+ }+}diff --git a/rust/capture/src/events/analytics.rs b/rust/capture/src/events/analytics.rsindex ea25be9926c2..b53754aa1853 100644--- a/rust/capture/src/events/analytics.rs+++ b/rust/capture/src/events/analytics.rs@@ -23,7 +23,7 @@ use crate::{api::CaptureError,debug_or_info,event_restrictions::{EventContext as RestrictionEventContext, EventRestrictionService},- events::overflow_stamping::stamp_overflow_reason,+ events::{ai_byte_limit::drop_ai_byte_limited, overflow_stamping::stamp_overflow_reason},global_rate_limiter::{GlobalRateLimitKey, GlobalRateLimiter},ingestion_warnings::{emit_distinct_id_truncated_warning, emit_rate_limit_warning,@@ -33,7 +33,8 @@ use crate::{router, sinks,utils::uuid_v7_from_datetime,v0_request::{- DataType, OverflowReason, ProcessedEvent, ProcessedEventMetadata, ProcessingContext,+ exceeds_max_ai_event_bytes, DataType, OverflowReason, ProcessedEvent,+ ProcessedEventMetadata, ProcessingContext,},};@@ -82,9 +83,6 @@ fn create_heatmap_redirect(historical_cfg: router::HistoricalConfig,context: &ProcessingContext,) -> Result<Option<ProcessedEvent>, CaptureError> {- // The redirect is always a `$$heatmap` event, so AI routing can never- // apply to it; hardcode the flag off instead of threading it through.- let route_ai_events = false;let Some(distinct_id) = event.extract_distinct_id() else {return Ok(None);};@@ -114,19 +112,14 @@ fn create_heatmap_redirect(set_once: None,};- process_single_event(&heatmap_event, historical_cfg, route_ai_events, context).map(Some)+ process_single_event(&heatmap_event, historical_cfg, context).map(Some)}/// Process a single analytics event from RawEvent to ProcessedEvent.-///-/// `route_ai_events` is the deployment's `CaptureMode::routes_ai_events` (see-/// `process_events`); when set, `$ai_*` events classify as-/// `DataType::AiEvents` instead of the analytics main/historical lanes.#[instrument(skip_all, fields(event_name, request_id))]pub fn process_single_event(event: &RawEvent,historical_cfg: router::HistoricalConfig,- route_ai_events: bool,context: &ProcessingContext,) -> Result<ProcessedEvent, CaptureError> {if event.event.is_empty() {@@ -136,8 +129,7 @@ pub fn process_single_event(Span::current().record("is_mirror_deploy", context.is_mirror_deploy);Span::current().record("request_id", &context.request_id);- let data_type =- DataType::from_event_name(&event.event, context.historical_migration, route_ai_events);+ let data_type = DataType::from_event_name(&event.event, context.historical_migration);// Redact the IP address of internally-generated events when tagged as suchlet resolved_ip = if event.properties.contains_key("capture_internal") {@@ -229,11 +221,11 @@ pub fn process_single_event(/// Process a batch of analytics events.///-/// All routing policy lives here: token dropping, `$ai_*` lane assignment-/// (per `CaptureMode::routes_ai_events`, resolved into `DataType::AiEvents`-/// at classification time), event restrictions, global-/// rate limiting (per `token:distinct_id`), historical rerouting, and-/// per-key overflow rerouting via [`OverflowLimiter`]. Overflow stamping+/// All routing policy lives here: token dropping, AI lane assignment+/// (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@@ -254,6 +246,7 @@ pub async fn process_events(ingestion_warning_emitter: Option<Arc<dyn WarningEmitter>>,events: Vec<RawEvent>,context: &ProcessingContext,+ ai_byte_rate_limiter: Option<Arc<GlobalRateLimiter>>,) -> Result<(), CaptureError> {// The whole request fails on the first hard error, so the abort warning// charges the full batch, matching what the endpoint's@@ -274,6 +267,7 @@ pub async fn process_events(ingestion_warning_emitter,events,context,+ ai_byte_rate_limiter,).await;@@ -295,6 +289,7 @@ async fn process_events_inner(ingestion_warning_emitter: Option<Arc<dyn WarningEmitter>>,events: Vec<RawEvent>,context: &ProcessingContext,+ ai_byte_rate_limiter: Option<Arc<GlobalRateLimiter>>,) -> Result<(), CaptureError> {let chatty_debug_enabled = context.chatty_debug_enabled;@@ -320,12 +315,6 @@ async fn process_events_inner(return Ok(());}- // Whether `$ai_*` events divert to the dedicated AI topic is a deployment- // property, mirroring v1's `process_batch`. The flag feeds- // `DataType::from_event_name` via `process_single_event`; the kafka sink- // maps the resulting `DataType::AiEvents` to `CAPTURE_ANALYTICS_AI_EVENTS_TOPIC`.- let route_ai_events = context.capture_mode.routes_ai_events();-// Build the processed batch one raw event at a time so we can split a// heatmap-carrying event into a stripped original + a `$$heatmap`// redirect *before* serialization happens inside `process_single_event`.@@ -343,38 +332,23 @@ async fn process_events_inner(.retain(|key, _| !key.starts_with(crate::gateway_provenance::GATEWAY_PREFIX));}if raw.event == "$$heatmap" || !has_heatmap_data(&raw) {- events.push(process_single_event(- &raw,- historical_cfg,- route_ai_events,- context,- )?);+ events.push(process_single_event(&raw, historical_cfg, context)?);continue;}let mut redirect = match create_heatmap_redirect(&raw, historical_cfg, context) {Ok(Some(redirect)) => redirect,Ok(None) => {- events.push(process_single_event(- &raw,- historical_cfg,- route_ai_events,- context,- )?);+ events.push(process_single_event(&raw, historical_cfg, context)?);continue;}Err(err) => {error!("failed to create heatmap redirect: {err:#}");- events.push(process_single_event(- &raw,- historical_cfg,- route_ai_events,- context,- )?);+ events.push(process_single_event(&raw, historical_cfg, context)?);continue;}};raw.properties.remove("$heatmap_data");- let mut processed = process_single_event(&raw, historical_cfg, route_ai_events, context)?;+ let mut processed = process_single_event(&raw, historical_cfg, context)?;processed.metadata.skip_heatmap_processing = true;events.push(processed);counter!("capture_heatmap_redirects_created").increment(1);@@ -387,6 +361,57 @@ async fn process_events_inner(debug_or_info!(chatty_debug_enabled, context=?context, event_count=?events.len(), "created ProcessedEvents batch");+ // capture-ai serves only the AI paths and loads only AI restrictions (see+ // `Pipeline::for_capture_mode`), so an event on any other lane would run+ // ungoverned there. Reject the batch rather than dropping the offender: a+ // client sending non-AI events to an AI endpoint is misconfigured, and a+ // silent drop would hide that until someone went looking for the data. The+ // abort path emits an `invalid_ai_event` ingestion warning alongside the+ // 400, so the project owner sees it too.+ //+ // Lane membership is the `AI_EVENT_NAMES` allowlist, not an `$ai_` prefix,+ // so a prefixed-but-unlisted name is rejected here too — the Node AI+ // pipeline would DLQ it anyway.+ if context.capture_mode == crate::config::CaptureMode::Ai {+ if let Some(offender) = events+ .iter()+ .find(|e| e.metadata.data_type != DataType::AiEvents)+ {+ return Err(CaptureError::NonAiEventOnAiLane(+ offender.metadata.event_name.clone(),+ ));+ }+ }++ // Reject an AI-lane event past the deployment's ceiling before it can reach+ // the sink, where the producer's own cap would refuse it anyway — after+ // capture had read and processed the whole request. The whole request is+ // refused, matching how every other oversize check on this path behaves.+ //+ // The drop isn't counted here. The abort reaches the endpoint, which charges+ // the whole batch under this error's own `ai_event_too_big` tag; counting+ // locally too would report one more drop than the batch held, and split one+ // rejection across two `cause` labels.+ //+ // The uuid says which event to fix, since a batch can carry several of the+ // same name. It is only a handle for clients that send their own; the rest+ // get the one `process_single_event` minted, which identifies nothing they+ // can look up. The non-AI-event rejection above deliberately omits it: its+ // offender may be the `$$heatmap` event capture itself synthesized, and+ // naming a uuid the client never issued would misdirect them.+ if let Some(offender) = events.iter().find(|e| {+ e.metadata.data_type == DataType::AiEvents+ && exceeds_max_ai_event_bytes(e.event.data.len(), context.ai_max_event_bytes)+ }) {+ return Err(CaptureError::AiEventTooBig(format!(+ "AI event {} (uuid {}) is {} bytes, over the {}-byte limit",+ offender.metadata.event_name,+ offender.event.uuid,+ offender.event.data.len(),+ context.ai_max_event_bytes+ )));+ }+events.retain(|e| {if dropper.should_drop(&e.event.token, &e.event.distinct_id) {report_dropped_events("token_dropper", 1);@@ -452,6 +477,13 @@ async fn process_events_inner(debug_or_info!(chatty_debug_enabled, context=?context, event_count=?events.len(), "filtered by event_restrictions");}+ // Charge the AI lane's per-project byte budget. This runs after event+ // restrictions so an event a `DropEvent` discards never spends the+ // project's budget on a send that was never going to happen. Events that+ // survive to here are charged whether or not the budget then sheds them:+ // those bytes crossed the wire either way.+ drop_ai_byte_limited(&mut events, ai_byte_rate_limiter.as_ref()).await;+// Per-(token, distinct_id) global rate limiting: skip person processing for// hot distinct_ids and reroute AnalyticsMain events to overflow. Import mode// opts out entirely — historical backfills must never be throttled — so the@@ -652,6 +684,7 @@ mod tests {historical_migration: false,chatty_debug_enabled: false,capture_mode: crate::config::CaptureMode::Events,+ ai_max_event_bytes: 0,sdk_attribution: crate::ingestion_warnings::SdkAttribution::default(),}}@@ -699,6 +732,7 @@ mod tests {overflow_limiter: Option<Arc<OverflowLimiter>>,ai_events_overflow_limiter: Option<Arc<OverflowLimiter>>,ingestion_warning_emitter: Option<Arc<dyn WarningEmitter>>,+ ai_byte_rate_limiter: Option<Arc<GlobalRateLimiter>>,}impl Default for PipelineOptions {@@ -711,6 +745,7 @@ mod tests {overflow_limiter: None,ai_events_overflow_limiter: None,ingestion_warning_emitter: None,+ ai_byte_rate_limiter: None,}}}@@ -732,6 +767,7 @@ mod tests {options.ingestion_warning_emitter,events,context,+ options.ai_byte_rate_limiter,).await}@@ -758,13 +794,9 @@ mod tests {token: Some("test_token".to_string()),};- let processed = process_single_event(- &event,- router::HistoricalConfig::new(false, 1),- false,- &context,- )- .unwrap();+ let processed =+ process_single_event(&event, router::HistoricalConfig::new(false, 1), &context)+ .unwrap();let expected_millis = processed.metadata@@ -799,13 +831,9 @@ mod tests {token: Some("test_token".to_string()),};- let processed = process_single_event(- &event,- router::HistoricalConfig::new(false, 1),- false,- &context,- )- .unwrap();+ let processed =+ process_single_event(&event, router::HistoricalConfig::new(false, 1), &context)+ .unwrap();// The event keeps its pre-epoch timestamp, but the uuid floors to the epoch rather than wrapping to garbage.assert!(@@ -827,12 +855,8 @@ mod tests {let context = create_test_context(now, None);let event = create_test_event(Some("2023-01-01T11:00:00Z".to_string()), None, None);- let result = process_single_event(- &event,- router::HistoricalConfig::new(false, 1),- false,- &context,- );+ let result =+ process_single_event(&event, router::HistoricalConfig::new(false, 1), &context);assert!(result.is_ok());let processed = result.unwrap();@@ -857,12 +881,8 @@ mod tests {let event = create_test_event(Some("2023-01-01T11:59:55Z".to_string()), None, None);- let result = process_single_event(- &event,- router::HistoricalConfig::new(false, 1),- false,- &context,- );+ let result =+ process_single_event(&event, router::HistoricalConfig::new(false, 1), &context);assert!(result.is_ok());let processed = result.unwrap();@@ -885,12 +905,8 @@ mod tests {let event = create_test_event(Some("2023-01-01T11:00:00Z".to_string()), None, Some(true));- let result = process_single_event(- &event,- router::HistoricalConfig::new(false, 1),- false,- &context,- );+ let result =+ process_single_event(&event, router::HistoricalConfig::new(false, 1), &context);assert!(result.is_ok());let processed = result.unwrap();@@ -912,12 +928,8 @@ mod tests {let event = create_test_event(Some("2023-01-01T11:00:00Z".to_string()), None, None);- let result = process_single_event(- &event,- router::HistoricalConfig::new(false, 1),- false,- &context,- );+ let result =+ process_single_event(&event, router::HistoricalConfig::new(false, 1), &context);assert!(result.is_ok());let processed = result.unwrap();@@ -937,12 +949,8 @@ mod tests {let event = create_test_event(Some("2023-01-01T11:00:00Z".to_string()), None, None);- let result = process_single_event(- &event,- router::HistoricalConfig::new(false, 1),- false,- &context,- );+ let result =+ process_single_event(&event, router::HistoricalConfig::new(false, 1), &context);assert!(result.is_ok());let processed = result.unwrap();@@ -1319,8 +1327,8 @@ mod tests {);}- /// The `$ai_*` lane assignment holds across capture modes: `Events` and- /// `Import` both divert every `$ai_*` event (only the AI lane has AI+ /// The AI lane assignment holds across capture modes: `Events` and+ /// `Import` both divert every allowlisted AI event (only the AI lane has AI/// processing, so imports must divert too), winning over historical./// Non-AI events stay on their normal route in every mode. The topic/// itself is resolved in the kafka sink from `DataType::AiEvents`, not@@ -1408,7 +1416,474 @@ mod tests {assert_eq!(pageview.metadata.redirect_to_topic, None);}- /// A diverted `$ai_*` event is governed by ai-scoped restrictions (the+ /// End-to-end: `process_events` drops the over-budget `$ai_generation` and keeps the small one.+ #[tokio::test]+ async fn ai_events_over_byte_budget_are_dropped_end_to_end() {+ use crate::sinks::kafka::{test_topics, KafkaSinkBase};+ use crate::sinks::producer::MockKafkaProducer;++ // 800-byte budget: the enveloped small event (~672 B) fits, and the+ // large one takes the running total past it.+ let limiter = Some(Arc::new(GlobalRateLimiter::mock_budget(800)));++ let producer = MockKafkaProducer::new();+ let sink = Arc::new(KafkaSinkBase::with_producer(+ producer.clone(),+ test_topics(),+ ));++ let now = DateTime::parse_from_rfc3339("2023-01-01T12:00:00Z")+ .unwrap()+ .with_timezone(&Utc);+ let context = create_test_context(now, None);++ let small_event = create_test_event_with_name(+ "$ai_generation",+ Some("2023-01-01T11:00:00Z".to_string()),+ None,+ None,+ );+ let mut oversized_event = create_test_event_with_name(+ "$ai_generation",+ Some("2023-01-01T11:00:00Z".to_string()),+ None,+ None,+ );+ oversized_event+ .properties+ .insert("$ai_input".to_string(), json!("x".repeat(500)));++ process_events(+ sink,+ Arc::new(TokenDropper::default()),+ None,+ router::HistoricalConfig::new(false, 1),+ None,+ None,+ None,+ None,+ vec![small_event, oversized_event],+ &context,+ limiter,+ )+ .await+ .expect("process_events must accept the batch even though one event is dropped");++ let records = producer.get_records();+ assert_eq!(+ records.len(),+ 1,+ "only the under-budget AI event must reach the sink"+ );+ let topics = test_topics();+ let ai_topic = topics.topic_for(&crate::sinks::registry::Output::AiMain);+ assert_eq!(+ records[0].topic, ai_topic,+ "the surviving record must be on the AI lane"+ );+ }++ /// An AI event past the deployment's ceiling refuses the whole request, so+ /// no part of it reaches the sink. The legacy path already answers 413 for+ /// every other oversize condition, and the producer would refuse this event+ /// anyway once the request had been read in full.+ #[tokio::test]+ async fn oversize_ai_events_refuse_the_request_end_to_end() {+ let now = DateTime::parse_from_rfc3339("2023-01-01T12:00:00Z")+ .unwrap()+ .with_timezone(&Utc);+ let mut context = create_test_context(now, None);+ context.ai_max_event_bytes = 700;++ let sink = Arc::new(MockSink::new());+ let mut oversized = create_test_event_with_name(+ "$ai_generation",+ Some("2023-01-01T11:00:00Z".to_string()),+ None,+ None,+ );+ oversized+ .properties+ .insert("$ai_input".to_string(), json!("x".repeat(800)));+ // A client-supplied uuid: the case where the uuid in the message is a+ // handle the sender can match against its own outbox.+ let offender_uuid = Uuid::parse_str("018f2c6e-0000-7000-8000-00000000beef").unwrap();+ oversized.uuid = Some(offender_uuid);++ let err = run_pipeline(+ sink.clone(),+ vec![+ create_test_event_with_name(+ "$ai_generation",+ Some("2023-01-01T11:00:00Z".to_string()),+ None,+ None,+ ),+ oversized,+ ],+ &context,+ PipelineOptions::default(),+ )+ .await+ .expect_err("an oversize AI event must refuse the batch");++ assert!(matches!(err, CaptureError::AiEventTooBig(_)), "got {err:?}");+ // The offender's uuid, not the batch's first event: a batch can carry+ // several events of one name, so the name alone doesn't say which to fix.+ assert!(+ err.to_string().contains(&offender_uuid.to_string()),+ "the message must name the offending event's uuid, got {err}"+ );+ assert!(+ sink.get_events().is_empty(),+ "no event may reach the sink once the request is refused"+ );+ }++ /// The ceiling governs the AI lane only: an analytics event of the same+ /// size passes, so a deployment sized for its AI topic's broker does not+ /// start refusing ordinary analytics traffic.+ #[tokio::test]+ async fn the_ai_size_ceiling_leaves_analytics_events_alone() {+ let now = DateTime::parse_from_rfc3339("2023-01-01T12:00:00Z")+ .unwrap()+ .with_timezone(&Utc);+ let mut context = create_test_context(now, None);+ context.ai_max_event_bytes = 700;++ let sink = Arc::new(MockSink::new());+ let mut oversized = create_test_event_with_name(+ "$pageview",+ Some("2023-01-01T11:00:00Z".to_string()),+ None,+ None,+ );+ oversized+ .properties+ .insert("big".to_string(), json!("x".repeat(800)));++ run_pipeline(+ sink.clone(),+ vec![oversized],+ &context,+ PipelineOptions::default(),+ )+ .await+ .expect("an oversize analytics event must not be refused");++ assert_eq!(sink.get_events().len(), 1);+ }++ /// A `DropEvent` restriction discards its event before the byte budget is+ /// charged, so the budget still has room for the events that survive it.+ /// Charging first would let a restricted event shed a legitimate one+ /// behind it.+ #[tokio::test]+ async fn restriction_dropped_ai_events_do_not_spend_the_byte_budget() {+ // 800-byte budget against two ~670 B enveloped events: whichever is+ // charged first is admitted, and a second charge exceeds the budget.+ let limiter = Some(Arc::new(GlobalRateLimiter::mock_budget(800)));++ let now = DateTime::parse_from_rfc3339("2023-01-01T12:00:00Z")+ .unwrap()+ .with_timezone(&Utc);+ let context = create_test_context(now, None);++ let service = EventRestrictionService::new(+ vec![Pipeline::Analytics, Pipeline::Ai],+ Duration::from_secs(300),+ );+ let mut manager = RestrictionManager::new();+ let mut filters = RestrictionFilters::default();+ filters.event_names.insert("$ai_generation".to_string());+ manager.insert_restrictions(+ Pipeline::Ai,+ "test_token",+ vec![Restriction {+ restriction_type: RestrictionType::DropEvent,+ scope: RestrictionScope::Filtered(filters),+ args: None,+ }],+ );+ service.update(manager).await;++ let sink = Arc::new(MockSink::new());+ let events = vec![+ create_test_event_with_name(+ "$ai_generation",+ Some("2023-01-01T11:00:00Z".to_string()),+ None,+ None,+ ),+ create_test_event_with_name(+ "$ai_span",+ Some("2023-01-01T11:00:00Z".to_string()),+ None,+ None,+ ),+ ];++ run_pipeline(+ sink.clone(),+ events,+ &context,+ PipelineOptions {+ restriction_service: Some(service),+ ai_byte_rate_limiter: limiter,+ ..Default::default()+ },+ )+ .await+ .unwrap();++ let captured = sink.get_events();+ assert_eq!(+ captured.len(),+ 1,+ "the restricted event must not spend budget the surviving event needs"+ );+ assert_eq!(captured[0].event.event, "$ai_span");+ }++ /// capture-ai loads only AI restrictions, so anything off the AI lane must+ /// not reach the pipeline there. Each case sends a two-event batch whose+ /// second event is the one under test.+ struct AiLaneGateCase {+ second_event: &'static str,+ rejected: bool,+ }++ #[rstest]+ #[case::analytics_event_is_rejected(AiLaneGateCase {+ second_event: "$pageview",+ rejected: true,+ })]+ // Lane membership is the AI_EVENT_NAMES allowlist, not an `$ai_` prefix.+ // A prefixed-but-unlisted name resolves to AnalyticsMain, so it must be+ // rejected too -- the Node AI pipeline would DLQ it downstream anyway.+ #[case::prefixed_but_unlisted_name_is_rejected(AiLaneGateCase {+ second_event: "$ai_call",+ rejected: true,+ })]+ #[case::exception_is_rejected(AiLaneGateCase {+ second_event: "$exception",+ rejected: true,+ })]+ #[case::second_allowlisted_event_passes(AiLaneGateCase {+ second_event: "$ai_span",+ rejected: false,+ })]+ #[tokio::test]+ async fn ai_mode_rejects_a_batch_carrying_anything_off_the_ai_lane(+ #[case] case: AiLaneGateCase,+ ) {+ let now = DateTime::parse_from_rfc3339("2023-01-01T12:00:00Z")+ .unwrap()+ .with_timezone(&Utc);+ let mut context = create_test_context(now, None);+ context.capture_mode = crate::config::CaptureMode::Ai;++ let events = vec![+ create_test_event_with_name("$ai_generation", None, None, None),+ create_test_event_with_name(case.second_event, None, None, None),+ ];++ let sink = Arc::new(MockSink::new());+ let collector = Arc::new(CollectingEmitter::new());+ let result = run_pipeline(+ sink.clone(),+ events,+ &context,+ PipelineOptions {+ ingestion_warning_emitter: Some(collector.clone()),+ ..Default::default()+ },+ )+ .await;++ if !case.rejected {+ result.expect("an all-AI batch must be accepted");+ assert_eq!(sink.get_events().len(), 2);+ assert!(collector.emitted().is_empty());+ return;+ }++ let err = result.expect_err("the batch must be rejected");+ assert!(+ matches!(&err, CaptureError::NonAiEventOnAiLane(name) if name == case.second_event),+ "the error must name the offending event, got {err:?}"+ );+ // Rejecting the request means the whole batch is refused, including the+ // valid AI event ahead of the offender.+ assert!(sink.get_events().is_empty());++ // The 400 reaches the caller; the warning reaches the project owner.+ let emitted = collector.emitted();+ assert_eq!(emitted.len(), 1);+ assert_eq!(emitted[0].warning, WarningType::InvalidAiEvent);+ }++ /// The gate is scoped to capture-ai. On capture-analytics the same mixed+ /// batch is ordinary traffic: both events are accepted, each on its lane.+ #[tokio::test]+ async fn events_mode_accepts_a_batch_the_ai_lane_would_reject() {+ let now = DateTime::parse_from_rfc3339("2023-01-01T12:00:00Z")+ .unwrap()+ .with_timezone(&Utc);+ let context = create_test_context(now, None);++ let events = vec![+ create_test_event_with_name("$ai_generation", None, None, None),+ create_test_event_with_name("$pageview", None, None, None),+ ];++ let sink = Arc::new(MockSink::new());+ run_pipeline(sink.clone(), events, &context, PipelineOptions::default())+ .await+ .expect("capture-analytics must accept a mixed batch");++ let captured = sink.get_events();+ assert_eq!(captured.len(), 2);+ assert_eq!(+ captured+ .iter()+ .filter(|e| e.metadata.data_type == DataType::AiEvents)+ .count(),+ 1+ );+ }++ /// Capture mode no longer changes which lane an AI event lands on: under `Ai`+ /// it diverts to `AiEvents` and the AI topic, exactly as under `Events`.+ #[tokio::test]+ async fn ai_mode_routes_ai_events_to_the_ai_lane_end_to_end() {+ use crate::sinks::kafka::{test_topics, KafkaSinkBase};+ use crate::sinks::producer::MockKafkaProducer;++ // 800-byte budget: the small event fits, the large one takes the+ // running total past it.+ let limiter = Some(Arc::new(GlobalRateLimiter::mock_budget(800)));++ let producer = MockKafkaProducer::new();+ let sink = Arc::new(KafkaSinkBase::with_producer(+ producer.clone(),+ test_topics(),+ ));++ let now = DateTime::parse_from_rfc3339("2023-01-01T12:00:00Z")+ .unwrap()+ .with_timezone(&Utc);+ let mut context = create_test_context(now, None);+ context.capture_mode = crate::config::CaptureMode::Ai;++ let small_event = create_test_event_with_name(+ "$ai_generation",+ Some("2023-01-01T11:00:00Z".to_string()),+ None,+ None,+ );+ let mut oversized_event = create_test_event_with_name(+ "$ai_generation",+ Some("2023-01-01T11:00:00Z".to_string()),+ None,+ None,+ );+ oversized_event+ .properties+ .insert("$ai_input".to_string(), json!("x".repeat(500)));++ process_events(+ sink,+ Arc::new(TokenDropper::default()),+ None,+ router::HistoricalConfig::new(false, 1),+ None,+ None,+ None,+ None,+ vec![small_event, oversized_event],+ &context,+ limiter,+ )+ .await+ .expect("process_events must accept the batch even though one event is dropped");++ let records = producer.get_records();+ assert_eq!(+ records.len(),+ 1,+ "only the under-budget event must reach the sink under Ai mode"+ );+ let topics = test_topics();+ let ai_topic = topics.topic_for(&crate::sinks::registry::Output::AiMain);+ assert_eq!(+ records[0].topic, ai_topic,+ "an allowlisted AI event diverts to the AI lane under Ai mode too"+ );+ }++ /// Under `Events` mode, only the diverted `AiEvents` lane is limited:+ /// AI traffic past the budget drops while same-sized `$pageview`s stay+ /// untouched however far over that budget the token already is.+ #[tokio::test]+ async fn events_mode_leaves_analytics_main_untouched_end_to_end() {+ let limiter = Some(Arc::new(GlobalRateLimiter::mock_budget(300)));++ let sink = Arc::new(MockSink::new());++ let now = DateTime::parse_from_rfc3339("2023-01-01T12:00:00Z")+ .unwrap()+ .with_timezone(&Utc);+ let context = create_test_context(now, None);++ let oversized_ai_event = || {+ let mut event = create_test_event_with_name(+ "$ai_generation",+ Some("2023-01-01T11:00:00Z".to_string()),+ None,+ None,+ );+ event+ .properties+ .insert("$ai_input".to_string(), json!("x".repeat(500)));+ event+ };+ let mut oversized_pageview = create_test_event_with_name(+ "$pageview",+ Some("2023-01-01T11:00:00Z".to_string()),+ None,+ None,+ );+ oversized_pageview+ .properties+ .insert("$current_url".to_string(), json!("x".repeat(500)));++ process_events(+ sink.clone(),+ Arc::new(TokenDropper::default()),+ None,+ router::HistoricalConfig::new(false, 1),+ None,+ None,+ None,+ None,+ vec![oversized_ai_event(), oversized_pageview],+ &context,+ limiter,+ )+ .await+ .expect("process_events must accept the batch even though one event is dropped");++ let captured = sink.get_events();+ assert_eq!(captured.len(), 1, "the over-budget AI event must drop");+ assert_eq!(+ captured[0].metadata.data_type,+ DataType::AnalyticsMain,+ "the same-sized $pageview must survive"+ );+ }++ /// A diverted AI event is governed by ai-scoped restrictions (the/// same slice the dedicated AI endpoints consult), not analytics ones:/// an ai-scoped DropEvent drops it, an analytics-scoped one must not/// cross pipelines into the AI lane.@@ -1480,7 +1955,7 @@ mod tests {}}- /// An ai-scoped RedirectToTopic applies to a diverted `$ai_*` event: the+ /// An ai-scoped RedirectToTopic applies to a diverted AI event: the/// event keeps its AI lane, but the stamped redirect beats the data type/// in the sink so operators can reroute an AI token's traffic ad hoc,/// matching v1 where the restriction overwrites `Destination::AiEvents`@@ -1931,7 +2406,7 @@ mod tests {expected_reason: Option<OverflowReason>,}- /// End-to-end gate for the AI overflow valve: a diverted `$ai_*` event+ /// End-to-end gate for the AI overflow valve: a diverted AI event/// is overflow-stamped only when the AI limiter is wired (setup builds/// it exactly when `CAPTURE_ANALYTICS_AI_EVENTS_OVERFLOW_TOPIC` is/// configured), and keeps its AI lane either way.diff --git a/rust/capture/src/events/mod.rs b/rust/capture/src/events/mod.rsindex a813d31d8082..d8df81b95239 100644--- a/rust/capture/src/events/mod.rs+++ b/rust/capture/src/events/mod.rs@@ -1,3 +1,4 @@+pub mod ai_byte_limit;pub mod analytics;pub mod overflow_stamping;pub mod recordings;diff --git a/rust/capture/src/events/recordings.rs b/rust/capture/src/events/recordings.rsindex 6ed154c2b494..9f57970a775c 100644--- a/rust/capture/src/events/recordings.rs+++ b/rust/capture/src/events/recordings.rs@@ -860,6 +860,7 @@ mod tests {user_agent: None,path: "/s/".to_string(),capture_mode: crate::config::CaptureMode::Recordings,+ ai_max_event_bytes: 0,sdk_attribution: crate::ingestion_warnings::SdkAttribution::default(),}}diff --git a/rust/capture/src/global_rate_limiter.rs b/rust/capture/src/global_rate_limiter.rsindex 8f158538bc79..d3d64d97816d 100644--- a/rust/capture/src/global_rate_limiter.rs+++ b/rust/capture/src/global_rate_limiter.rs@@ -45,25 +45,45 @@ impl<'a> GlobalRateLimitKey<'a> {}}+/// Redis key prefix for the AI lane's byte budget. Unlike the event limiters+/// this deliberately carries no `capture_mode`: AI events reach the AI topic+/// from the capture-ai deployment and from AI traffic diverted on+/// capture-analytics, so one token must draw on one budget across both. Both+/// deployments therefore have to point at the same rate-limiter Redis.+const AI_BYTES_REDIS_KEY_PREFIX: &str = "@ph/grl/capture/ai_bytes";++/// The per-instance knobs that distinguish one capture limiter from another.+/// Named fields rather than positional arguments: several are same-typed (two+/// `&str`, two `bool`) and a swap would silently misconfigure a limiter.+struct LimiterSpec<'a> {+ /// Default budget per window for keys with no custom override.+ threshold: u64,+ /// Static `key=value` CSV seeding the custom-key map.+ custom_keys_csv: Option<&'a String>,+ /// Multiplier applied to each seeded CSV value, for limiters whose+ /// operator-facing unit is not the window budget: the AI byte limiter is+ /// configured in bytes/second and enforces bytes/window. `1` when the CSV+ /// already carries per-window values.+ custom_key_scale: u64,+ local_cache_max_entries: u64,+ /// Minimum local level before a key earns a Redis sync. The unit is+ /// whatever the limiter counts, so an event limiter's floor is in events+ /// and the AI byte limiter's is in bytes.+ min_sync_floor: u64,+ redis_key_prefix: &'a str,+ metrics_scope: &'a str,+ /// Whether to wire the Redis-backed dynamic threshold source.+ enable_dynamic_source: bool,+ /// Evaluate and report, but never enforce.+ dry_run: bool,+}+pub struct GlobalRateLimiter {limiter: Box<dyn CommonGlobalRateLimiter>,dry_run: bool,}impl GlobalRateLimiter {- /// Build the token+distinct_id rate limiter from the capture config, sharing a- /// single Redis client. If a dedicated Redis URL is configured, creates a separate- /// client (optionally with read/write split). Falls back to `shared_redis` when no- /// dedicated URL is set.- pub async fn try_from_config(- config: &Config,- shared_redis: Arc<dyn Client + Send + Sync>,- ) -> anyhow::Result<Self> {- let redis_client = Self::build_redis_client(config, shared_redis).await?;- let redis_instances = vec![redis_client];- Self::new_token_distinct_id(config, redis_instances)- }-/// Create a per-(token, distinct_id) rate limiter sharing the given Redis instances.pub fn new_token_distinct_id(config: &Config,@@ -77,15 +97,20 @@ impl GlobalRateLimiter {Self::build(config,redis_instances,- config.global_rate_limit_token_distinctid_threshold,- config- .global_rate_limit_token_distinctid_overrides_csv- .as_ref(),- config.global_rate_limit_token_distinctid_local_cache_max_entries,- config.global_rate_limit_min_sync_floor,- &prefix,- &metrics_scope,- config.global_rate_limit_custom_threshold_key.is_some(),+ LimiterSpec {+ threshold: config.global_rate_limit_token_distinctid_threshold,+ custom_keys_csv: config+ .global_rate_limit_token_distinctid_overrides_csv+ .as_ref(),+ custom_key_scale: 1,+ local_cache_max_entries: config+ .global_rate_limit_token_distinctid_local_cache_max_entries,+ min_sync_floor: config.global_rate_limit_min_sync_floor,+ redis_key_prefix: &prefix,+ metrics_scope: &metrics_scope,+ enable_dynamic_source: config.global_rate_limit_custom_threshold_key.is_some(),+ dry_run: config.global_rate_limit_dry_run,+ },)}@@ -100,16 +125,63 @@ impl GlobalRateLimiter {Self::build(config,redis_instances,- config.global_rate_limit_token_threshold,- config.global_rate_limit_token_overrides_csv.as_ref(),- config.global_rate_limit_token_local_cache_max_entries,- config.global_rate_limit_min_sync_floor,- &prefix,- &metrics_scope,- // The token-only limiter is not wired to the dynamic refresh source.- // (The hierarchical resolver is still set but is a no-op for bare- // token keys, which have no `:distinct_id` suffix.)- false,+ LimiterSpec {+ threshold: config.global_rate_limit_token_threshold,+ custom_keys_csv: config.global_rate_limit_token_overrides_csv.as_ref(),+ custom_key_scale: 1,+ local_cache_max_entries: config.global_rate_limit_token_local_cache_max_entries,+ min_sync_floor: config.global_rate_limit_min_sync_floor,+ redis_key_prefix: &prefix,+ metrics_scope: &metrics_scope,+ // The token-only limiter is not wired to the dynamic refresh+ // source. (The hierarchical resolver is still set but is a no-op+ // for bare token keys, which have no `:distinct_id` suffix.)+ enable_dynamic_source: false,+ dry_run: config.global_rate_limit_dry_run,+ },+ )+ }++ /// Create the AI lane's per-token byte budget, sharing the given Redis instances.+ ///+ /// Nothing about the underlying limiter changes: the counts it accumulates+ /// are bytes rather than events, so the same sliding window that caps+ /// events/window elsewhere caps bytes/window here. Callers pass an event's+ /// serialized size as the count.+ ///+ /// Budgets are configured in bytes/second and scaled to the window, so the+ /// knob keeps the same meaning whatever `GLOBAL_RATE_LIMIT_WINDOW_INTERVAL_SECS`+ /// is set to.+ pub fn new_ai_bytes(+ config: &Config,+ redis_instances: Vec<Arc<dyn Client + Send + Sync>>,+ ) -> anyhow::Result<Self> {+ // `build` refuses to boot on a zero window, so this scaling never+ // divides a budget down to nothing.+ let window_secs = config.global_rate_limit_window_interval_secs;+ let metrics_scope = format!("{}_ai_bytes", config.capture_mode.as_tag());+ Self::build(+ config,+ redis_instances,+ LimiterSpec {+ threshold: config.ai_byte_limit_per_second.saturating_mul(window_secs),+ custom_keys_csv: config.ai_byte_limit_overrides_csv.as_ref(),+ custom_key_scale: window_secs,+ local_cache_max_entries: config.ai_byte_limit_local_cache_max_entries,+ // No floor. The shared knob is an event count, and this+ // limiter counts bytes, so inheriting it would be a unit+ // confusion that reads as deliberate. The floor exists to keep+ // an unbounded key space off Redis; this limiter's keys are+ // projects sending AI traffic, few enough that syncing all of+ // them is cheap and accurate enforcement is worth more.+ min_sync_floor: 0,+ redis_key_prefix: AI_BYTES_REDIS_KEY_PREFIX,+ metrics_scope: &metrics_scope,+ // Thresholds come from config only; the Django-written blob+ // holds event-count limits, in different units.+ enable_dynamic_source: false,+ dry_run: config.ai_byte_limit_dry_run,+ },)}@@ -131,29 +203,39 @@ impl GlobalRateLimiter {})}- #[allow(clippy::too_many_arguments)]fn build(config: &Config,redis_instances: Vec<Arc<dyn Client + Send + Sync>>,- threshold: u64,- custom_keys_csv: Option<&String>,- local_cache_max_entries: u64,- min_sync_floor: u64,- redis_key_prefix: &str,- metrics_scope: &str,- enable_dynamic_source: bool,+ spec: LimiterSpec<'_>,) -> anyhow::Result<Self> {+ // `leak_rate_for` divides the threshold by the window, so a zero window+ // gives every bucket an infinite leak rate and the limiter admits+ // everything. That is the opposite of what an operator setting a limit+ // asked for, and it fails silently, so refuse to boot on it.+ if config.global_rate_limit_window_interval_secs == 0 {+ anyhow::bail!(+ "invalid configuration: GLOBAL_RATE_LIMIT_WINDOW_INTERVAL_SECS must be greater than 0; \+ a zero window gives every key an infinite leak rate, so no limit is ever enforced"+ );+ }+// Seed the (swappable) custom-key map from the static CSV overrides. When a// dynamic source is enabled, the common refresh loop replaces this map only// from an explicit Redis blob; an absent key or an unreachable Redis is// fail-static, so the CSV seed keeps applying until a blob is written.- let seed = Self::format_custom_keys(custom_keys_csv);+ let mut seed = Self::format_custom_keys(spec.custom_keys_csv);+ if spec.custom_key_scale != 1 {+ for value in seed.values_mut() {+ *value = value.saturating_mul(spec.custom_key_scale);+ }+ }// Build the dynamic source when enabled and its Redis key + URL are set.// The source reads the JSON blob from the event-restrictions Redis (a// separate store from the traffic-count Redis in `redis_instances`) and// owns its own connection/reconnect; the common limiter runs the loop.- let custom_key_source: Option<Arc<dyn CustomKeyThresholdSource>> = if enable_dynamic_source+ let custom_key_source: Option<Arc<dyn CustomKeyThresholdSource>> = if spec+ .enable_dynamic_source{match (config.global_rate_limit_custom_threshold_key.as_ref(),@@ -183,11 +265,11 @@ impl GlobalRateLimiter {};let grl_config = GlobalRateLimiterConfig {- global_threshold: threshold,+ global_threshold: spec.threshold,window_interval: Duration::from_secs(config.global_rate_limit_window_interval_secs),sync_interval: Duration::from_secs(config.global_rate_limit_sync_interval_secs),tick_interval: Duration::from_millis(config.global_rate_limit_tick_interval_ms),- redis_key_prefix: redis_key_prefix.to_string(),+ redis_key_prefix: spec.redis_key_prefix.to_string(),custom_keys: Arc::new(ArcSwap::from_pointee(seed)),// Capture keys are always `token` or `token:distinct_id`, so the// hierarchical resolver is always the correct policy — a token-level@@ -198,9 +280,9 @@ impl GlobalRateLimiter {custom_key_refresh_interval: Duration::from_secs(config.global_rate_limit_custom_threshold_refresh_secs,),- local_cache_max_entries,- metrics_scope: metrics_scope.to_string(),- min_sync_floor,+ local_cache_max_entries: spec.local_cache_max_entries,+ metrics_scope: spec.metrics_scope.to_string(),+ min_sync_floor: spec.min_sync_floor,max_sync_keys_per_tick: config.global_rate_limit_max_sync_keys_per_tick,max_keys_per_command: config.global_rate_limit_max_keys_per_command,max_concurrent_commands: config.global_rate_limit_max_concurrent_commands,@@ -215,7 +297,7 @@ impl GlobalRateLimiter {..Default::default()};- let dry_run = config.global_rate_limit_dry_run;+ let dry_run = spec.dry_run;let limiter = match CommonGlobalRateLimiterImpl::new(grl_config, redis_instances) {Ok(l) => l,@@ -226,7 +308,10 @@ impl GlobalRateLimiter {};if dry_run {- info!("GlobalRateLimiter initialized in dry-run mode (evaluating but not enforcing)");+ info!(+ scope = spec.metrics_scope,+ "GlobalRateLimiter initialized in dry-run mode (evaluating but not enforcing)"+ );}Ok(Self {@@ -454,6 +539,97 @@ impl GlobalRateLimiter {Self::new_with(MockLimitingLimiter { limited_keys })}+ /// Test helper: build a `GlobalRateLimiter` that tallies the counts charged+ /// per key and limits once a key's running total reaches `threshold`, with+ /// the charge for the current call included. Lets weight-charging call sites+ /// (the AI byte budget) be tested without Redis.+ ///+ /// Accounting is strict: a key is limited as soon as its total crosses the+ /// threshold, including on its very first charge. Tests then say what they+ /// mean — an event drops because of arithmetic a reader can check, not+ /// because of a seam-specific exemption.+ ///+ /// The real limiter also admits a key whose cache entry is missing, which+ /// recurs on every eviction and every new pod.+ /// [`Self::mock_budget_admitting_cold_keys`] models that, and one test pins+ /// it rather than every test inheriting it.+ ///+ /// Neither models the local cache's leaky-bucket decay, so a key never+ /// recovers here.+ #[cfg(test)]+ pub(crate) fn mock_budget(threshold: u64) -> Self {+ Self::mock_budget_with(threshold, false)+ }++ /// Test helper: [`Self::mock_budget`], plus the real limiter's fail-open on+ /// a cache miss — a key's first charge is admitted however far over the+ /// threshold it is.+ #[cfg(test)]+ pub(crate) fn mock_budget_admitting_cold_keys(threshold: u64) -> Self {+ Self::mock_budget_with(threshold, true)+ }++ #[cfg(test)]+ fn mock_budget_with(threshold: u64, admit_cold_keys: bool) -> Self {+ use async_trait::async_trait;+ use std::sync::Mutex;++ struct MockBudgetLimiter {+ threshold: u64,+ admit_cold_keys: bool,+ charged: Mutex<HashMap<String, u64>>,+ }++ #[async_trait]+ impl CommonGlobalRateLimiter for MockBudgetLimiter {+ async fn check_limit(+ &self,+ key: &str,+ count: u64,+ _timestamp: Option<DateTime<Utc>>,+ ) -> EvalResult {+ let mut charged = self.charged.lock().unwrap();+ let cold_key = !charged.contains_key(key);+ let total = charged.entry(key.to_string()).or_insert(0);+ *total += count;+ let exempt = cold_key && self.admit_cold_keys;+ if !exempt && *total >= self.threshold {+ EvalResult::Limited(GlobalRateLimitResponse {+ key: key.to_string(),+ current_count: *total as f64,+ threshold: self.threshold,+ window_interval: std::time::Duration::from_secs(60),+ sync_interval: std::time::Duration::from_secs(15),+ is_custom_limited: false,+ })+ } else {+ EvalResult::Allowed+ }+ }++ async fn check_custom_limit(+ &self,+ _key: &str,+ _count: u64,+ _timestamp: Option<DateTime<Utc>>,+ ) -> EvalResult {+ EvalResult::NotApplicable+ }++ fn is_custom_key(&self, _key: &str) -> bool {+ false+ }++ fn shutdown(&mut self) {}+ }++ Self::new_with(MockBudgetLimiter {+ threshold,+ admit_cold_keys,+ charged: Mutex::new(HashMap::new()),+ })+ }+// In capture deploys, the custom keys and rate limit thresholds should be// supplied as a CSV list of <string_key>=<u64_value> elements. malformed// elements will be logged and skipped during limiter initializationdiff --git a/rust/capture/src/ingestion_warnings/legacy.rs b/rust/capture/src/ingestion_warnings/legacy.rsindex 1b162eef5e4c..79dc0d97c685 100644--- a/rust/capture/src/ingestion_warnings/legacy.rs+++ b/rust/capture/src/ingestion_warnings/legacy.rs@@ -55,7 +55,14 @@ pub fn warning_for_capture_error(err: &CaptureError) -> Option<WarningType> {// verified token exists, and so never reach the abort path. This is// the same drop the nodejs pipeline reports as message_size_too_large// when its own produce hits the broker limit.- CaptureError::EventTooBig(_) => Some(WarningType::MessageSizeTooLarge),+ //+ // `AiEventTooBig` is the AI lane's own per-event ceiling, raised by+ // `process_events` before anything is sent. Same warning: the customer's+ // fix is identical either way — send a smaller event. They differ only+ // in how many events the warning charges, below.+ CaptureError::EventTooBig(_) | CaptureError::AiEventTooBig(_) => {+ Some(WarningType::MessageSizeTooLarge)+ }// Transport and parse failures surface before a verified token// exists, so there is no team to attribute a warning to.@@ -94,6 +101,11 @@ pub fn warning_for_capture_error(err: &CaptureError) -> Option<WarningType> {| CaptureError::ServiceUnavailable(_)| CaptureError::BodyReadTimeout| CaptureError::InternalError(_) => None,++ // A non-AI event sent to an AI endpoint. The 400 tells whoever made the+ // call; the warning tells whoever owns the project, who is usually not+ // the same person and cannot see the response.+ CaptureError::NonAiEventOnAiLane(_) => Some(WarningType::InvalidAiEvent),}}@@ -110,6 +122,10 @@ pub fn warning_for_capture_error(err: &CaptureError) -> Option<WarningType> {/// would report delivered events as failed. It emits `count = 1` — at least/// one event was rejected — matching the sink's per-event/// `kafka_message_size` drop metric.+///+/// `AiEventTooBig` is not an exception, despite also being a size failure: it+/// fires before the sink, so nothing was enqueued and the whole batch really+/// was lost. It takes the full-batch count like every other validation abort.pub fn emit_processing_abort_warning(emitter: Option<&dyn WarningEmitter>,context: &ProcessingContext,@@ -154,6 +170,7 @@ mod tests {historical_migration: false,chatty_debug_enabled: false,capture_mode: crate::config::CaptureMode::Events,+ ai_max_event_bytes: 0,sdk_attribution: attribution,}}@@ -232,7 +249,7 @@ mod tests {#[test]fn abort_warnings_map_only_customer_actionable_errors() {- let cases: [(CaptureError, Option<WarningType>); 13] = [+ let cases: [(CaptureError, Option<WarningType>); 14] = [(CaptureError::MissingEventName,Some(WarningType::MissingEventName),@@ -245,6 +262,10 @@ mod tests {CaptureError::EventTooBig("too big".to_string()),Some(WarningType::MessageSizeTooLarge),),+ (+ CaptureError::AiEventTooBig("too big".to_string()),+ Some(WarningType::MessageSizeTooLarge),+ ),// Excluded on purpose; see warning_for_capture_error's doc.(CaptureError::InvalidCookielessMode, None),(CaptureError::EmptyBatch, None),@@ -281,6 +302,7 @@ mod tests {CaptureError::MissingEventName,CaptureError::MissingDistinctId,CaptureError::EventTooBig("too big".to_string()),+ CaptureError::AiEventTooBig("too big".to_string()),];let mapped = mapping_errors.iter().filter_map(warning_for_capture_error);@@ -308,7 +330,9 @@ mod tests {// the v2 row never reads as a no-op, matching v1's batch-abort// convention. EventTooBig charges 1: earlier batch events were// already enqueued and typically deliver, so a batch count would- // report delivered events as failed.+ // report delivered events as failed. AiEventTooBig is the same warning+ // but not the same case: it fires before the sink, nothing was+ // enqueued, so it charges the batch like any other validation abort.let cases = [(CaptureError::MissingDistinctId,@@ -328,6 +352,12 @@ mod tests {25u64,1u64,),+ (+ CaptureError::AiEventTooBig("too big".to_string()),+ WarningType::MessageSizeTooLarge,+ 25u64,+ 25u64,+ ),];for (error, expected_warning, event_count, expected_count) in cases {diff --git a/rust/capture/src/ingestion_warnings/otel.rs b/rust/capture/src/ingestion_warnings/otel.rsindex c1df7d5d2556..60ab04e3aa98 100644--- a/rust/capture/src/ingestion_warnings/otel.rs+++ b/rust/capture/src/ingestion_warnings/otel.rs@@ -56,7 +56,12 @@ pub fn warning_for_otel_parse_error(err: &CaptureError) -> Option<WarningType> {// Reachable only if `parse_request` grows a new failure mode: decide// warn-or-not there rather than defaulting to silence here.- CaptureError::RequestHydrationError(_)+ // `NonAiEventOnAiLane` and `AiEventTooBig` join them as structurally+ // unreachable: only `process_events` raises them, and this handler does+ // not call it.+ CaptureError::NonAiEventOnAiLane(_)+ | CaptureError::AiEventTooBig(_)+ | CaptureError::RequestHydrationError(_)| CaptureError::EmptyBatch| CaptureError::EmptyPayload| CaptureError::EmptyPayloadFiltered@@ -134,6 +139,36 @@ pub fn emit_span_cap_warning();}+/// Emit the warning for spans shed for exceeding the deployment's per-event+/// size ceiling.+///+/// This is the second warning here that accompanies a 200. The export is not+/// refused, because an OTEL collector retries a rejected export and would stall+/// behind a span that can never fit — so the offending spans are shed and the+/// rest publish. That trade makes the loss invisible in the response, which is+/// what this warning exists to correct.+///+/// `count` charges only the spans that were shed; the others landed.+pub fn emit_span_too_big_warning(+ emitter: Option<&dyn WarningEmitter>,+ request: &WarningRequestContext,+ dropped_spans: usize,+ limit: u64,+) {+ let mut details = Map::new();+ details.insert("droppedSpans".to_string(), json!(dropped_spans));+ details.insert("limit".to_string(), json!(limit));++ emit_request_warning(+ emitter,+ request,+ CAPTURE_AI_OTEL,+ WarningType::MessageSizeTooLarge,+ details,+ dropped_spans as u64,+ );+}+/// Emit the warning for an export whose spans all filtered out as non-AI.////// This is the one warning here that accompanies a 200. The OTLP contract givesdiff --git a/rust/capture/src/ingestion_warnings/replay.rs b/rust/capture/src/ingestion_warnings/replay.rsindex ee5d655e7cf8..8868754d615d 100644--- a/rust/capture/src/ingestion_warnings/replay.rs+++ b/rust/capture/src/ingestion_warnings/replay.rs@@ -181,6 +181,8 @@ pub fn warning_for_capture_error(err: &CaptureError) -> Option<WarningType> {CaptureError::InvalidCookielessMode| CaptureError::InvalidTimestamp| CaptureError::MissingWindowId+ | CaptureError::NonAiEventOnAiLane(_)+ | CaptureError::AiEventTooBig(_)| CaptureError::MissingEventName => None,// Quota, rate, and ops-imposed drops are surfaced through billing and@@ -270,6 +272,7 @@ mod tests {historical_migration: false,chatty_debug_enabled: false,capture_mode: CaptureMode::Recordings,+ ai_max_event_bytes: 0,sdk_attribution: attribution,}}diff --git a/rust/capture/src/otel/filtering.rs b/rust/capture/src/otel/filtering.rsindex b2dc04331f88..0f1002d8abd4 100644--- a/rust/capture/src/otel/filtering.rs+++ b/rust/capture/src/otel/filtering.rs@@ -130,7 +130,7 @@ pub fn build_events(};let metadata = ProcessedEventMetadata {- data_type: DataType::AnalyticsMain,+ data_type: DataType::AiEvents,session_id: None,computed_timestamp: Some(timestamp),event_name: span_event.event_name,diff --git a/rust/capture/src/otel/mod.rs b/rust/capture/src/otel/mod.rsindex 9511164eed80..d27bb358edc4 100644--- a/rust/capture/src/otel/mod.rs+++ b/rust/capture/src/otel/mod.rs@@ -19,14 +19,17 @@ use serde_json::json;use tracing::{debug, instrument, warn, Span};use crate::api::{CaptureError, CaptureResponse, CaptureResponseCode};+use crate::events::ai_byte_limit::drop_ai_byte_limited;use crate::events::overflow_stamping::stamp_overflow_reason;use crate::extractors::extract_body_with_timeout;use crate::ingestion_warnings::otel::{- emit_no_ai_spans_warning, emit_otel_parse_warning, emit_span_cap_warning, SpanCapStage,+ emit_no_ai_spans_warning, emit_otel_parse_warning, emit_span_cap_warning,+ emit_span_too_big_warning, SpanCapStage,};use crate::prometheus::{report_dropped_events, report_internal_error_metrics};use crate::router::State as AppState;use crate::token::validate_token;+use crate::v0_request::exceeds_max_ai_event_bytes;use self::attribution::otel_request_context;@@ -280,6 +283,49 @@ pub async fn otel_handler(e.into_response()})?;+ // Shed spans past the deployment's per-event ceiling rather than refusing+ // the export.+ //+ // Every other AI path answers an oversize event with an error: the legacy+ // batch path 413s the request and v1 marks the single event dropped. OTEL+ // diverges because a collector retries a rejected export, so a span that+ // can never fit would stall every span queued behind it, indefinitely. The+ // span cap on this endpoint sheds spans for the same reason.+ //+ // The cost is that the loss cannot be seen in the response, so it is+ // reported twice: on `capture_events_dropped_total` for us, and as a+ // `MessageSizeTooLarge` ingestion warning for whoever owns the project.+ let before = processed_events.len();+ processed_events+ .retain(|e| !exceeds_max_ai_event_bytes(e.event.data.len(), state.ai_max_event_bytes));+ let dropped = before - processed_events.len();+ if dropped > 0 {+ report_dropped_events("ai_event_too_big", dropped as u64);+ emit_span_too_big_warning(+ state.ingestion_warning_emitter.as_deref(),+ &otel_request_context(&token, OTEL_PATH, Some(&request)),+ dropped,+ state.ai_max_event_bytes,+ );+ }++ // Charge the AI lane's per-project byte budget, shedding the spans that+ // take the project past it. This endpoint builds its events at the handler+ // and reaches the sink through neither analytics pipeline, so without this+ // call a sender could spend an unbounded number of bytes here while the+ // same bytes on `/i/v0/ai/batch` are capped.+ //+ // Shedding rather than refusing, for the reason the size ceiling above+ // sheds: a collector retries a rejected export, so refusing would stall+ // every span behind the ones over budget. Unlike the size ceiling this+ // raises no ingestion warning — a rate drop is ops-imposed, and capture+ // surfaces those through billing and ops channels rather than the+ // customer-facing warnings table, which `warning_for_capture_error` pins.+ //+ // It runs after the ceiling so an event too big to publish spends none of+ // the budget, matching the order both analytics pipelines use.+ drop_ai_byte_limited(&mut processed_events, state.ai_byte_rate_limiter.as_ref()).await;+// Apply the in-process OverflowLimiter governor to every AnalyticsMain// span in the batch before handing off to the sink. OTEL bypasses// `events::analytics::process_events`, so this call is what preserves@@ -293,13 +339,17 @@ pub async fn otel_handler(state.ai_events_overflow_limiter.as_ref(),);+ // Count what the sink was handed, not what arrived: `span_count` predates+ // the size ceiling and the byte budget, either of which may have shed spans.+ let ingested = processed_events.len() as u64;+state.sink.send_batch(processed_events).await.map_err(|e| {report_internal_error_metrics(e.to_metric_tag(), "otel_sink");warn!("Failed to send OTel events to Kafka: {:?}", e);e.into_response()})?;- counter!("capture_ai_otel_events_ingested").increment(span_count as u64);+ counter!("capture_ai_otel_events_ingested").increment(ingested);counter!("capture_ai_otel_requests_success").increment(1);debug!(diff --git a/rust/capture/src/overflow_parity.rs b/rust/capture/src/overflow_parity.rsindex 9c9afcd9f868..331d8fdeef32 100644--- a/rust/capture/src/overflow_parity.rs+++ b/rust/capture/src/overflow_parity.rs@@ -113,6 +113,7 @@ fn v0_context(now: DateTime<Utc>) -> ProcessingContext {historical_migration: false,chatty_debug_enabled: false,capture_mode: crate::config::CaptureMode::Events,+ ai_max_event_bytes: 0,sdk_attribution: crate::ingestion_warnings::SdkAttribution::default(),}}@@ -146,6 +147,7 @@ async fn run_v0(limits: Limits, batch_size: usize, observe: usize) -> Observed {None,(0..batch_size).map(|_| v0_raw_event()).collect(),&v0_context(now),+ None,).await.expect("v0 pipeline must accept the batch");diff --git a/rust/capture/src/payload/analytics.rs b/rust/capture/src/payload/analytics.rsindex 1a7a18026bca..c4d922ed420c 100644--- a/rust/capture/src/payload/analytics.rs+++ b/rust/capture/src/payload/analytics.rs@@ -132,6 +132,7 @@ pub async fn handle_event_payload(user_agent: Some(metadata.user_agent.to_string()),chatty_debug_enabled,capture_mode: state.capture_mode,+ ai_max_event_bytes: state.ai_max_event_bytes,sdk_attribution,};debug_or_info!(chatty_debug_enabled, context=?context, event_count=?events.len(), "processing complete");diff --git a/rust/capture/src/payload/recordings.rs b/rust/capture/src/payload/recordings.rsindex bc21fa2a68de..1423f8365aad 100644--- a/rust/capture/src/payload/recordings.rs+++ b/rust/capture/src/payload/recordings.rs@@ -135,6 +135,7 @@ pub async fn handle_recording_payload(user_agent: Some(metadata.user_agent.to_string()),chatty_debug_enabled,capture_mode: state.capture_mode,+ ai_max_event_bytes: 0,sdk_attribution: attribution_from_event(&events[0], metadata.user_agent),};diff --git a/rust/capture/src/router.rs b/rust/capture/src/router.rsindex 4a9ee3255b63..ca836ff92632 100644--- a/rust/capture/src/router.rs+++ b/rust/capture/src/router.rs@@ -66,6 +66,9 @@ pub struct State {pub is_mirror_deploy: bool,pub verbose_sample_percent: f32,pub ai_max_sum_of_parts_bytes: usize,+ /// Largest AI-lane event this deployment accepts (`AI_MAX_EVENT_BYTES`).+ /// `0` disables the ceiling.+ pub ai_max_event_bytes: u64,pub body_chunk_read_timeout: Option<Duration>,pub body_read_chunk_size_kb: usize,pub capture_v1_max_compressed_body_bytes: usize,@@ -93,6 +96,11 @@ pub struct State {/// `OVERFLOW_ENABLED` and the AI overflow valve are set; `None` leaves/// the AI lane subject to restriction-driven `force_overflow` only.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,+ /// charged an event's serialized size rather than `1`. Drops over-budget+ /// events, unlike the overflow limiter's reroute.+ pub ai_byte_rate_limiter: Option<Arc<GlobalRateLimiter>>,/// Redis-backed replay overflow limiter for session recording sessions./// When present, the recordings pipeline calls `is_limited(session_id)`/// and stamps `ProcessedEventMetadata::overflow_reason = ReplayLimited` so@@ -176,12 +184,14 @@ pub fn router<TZ: TimeSource + Send + Sync + 'static, R: Client + Send + Sync +is_mirror_deploy: bool,verbose_sample_percent: f32,ai_max_sum_of_parts_bytes: usize,+ ai_max_event_bytes: u64,body_chunk_read_timeout_ms: Option<u64>,body_read_chunk_size_kb: usize,capture_v1_max_compressed_body_bytes: usize,capture_v1_max_decompressed_body_bytes: usize,overflow_limiter: Option<Arc<OverflowLimiter>>,ai_events_overflow_limiter: Option<Arc<OverflowLimiter>>,+ ai_byte_rate_limiter: Option<Arc<GlobalRateLimiter>>,replay_overflow_limiter: Option<Arc<RedisLimiter>>,v1_sink_router: Option<Arc<crate::v1::sinks::Router>>,capture_v1_scatter_gather_min_batch: usize,@@ -205,12 +215,14 @@ pub fn router<TZ: TimeSource + Send + Sync + 'static, R: Client + Send + Sync +is_mirror_deploy,verbose_sample_percent,ai_max_sum_of_parts_bytes,+ ai_max_event_bytes,body_chunk_read_timeout: body_chunk_read_timeout_ms.map(Duration::from_millis),body_read_chunk_size_kb,capture_v1_max_compressed_body_bytes,capture_v1_max_decompressed_body_bytes,overflow_limiter,ai_events_overflow_limiter,+ ai_byte_rate_limiter,replay_overflow_limiter,v1_sink_router,capture_v1_scatter_gather_min_batch,@@ -257,8 +269,16 @@ pub fn router<TZ: TimeSource + Send + Sync + 'static, R: Client + Send + Sync +.get(v0_endpoint::event).options(v0_endpoint::options),)- // `$ai_*` events: same batch handler, dedicated path so the ingress can route- // them to the capture-ai deployment and keep AI/analytics workloads isolated.+ .layer(DefaultBodyLimit::max(BATCH_BODY_SIZE))+ .layer(Extension(WireBodyLimit(BATCH_BODY_SIZE)));++ // AI events: the same batch handler as `/batch`, on a dedicated path so the+ // ingress can route them to the capture-ai deployment and keep AI and+ // analytics workloads isolated. Its own router rather than a member of+ // `batch_router` so capture-ai can serve this path without also serving the+ // analytics batch and event routes, and rather than a member of `ai_router`+ // so it keeps the batch body limit instead of the larger multipart one.+ let ai_batch_router = Router::new().route("/i/v0/ai/batch",post(v0_endpoint::event)@@ -396,19 +416,32 @@ pub fn router<TZ: TimeSource + Send + Sync + 'static, R: Client + Send + Sync +).layer(DefaultBodyLimit::max(otel::OTEL_BODY_SIZE));+ // Each deployment registers its own ingress and nothing else. The AI paths+ // (`/i/v0/ai*`) belong to capture-ai and the analytics paths to+ // capture-analytics; the ingress has always routed them that way, so a+ // deployment serving the other set is surface no traffic reaches and no+ // restriction slice covers. `Pipeline::for_capture_mode` loads exactly the+ // pipelines each set can produce to, so the two must stay in step.+ //+ // `$ai_*` events still reach capture-analytics — on `/batch`, from SDKs that+ // send everything to one endpoint. Those divert to the AI lane by event+ // name; that is unrelated to which paths are registered here.let mut router = match capture_mode {- CaptureMode::Events | CaptureMode::Ai => Router::new()+ CaptureMode::Events => Router::new().merge(batch_router).merge(event_router)- .merge(test_router)+ .merge(test_router),+ CaptureMode::Ai => Router::new()+ .merge(ai_batch_router).merge(ai_router).merge(otel_router),- // Import must not register ai_router/otel_router: those handlers build- // their own ProcessingContext with historical_migration: false, so they- // sidestep both Import gates (historical-only drop and GRL bypass) and- // would return a false 200 for events this deployment silently discards.- // The /i/v0/ai/batch path stays reachable via batch_router, which- // dispatches to the gated v0_endpoint::event handler.+ // Import is an analytics deployment restricted to backfills, so it+ // serves the analytics paths. It must never register ai_router or+ // otel_router for a second reason on top of the split above: those+ // handlers build their own ProcessingContext with+ // `historical_migration: false`, so they sidestep both Import gates+ // (historical-only drop and GRL bypass) and would return a false 200+ // for events this deployment silently discards.CaptureMode::Import => Router::new().merge(batch_router).merge(event_router)@@ -441,8 +474,11 @@ pub fn router<TZ: TimeSource + Send + Sync + 'static, R: Client + Send + Sync +// mode must declare whether it serves the v1 analytics endpoint instead of// silently defaulting to "no v1 routes" and 404ing its traffic.let serves_v1_analytics = match capture_mode {- CaptureMode::Events | CaptureMode::Ai | CaptureMode::Import => true,- CaptureMode::Recordings => false,+ CaptureMode::Events | CaptureMode::Import => true,+ // `/i/v1/analytics/events` is an analytics endpoint: it accepts any+ // event name and its traffic is governed by analytics restrictions,+ // which capture-ai no longer loads.+ CaptureMode::Ai | CaptureMode::Recordings => false,};if serves_v1_analytics && state.v1_sink_router.is_some() {router = router.merge(crate::v1::router::router(crate::v1::router::RouterConfig {diff --git a/rust/capture/src/setup.rs b/rust/capture/src/setup.rsindex ede2994f3806..1bf6ddd78477 100644--- a/rust/capture/src/setup.rs+++ b/rust/capture/src/setup.rs@@ -177,18 +177,44 @@ pub async fn build_components(.expect("failed to create redis client"),);- // The dynamic custom-threshold refresh loop is owned by the common limiter:- // when GLOBAL_RATE_LIMIT_CUSTOM_THRESHOLD_KEY is set, `build()` wires a Redis- // source into the limiter, which spawns and manages the refresh task itself.- let global_rate_limiter_token_distinctid = if config.global_rate_limit_enabled {- let limiter = GlobalRateLimiter::try_from_config(&config, redis_client.clone())- .await- .expect("failed to create global rate limiter");- Some(Arc::new(limiter))+ // Each global limiter gets its own Redis client, from the same source: the+ // dedicated rate-limiter Redis when GLOBAL_RATE_LIMIT_REDIS_URL is set,+ // otherwise the shared one. A client owns one MultiplexedConnection, and+ // each limiter drives its own tick loop against it under a per-command+ // timeout, so sharing one would let a slow drain on either limiter eat the+ // other's budget. Key prefixes already keep their counts apart; this keeps+ // their pipelines apart too. Neither is built unless its limiter is on, so+ // a deployment running neither opens no connection.+ let ai_byte_limit_enabled = ai_byte_limit_per_second(&config) > 0;+ let rate_limiter_redis = if config.global_rate_limit_enabled {+ Some(+ GlobalRateLimiter::build_redis_client(&config, redis_client.clone())+ .await+ .expect("failed to create rate limiter redis client"),+ )+ } else {+ None+ };+ let ai_byte_limiter_redis = if ai_byte_limit_enabled {+ Some(+ GlobalRateLimiter::build_redis_client(&config, redis_client.clone())+ .await+ .expect("failed to create AI byte limiter redis client"),+ )} else {None};+ // The dynamic custom-threshold refresh loop is owned by the common limiter:+ // when GLOBAL_RATE_LIMIT_CUSTOM_THRESHOLD_KEY is set, `build()` wires a Redis+ // source into the limiter, which spawns and manages the refresh task itself.+ let global_rate_limiter_token_distinctid = rate_limiter_redis.as_ref().map(|redis| {+ Arc::new(+ GlobalRateLimiter::new_token_distinct_id(&config, vec![redis.clone()])+ .expect("failed to create global rate limiter"),+ )+ });+// add new "scoped" quota limiters here as new quota tracking buckets are added// to PostHog! Here a "scoped" limiter is one that should be INDEPENDENT of the// global billing limiter applied here to every event batch. You must supply the@@ -327,6 +353,21 @@ pub async fn build_components(None};+ // Unlike the governor-backed overflow limiters above, this one needs no+ // metrics or state-cleanup tasks of its own: the global rate limiter owns+ // its background tick loop, its cache eviction, and its own metric series+ // (scoped `<mode>_ai_bytes`).+ if ai_byte_limit_enabled {+ warn_if_ai_byte_budget_below_max_event(&config);+ }+ warn_if_ai_ceiling_exceeds_producer_cap(&config);+ let ai_byte_rate_limiter = ai_byte_limiter_redis.as_ref().map(|redis| {+ Arc::new(+ GlobalRateLimiter::new_ai_bytes(&config, vec![redis.clone()])+ .expect("failed to create AI byte rate limiter"),+ )+ });+let v1_sink_router = if !config.capture_v1_sinks.is_empty() {Some(create_v1_sink_router(&config, &sink_env, v1_sink_handles)@@ -358,12 +399,14 @@ pub async fn build_components(config.is_mirror_deploy,config.verbose_sample_percent,config.ai_max_sum_of_parts_bytes,+ config.ai_max_event_bytes,config.body_chunk_read_timeout_ms,config.body_read_chunk_size_kb,config.capture_v1_max_compressed_body_bytes,config.capture_v1_max_decompressed_body_bytes,overflow_limiter,ai_events_overflow_limiter,+ ai_byte_rate_limiter,replay_overflow_limiter,v1_sink_router.clone(),config.capture_v1_scatter_gather_min_batch,@@ -391,7 +434,7 @@ pub async fn build_components(/// `CAPTURE_ANALYTICS_AI_EVENTS_OVERFLOW_TOPIC` means AI events never/// overflow. Import mode refuses an armed valve at boot: non-AI import events/// can't overflow because historical rerouting takes precedence no matter how-/// the deployment is configured, but nothing structural protects `$ai_*`+/// 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 {@@ -407,7 +450,64 @@ fn ai_events_overflow_valve(config: &Config) -> bool {armed}-/// Builds the v1 sink router. The dedicated `$ai_*` topics are+/// The AI byte budget this deployment enforces, or `0` to skip building the+/// limiter entirely. Import is exempt — backfills are never throttled, matching+/// the other limiters — and not building the limiter is the whole exemption, so+/// neither pipeline's charge step needs capture-mode awareness of its own.+fn ai_byte_limit_per_second(config: &Config) -> u64 {+ if matches!(config.capture_mode, CaptureMode::Import) {+ return 0;+ }+ config.ai_byte_limit_per_second+}++/// Warns when the per-event ceiling is at or above what the producer will+/// send. Above the cap the ceiling stops being a guard: capture reads the+/// body, builds the event, and the producer refuses it anyway, so the only+/// thing the higher ceiling buys is a later failure. Both sides come from+/// config, so the check stays correct when either knob moves.+fn ai_ceiling_exceeds_producer_cap(config: &Config) -> bool {+ let ceiling = config.ai_max_event_bytes;+ // `0` disables the ceiling, so there is no ordering to be wrong about.+ ceiling != 0 && ceiling >= config.kafka.kafka_producer_message_max_bytes as u64+}++fn warn_if_ai_ceiling_exceeds_producer_cap(config: &Config) {+ if ai_ceiling_exceeds_producer_cap(config) {+ warn!(+ ai_max_event_bytes = config.ai_max_event_bytes,+ kafka_producer_message_max_bytes = config.kafka.kafka_producer_message_max_bytes,+ "AI_MAX_EVENT_BYTES is at or above KAFKA_PRODUCER_MESSAGE_MAX_BYTES; \+ events between the producer cap and the ceiling are built and then \+ refused by the producer"+ );+ }+}++/// Warns when a token sending full-size AI events would be limited on nearly+/// every one of them, because the window budget cannot fit even a single event+/// at the deployment's ceiling. Both sides come from config, so the check stays+/// correct when either knob moves.+fn warn_if_ai_byte_budget_below_max_event(config: &Config) {+ let max_event_bytes = config.ai_max_event_bytes;+ if max_event_bytes == 0 {+ return;+ }+ let window_secs = config.global_rate_limit_window_interval_secs;+ let window_budget = ai_byte_limit_per_second(config).saturating_mul(window_secs);+ if window_budget < max_event_bytes {+ warn!(+ ai_byte_limit_per_second = config.ai_byte_limit_per_second,+ window_secs,+ window_budget,+ max_event_bytes,+ "AI_BYTE_LIMIT_PER_SECOND yields a window budget below AI_MAX_EVENT_BYTES; \+ a token sending full-size events will be limited on nearly every event"+ );+ }+}++/// Builds the v1 sink router. The dedicated AI topics are/// deployment-level config (`CAPTURE_ANALYTICS_AI_EVENTS_TOPIC` and `CAPTURE_ANALYTICS_AI_EVENTS_OVERFLOW_TOPIC`),/// so they are injected into every sink config here; the overwrite is/// unconditional so a stray per-sink `TOPIC_AI`/`TOPIC_AI_OVERFLOW` env var@@ -867,6 +967,44 @@ mod tests {);}+ /// Signature shared by the limiter constructors under test.+ type LimiterBuilder = fn(+ &Config,+ Vec<Arc<dyn common_redis::Client + Send + Sync>>,+ ) -> anyhow::Result<GlobalRateLimiter>;++ /// A zero window gives every bucket an infinite leak rate, so the limiter+ /// admits everything. Building one must fail at boot rather than run as a+ /// limiter that never limits.+ #[rstest]+ #[case::ai_bytes(GlobalRateLimiter::new_ai_bytes)]+ #[case::token_distinct_id(GlobalRateLimiter::new_token_distinct_id)]+ fn limiters_reject_a_zero_window(#[case] build: LimiterBuilder) {+ let cfg_env: HashMap<String, String> = [+ ("REDIS_URL", "redis://localhost:6379/"),+ ("CAPTURE_MODE", "events"),+ ("KAFKA_HOSTS", "localhost:9092"),+ ("KAFKA_TOPIC", "events_plugin_ingestion"),+ ("GLOBAL_RATE_LIMIT_WINDOW_INTERVAL_SECS", "0"),+ ]+ .into_iter()+ .map(|(k, v)| (k.to_string(), v.to_string()))+ .collect();+ let config: Config =+ envconfig::Envconfig::init_from_hashmap(&cfg_env).expect("test config");++ // `GlobalRateLimiter` is not `Debug`, so unwrap the error by hand.+ let err = match build(&config, vec![]) {+ Ok(_) => panic!("a zero window must not build a limiter"),+ Err(err) => err,+ };+ assert!(+ err.to_string()+ .contains("GLOBAL_RATE_LIMIT_WINDOW_INTERVAL_SECS"),+ "the error must name the offending setting, got: {err}"+ );+ }+#[test]#[should_panic(expected = "imports must never overflow")]fn ai_events_overflow_valve_rejects_armed_valve_in_import_mode() {@@ -1083,6 +1221,64 @@ mod tests {.expect("boot must proceed when the completeness check is disabled");}+ /// The ceiling only guards anything while it sits under the producer's cap.+ /// A deployment that raises the producer keeps its headroom; one that never+ /// touched it gets told the default is too high for its broker.+ #[rstest::rstest]+ #[case::default_ceiling_on_a_default_producer(8_388_608, 1_000_000, true)]+ #[case::default_ceiling_under_a_raised_producer(8_388_608, 10_485_760, false)]+ #[case::equal_still_warns(1_000_000, 1_000_000, true)]+ #[case::disabled_ceiling_never_warns(0, 1_000_000, false)]+ fn ai_ceiling_is_checked_against_the_producer_cap(+ #[case] ceiling: u64,+ #[case] producer_cap: u32,+ #[case] expected: bool,+ ) {+ let cfg_env: HashMap<String, String> = [+ ("REDIS_URL", "redis://localhost:6379/"),+ ("CAPTURE_MODE", "ai"),+ ("KAFKA_HOSTS", "localhost:9092"),+ ("KAFKA_TOPIC", "events_plugin_ingestion_ai"),+ ]+ .into_iter()+ .map(|(k, v)| (k.to_string(), v.to_string()))+ .collect();+ let mut config: Config =+ envconfig::Envconfig::init_from_hashmap(&cfg_env).expect("test config");+ config.ai_max_event_bytes = ceiling;+ config.kafka.kafka_producer_message_max_bytes = producer_cap;++ assert_eq!(ai_ceiling_exceeds_producer_cap(&config), expected);+ }++ /// Import deployments never build the AI byte limiter, however the knob is+ /// set — that omission is the entire import exemption, so a rate leaking+ /// through here would start throttling backfills.+ #[rstest::rstest]+ #[case::events_keeps_the_configured_rate(CaptureMode::Events, 5_000, 5_000)]+ #[case::ai_keeps_the_configured_rate(CaptureMode::Ai, 5_000, 5_000)]+ #[case::import_is_exempt(CaptureMode::Import, 5_000, 0)]+ #[case::unset_stays_unset(CaptureMode::Events, 0, 0)]+ fn ai_byte_limit_per_second_by_mode(+ #[case] mode: CaptureMode,+ #[case] configured: u64,+ #[case] expected: u64,+ ) {+ let cfg_env: HashMap<String, String> = [+ ("REDIS_URL", "redis://localhost:6379/"),+ ("CAPTURE_MODE", mode.as_tag()),+ ("KAFKA_HOSTS", "localhost:9092"),+ ]+ .into_iter()+ .map(|(k, v)| (k.to_string(), v.to_string()))+ .collect();+ let mut config: Config =+ envconfig::Envconfig::init_from_hashmap(&cfg_env).expect("test config");+ config.ai_byte_limit_per_second = configured;++ assert_eq!(ai_byte_limit_per_second(&config), expected);+ }+/// Absent gauge means warnings are off on purpose; `0` means an operator/// asked for them and we could not build them. `reason` says which.#[rstest]diff --git a/rust/capture/src/v0_endpoint.rs b/rust/capture/src/v0_endpoint.rsindex 9110c7c7ea05..d01ab903f1a0 100644--- a/rust/capture/src/v0_endpoint.rs+++ b/rust/capture/src/v0_endpoint.rs@@ -84,6 +84,7 @@ pub async fn event(state.ingestion_warning_emitter.clone(),events,&context,+ state.ai_byte_rate_limiter.clone(),).await{diff --git a/rust/capture/src/v0_request.rs b/rust/capture/src/v0_request.rsindex 6bd332e767f2..3290fb62b314 100644--- a/rust/capture/src/v0_request.rs+++ b/rust/capture/src/v0_request.rs@@ -149,6 +149,10 @@ pub struct ProcessingContext {/// analytics path: skip the global rate limiter and drop any batch not/// flagged `historical_migration: true`.pub capture_mode: CaptureMode,+ /// Largest AI-lane event this deployment accepts, from+ /// `AI_MAX_EVENT_BYTES`. `0` disables the ceiling. See+ /// [`exceeds_max_ai_event_bytes`].+ pub ai_max_event_bytes: u64,/// SDK identity snapshotted from the batch's first event, for ingestion/// warning attribution. Captured at batch construction because the events/// are typed there; downstream stages hold serialized payloads and would@@ -177,11 +181,10 @@ pub enum DataType {HeatmapMain,ExceptionErrorTracking,SnapshotMain,- /// Dedicated `$ai_*` lane, mirroring v1's `Destination::AiEvents`. Only- /// produced on deployments whose capture mode routes AI events (see- /// `CaptureMode::routes_ai_events`); the kafka sink maps it to- /// `CAPTURE_ANALYTICS_AI_EVENTS_TOPIC`. Like heatmaps and exceptions, AI events never- /// reroute historical.+ /// Dedicated AI lane, mirroring v1's `Destination::AiEvents`. The+ /// kafka sink maps it to `CAPTURE_ANALYTICS_AI_EVENTS_TOPIC`, so every+ /// deployment that accepts AI traffic must configure that topic. Like+ /// heatmaps and exceptions, AI events never reroute historical.AiEvents,}@@ -211,30 +214,42 @@ pub fn is_ai_event(name: &str) -> bool {AI_EVENT_NAMES.contains(&name)}+/// Whether an AI-lane event's body exceeds the deployment's per-event ceiling.+///+/// The ceiling exists because each deployment's AI topic sits on a broker with+/// its own message limit, and the producer's own cap rejects an oversized event+/// only after capture has read and processed the whole request. `0` disables+/// the check.+///+/// `body_bytes` is whatever the calling path can measure cheaply, and the+/// paths differ: v0, OTEL, and the multipart handler pass the serialized+/// event, while v1 passes the properties blob, which dominates an AI event+/// but omits the event name, distinct_id, uuid, timestamp, and their keys.+/// The ceiling is sized with broker headroom well above that difference, so+/// the looser measure still keeps an accepted event under the producer's cap.+pub fn exceeds_max_ai_event_bytes(body_bytes: usize, max: u64) -> bool {+ max != 0 && body_bytes as u64 > max+}+impl DataType {/// Classify an event by its name (and historical-migration flag) into a/// `DataType`. Used by both v0's `process_single_event` and v1's/// `apply_restrictions` so the analytics → exception → heatmap →/// ingestion-warning split stays in one place.///- /// `route_ai_events` reflects the deployment's `CaptureMode::routes_ai_events`,- /// mirroring v1's `destination_for_event_name`: when set, AI events (per- /// [`is_ai_event`]) divert to `AiEvents`, winning over historical (in v1- /// the historical reroute only applies to the analytics-main destination).- /// When unset the mapping keeps AI events on the main/historical lanes.+ /// AI events (per [`is_ai_event`]) divert to `AiEvents` on every+ /// deployment, winning over historical (in v1 the historical reroute only+ /// applies to the analytics-main destination). Mirrors v1's+ /// `destination_for_event_name`.////// `SnapshotMain` is not produced here — replay events arrive on a/// separate endpoint and never flow through analytics processing.- pub fn from_event_name(- event_name: &str,- historical_migration: bool,- route_ai_events: bool,- ) -> Self {+ pub fn from_event_name(event_name: &str, historical_migration: bool) -> Self {match event_name {"$$client_ingestion_warning" => Self::ClientIngestionWarning,"$exception" => Self::ExceptionErrorTracking,"$$heatmap" => Self::HeatmapMain,- _ if route_ai_events && is_ai_event(event_name) => Self::AiEvents,+ _ if is_ai_event(event_name) => Self::AiEvents,_ if historical_migration => Self::AnalyticsHistorical,_ => Self::AnalyticsMain,}@@ -245,11 +260,10 @@ impl DataType {/// don't share Redis-backed restriction config with any other pipeline,/// so they're not subject to `EventRestrictionService` lookups.///- /// `AiEvents` maps to the `ai` restriction pipeline: an event diverted to- /// the AI lane is governed by ai-scoped restrictions, the same slice the- /// dedicated AI endpoints consult. Non-diverted `$ai_*` events classify- /// as `AnalyticsMain` and stay under analytics restrictions. v1 derives- /// the same mapping from `Destination::pipeline`.+ /// `AiEvents` maps to the `ai` restriction pipeline: an event on the AI+ /// lane is governed by ai-scoped restrictions, the same slice the+ /// dedicated AI endpoints consult. v1 derives the same mapping from+ /// `Destination::pipeline`.pub fn pipeline(self) -> Option<Pipeline> {match self {Self::AnalyticsMain | Self::AnalyticsHistorical => Some(Pipeline::Analytics),@@ -358,55 +372,40 @@ mod tests {use super::{CaptureError, Compression, DataType, RawRequest};/// Mirrors v1's `destination_for_event_name` mapping tests: the- /// dedicated-name lanes always win, `$ai_*` diverts only when the route- /// flag is set (beating historical), and everything else falls through to+ /// dedicated-name lanes always win, an allowlisted AI name diverts on every deployment+ /// (beating historical), and everything else falls through to/// main/historical per the batch flag.#[rstest::rstest]- // Dedicated-name lanes are unaffected by both flags.- #[case("$exception", false, false, DataType::ExceptionErrorTracking)]- #[case("$exception", true, true, DataType::ExceptionErrorTracking)]- #[case("$$heatmap", false, false, DataType::HeatmapMain)]- #[case("$$heatmap", true, true, DataType::HeatmapMain)]- #[case(- "$$client_ingestion_warning",- false,- false,- DataType::ClientIngestionWarning- )]- #[case(- "$$client_ingestion_warning",- true,- true,- DataType::ClientIngestionWarning- )]+ // Dedicated-name lanes are unaffected by the historical flag.+ #[case("$exception", false, DataType::ExceptionErrorTracking)]+ #[case("$exception", true, DataType::ExceptionErrorTracking)]+ #[case("$$heatmap", false, DataType::HeatmapMain)]+ #[case("$$heatmap", true, DataType::HeatmapMain)]+ #[case("$$client_ingestion_warning", false, DataType::ClientIngestionWarning)]+ #[case("$$client_ingestion_warning", true, DataType::ClientIngestionWarning)]// Non-AI events keep the main/historical split.- #[case("$pageview", false, false, DataType::AnalyticsMain)]- #[case("$pageview", false, true, DataType::AnalyticsMain)]- #[case("custom_event", false, true, DataType::AnalyticsMain)]- #[case("$pageview", true, false, DataType::AnalyticsHistorical)]- #[case("$pageview", true, true, DataType::AnalyticsHistorical)]- // Allowlisted AI events divert only when AI routing is enabled, and win over historical.- #[case("$ai_generation", false, true, DataType::AiEvents)]- #[case("$ai_span", false, true, DataType::AiEvents)]- #[case("$ai_trace", false, true, DataType::AiEvents)]- #[case("$ai_generation_summary", false, true, DataType::AiEvents)]- #[case("$ai_generation", true, true, DataType::AiEvents)]- #[case("$ai_generation", false, false, DataType::AnalyticsMain)]- #[case("$ai_generation", true, false, DataType::AnalyticsHistorical)]+ #[case("$pageview", false, DataType::AnalyticsMain)]+ #[case("custom_event", false, DataType::AnalyticsMain)]+ #[case("$pageview", true, DataType::AnalyticsHistorical)]+ // Allowlisted AI events divert, and win over historical.+ #[case("$ai_generation", false, DataType::AiEvents)]+ #[case("$ai_span", false, DataType::AiEvents)]+ #[case("$ai_trace", false, DataType::AiEvents)]+ #[case("$ai_generation_summary", false, DataType::AiEvents)]+ #[case("$ai_generation", true, DataType::AiEvents)]// Names matching the $ai_ prefix but absent from the allowlist do NOT divert:// the ingestion AI pipeline would DLQ them, so they stay on the main lane.- #[case("$ai_call", false, true, DataType::AnalyticsMain)]- #[case("$ai_generation_enriched", false, true, DataType::AnalyticsMain)]- #[case("$ai_model_failover", false, true, DataType::AnalyticsMain)]- #[case("$ai_model_failover", true, true, DataType::AnalyticsHistorical)]+ #[case("$ai_call", false, DataType::AnalyticsMain)]+ #[case("$ai_generation_enriched", false, DataType::AnalyticsMain)]+ #[case("$ai_model_failover", false, DataType::AnalyticsMain)]+ #[case("$ai_model_failover", true, DataType::AnalyticsHistorical)]fn from_event_name_mapping(#[case] event_name: &str,#[case] historical_migration: bool,- #[case] route_ai_events: bool,#[case] expected: DataType,) {assert_eq!(- DataType::from_event_name(event_name, historical_migration, route_ai_events),+ DataType::from_event_name(event_name, historical_migration),expected);}diff --git a/rust/capture/src/v1/analytics/constants.rs b/rust/capture/src/v1/analytics/constants.rsindex faa746ca3c8a..00ea08a3494e 100644--- a/rust/capture/src/v1/analytics/constants.rs+++ b/rust/capture/src/v1/analytics/constants.rs@@ -55,6 +55,14 @@ pub(super) const DETAIL_NON_HISTORICAL_DROP: &str = "non_historical_import_drop"/// Detail tag for events dropped due to uncoercible options fields.pub(super) const DETAIL_INVALID_OPTIONS: &str = "invalid_options";+/// Detail tag for AI-lane events dropped because the project is over its+/// byte budget.+pub(super) const DETAIL_AI_BYTE_RATE_LIMITED: &str = "ai_byte_rate_limited";++/// Detail tag for AI-lane events dropped for exceeding the deployment's+/// per-event size ceiling.+pub(super) const DETAIL_AI_EVENT_TOO_BIG: &str = "ai_event_too_big";+// ---------------------------------------------------------------------------// Validation limits// ---------------------------------------------------------------------------diff --git a/rust/capture/src/v1/analytics/process.rs b/rust/capture/src/v1/analytics/process.rsindex c3f2fede3d34..f255029f1292 100644--- a/rust/capture/src/v1/analytics/process.rs+++ b/rust/capture/src/v1/analytics/process.rs@@ -11,15 +11,16 @@ use super::constants::{CAPTURE_V1_EVENTS_REROUTED_HISTORICAL, CAPTURE_V1_EVENTS_RESTRICTED,CAPTURE_V1_EVENT_ADJUSTMENTS_APPLIED, CAPTURE_V1_MAX_EVENT_NAME_LENGTH,CAPTURE_V1_OVERFLOW_ROUTED, CAPTURE_V1_PARSED_EVENTS, CAPTURE_V1_PROCESSING_DURATION_SECONDS,- CAPTURE_V1_RATE_LIMITER, DETAIL_EVENT_RESTRICTION_DROP, DETAIL_INVALID_OPTIONS,- DETAIL_NON_HISTORICAL_DROP, DETAIL_PERSON_PROCESSING_DISABLED, FUTURE_EVENT_HOURS_CUTOFF_MS,- ILLEGAL_DISTINCT_IDS,+ CAPTURE_V1_RATE_LIMITER, DETAIL_AI_BYTE_RATE_LIMITED, DETAIL_AI_EVENT_TOO_BIG,+ DETAIL_EVENT_RESTRICTION_DROP, DETAIL_INVALID_OPTIONS, DETAIL_NON_HISTORICAL_DROP,+ DETAIL_PERSON_PROCESSING_DISABLED, FUTURE_EVENT_HOURS_CUTOFF_MS, ILLEGAL_DISTINCT_IDS,};use super::response::BatchResponse;use super::types::{Batch, Event, EventResult, Options, WrappedEvent};use crate::event_restrictions::{EventContext, EventRestrictionService};+use crate::events::ai_byte_limit::charge_ai_bytes;use crate::global_rate_limiter::{GlobalRateLimitKey, GlobalRateLimiter};-use crate::v0_request::is_ai_event;+use crate::v0_request::{exceeds_max_ai_event_bytes, is_ai_event};use limiters::overflow::{OverflowLimiter, OverflowLimiterResult};use tracing::Level;@@ -43,16 +44,14 @@ use common_ingestion_warnings::{/// (extractHeatmapDataStep) handles extraction when `skip_heatmap_processing` is unset/// in Kafka headers — removing that fallback would break scroll-depth heatmaps for v1.///-/// When `route_ai_events` is set (the deployment's capture mode routes AI-/// events, see `CaptureMode::routes_ai_events`), AI events (per-/// [`is_ai_event`]) are diverted to `Destination::AiEvents`; otherwise they-/// fall through to `AnalyticsMain`.-fn destination_for_event_name(name: &str, route_ai_events: bool) -> Destination {+/// AI events (per [`is_ai_event`]) are diverted to `Destination::AiEvents` on+/// every deployment.+fn destination_for_event_name(name: &str) -> Destination {match name {"$exception" => Destination::ExceptionErrorTracking,"$$heatmap" => Destination::HeatmapMain,"$$client_ingestion_warning" => Destination::ClientIngestionWarning,- _ if route_ai_events && is_ai_event(name) => Destination::AiEvents,+ _ if is_ai_event(name) => Destination::AiEvents,_ => Destination::AnalyticsMain,}}@@ -72,9 +71,7 @@ pub async fn process_batch(}context.set_batch_metadata(&batch);- // Whether `$ai_*` events divert to the AI lane is a deployment property.- let route_ai_events = state.capture_mode.routes_ai_events();- let mut events = match validate_events(context, batch, route_ai_events) {+ let mut events = match validate_events(context, batch) {Ok(events) => events,Err(err) => {emit_batch_abort_warning(state, context, &err, batch_len);@@ -133,6 +130,12 @@ pub async fn process_batch(.await;}+ apply_ai_event_size_limit(state.ai_max_event_bytes, &mut events);++ if let Some(ref limiter) = state.ai_byte_rate_limiter {+ apply_ai_byte_limits(limiter, &context.api_token, &mut events).await;+ }+apply_historical_rerouting(&state.historical_cfg, context, &mut events);// Overflow and global rate limit are independent checks on different axes:@@ -462,11 +465,7 @@ fn validate_batch(batch: &Batch) -> Result<(), Error> {Ok(())}-fn validate_events(- context: &RequestContext,- batch: Batch,- route_ai_events: bool,-) -> Result<Vec<WrappedEvent>, Error> {+fn validate_events(context: &RequestContext, batch: Batch) -> Result<Vec<WrappedEvent>, Error> {let batch_len = batch.batch.len();let mut events: Vec<WrappedEvent> = Vec::with_capacity(batch_len);let mut seen: HashSet<Uuid> = HashSet::with_capacity(batch_len);@@ -486,7 +485,7 @@ fn validate_events());}- let destination = destination_for_event_name(&event.event, route_ai_events);+ let destination = destination_for_event_name(&event.event);match validate_event(&event) {Ok(raw_ts) => {@@ -827,6 +826,96 @@ async fn apply_restrictions(}}+/// Whether this event rides the AI lane, independent of where restrictions+/// have since pointed it.+///+/// Gating on `destination == AiEvents` would exempt exactly the events an+/// operator redirected: `force_overflow` retargets an AI event to+/// `AiEventsOverflow`, which is still the AI lane, and a `redirect_to_topic`+/// or DLQ restriction moves it off `AiEvents` without taking it off the wire.+/// The allowlist is the same source v0 stamps `DataType::AiEvents` from, so+/// both pipelines charge and measure the same set.+fn on_ai_lane(event: &WrappedEvent) -> bool {+ is_ai_event(&event.event.event)+}++/// Drop AI-lane events past the deployment's per-event size ceiling.+///+/// Runs before the byte budget so an event that will never be published spends+/// none of the project's budget. Only the offending event is dropped: v1+/// reports per-event outcomes, so the rest of the batch still publishes and the+/// client learns which event was refused. The legacy path refuses the whole+/// request instead, matching the oversize checks already on it.+///+/// Charged bytes are the event's properties, which dominate an AI event's wire+/// size; the serialized envelope is not built until the sink.+fn apply_ai_event_size_limit(max_event_bytes: u64, events: &mut [WrappedEvent]) {+ if max_event_bytes == 0 {+ return;+ }++ let mut dropped: u64 = 0;++ for event in events.iter_mut() {+ if event.result != EventResult::Ok || !on_ai_lane(event) {+ continue;+ }+ if exceeds_max_ai_event_bytes(event.event.properties.get().len(), max_event_bytes) {+ event.result = EventResult::Drop;+ event.details = Some(DETAIL_AI_EVENT_TOO_BIG);+ event.destination = Destination::Drop;+ dropped += 1;+ }+ }++ if dropped > 0 {+ metrics::counter!(CAPTURE_V1_EVENTS_DROPPED, "reason" => "ai_event_too_big")+ .increment(dropped);+ }+}++/// Charge the AI lane's per-project byte budget, dropping the events that take+/// the project past it. The budget is fleet-wide and shared with the v0 path+/// (`events::ai_byte_limit`), so a token's bytes count once no matter which+/// pipeline carries them.+///+/// Membership comes from the event-name allowlist, not the current+/// destination: a restriction that retargets an AI event still spends the+/// project's bytes, and `force_overflow` keeps it on the AI lane outright. The+/// `EventResult::Ok` guard keeps every upstream drop — validation, quota, a+/// `DropEvent` restriction — off the budget, since none of those bytes were+/// ever going to be published.+///+/// Charged bytes are the event's properties, which dominate an AI event's wire+/// size; `charge_ai_bytes` adds the flat envelope allowance the v0 path uses.+async fn apply_ai_byte_limits(+ limiter: &GlobalRateLimiter,+ token: &str,+ events: &mut [WrappedEvent],+) {+ let mut dropped: u64 = 0;++ for event in events.iter_mut() {+ if event.result != EventResult::Ok || !on_ai_lane(event) {+ continue;+ }+ if charge_ai_bytes(limiter, token, event.event.properties.get().len()).await {+ event.result = EventResult::Drop;+ event.details = Some(DETAIL_AI_BYTE_RATE_LIMITED);+ event.destination = Destination::Drop;+ dropped += 1;+ }+ }++ if dropped > 0 {+ // Same label value as the legacy path's+ // capture_events_dropped_total{cause=...} so one alert expression+ // covers both metric names.+ metrics::counter!(CAPTURE_V1_EVENTS_DROPPED, "reason" => "ai_byte_rate_limited")+ .increment(dropped);+ }+}+/// Per-batch tally of how the shared global rate limiter classified each/// evaluated event. All three fields count events (not distinct_ids), so/// `allowed + limited + already_disabled` equals the number of non-Drop events@@ -1258,7 +1347,7 @@ mod tests {let normal = valid_event();let normal_uuid = Uuid::parse_str(&normal.uuid).unwrap();let batch = valid_batch(vec![perf, normal]);- let events = validate_events(&ctx, batch, false).unwrap();+ let events = validate_events(&ctx, batch).unwrap();assert_eq!(events.len(), 2);// Vec preserves input order: perf first, normal second.let p = &events[0];@@ -1282,7 +1371,7 @@ mod tests {..valid_event()};let batch = valid_batch(vec![p1, p2]);- let events = validate_events(&ctx, batch, false).unwrap();+ let events = validate_events(&ctx, batch).unwrap();assert_eq!(events.len(), 2);for ev in &events {assert_eq!(ev.result, EventResult::Drop);@@ -1298,7 +1387,7 @@ mod tests {illegal_event.distinct_id = id.to_string();let legal_event = valid_event();let batch = valid_batch(vec![illegal_event, legal_event]);- let events = validate_events(&ctx, batch, false).unwrap();+ let events = validate_events(&ctx, batch).unwrap();assert_eq!(events.len(), 2, "id={id:?}");let flagged = &events[0];@@ -1323,7 +1412,7 @@ mod tests {let ctx = test_utils::test_context();let event = deserialized_event(&Uuid::new_v4().to_string(), " NULL ");let batch = valid_batch(vec![event]);- let events = validate_events(&ctx, batch, false).unwrap();+ let events = validate_events(&ctx, batch).unwrap();assert_eq!(events[0].result, EventResult::Ok);assert!(events[0].force_disable_person_processing);assert_eq!(events[0].details, Some(DETAIL_PERSON_PROCESSING_DISABLED));@@ -1336,7 +1425,7 @@ mod tests {let mut illegal_event = valid_event();illegal_event.distinct_id = id.to_string();let batch = valid_batch(vec![illegal_event]);- let events = validate_events(&ctx, batch, false).unwrap();+ let events = validate_events(&ctx, batch).unwrap();assert_eq!(events.len(), 1, "id={id:?}");assert!(events[0].should_publish(), "id={id:?}");}@@ -1363,7 +1452,7 @@ mod tests {},],};- let err = validate_events(&ctx, batch, false).unwrap_err();+ let err = validate_events(&ctx, batch).unwrap_err();assert!(matches!(err, Error::DuplicateEventUuid(_)));}@@ -1379,7 +1468,7 @@ mod tests {..valid_event()}],};- let err = validate_events(&ctx, batch, false).unwrap_err();+ let err = validate_events(&ctx, batch).unwrap_err();assert!(matches!(err, Error::InvalidEventUuid(_)));}@@ -1395,7 +1484,7 @@ mod tests {..valid_event()}],};- let err = validate_events(&ctx, batch, false).unwrap_err();+ let err = validate_events(&ctx, batch).unwrap_err();assert!(matches!(err, Error::MissingEventUuid));}@@ -1427,7 +1516,7 @@ mod tests {let count = dropped_count("duplicate_event_uuid", "validation_abort", || {assert!(matches!(- validate_events(&ctx, batch, false).unwrap_err(),+ validate_events(&ctx, batch).unwrap_err(),Error::DuplicateEventUuid(_)));});@@ -1449,7 +1538,7 @@ mod tests {let count = dropped_count("invalid_event_uuid", "validation_abort", || {assert!(matches!(- validate_events(&ctx, batch, false).unwrap_err(),+ validate_events(&ctx, batch).unwrap_err(),Error::InvalidEventUuid(_)));});@@ -1469,7 +1558,7 @@ mod tests {let count = dropped_count("missing_event_uuid", "validation_abort", || {assert!(matches!(- validate_events(&ctx, batch, false).unwrap_err(),+ validate_events(&ctx, batch).unwrap_err(),Error::MissingEventUuid));});@@ -1517,7 +1606,7 @@ mod tests {let event = deserialized_event(&padded_uuid, "user-42");assert_eq!(event.uuid, inner_uuid.to_string());let batch = valid_batch(vec![event]);- let events = validate_events(&ctx, batch, false).unwrap();+ let events = validate_events(&ctx, batch).unwrap();assert_eq!(events.len(), 1);assert_eq!(events[0].uuid, inner_uuid);}@@ -1536,7 +1625,7 @@ mod tests {capture_internal: None,batch: vec![bad_event],};- let events = validate_events(&ctx, batch, false).unwrap();+ let events = validate_events(&ctx, batch).unwrap();assert_eq!(events.len(), 1);let event = &events[0];assert_eq!(event.uuid, uuid);@@ -1562,7 +1651,7 @@ mod tests {capture_internal: None,batch: vec![good, bad],};- let events = validate_events(&ctx, batch, false).unwrap();+ let events = validate_events(&ctx, batch).unwrap();assert_eq!(events.len(), 2);assert_eq!(events[0].result, EventResult::Ok);@@ -1591,7 +1680,7 @@ mod tests {capture_internal: None,batch: vec![ev1, ev2],};- let result = validate_events(&ctx, batch, false);+ let result = validate_events(&ctx, batch);assert!(result.is_ok());let events = result.unwrap();assert_eq!(events[0].result, EventResult::Drop);@@ -1613,7 +1702,7 @@ mod tests {capture_internal: None,batch: vec![ev],};- let events = validate_events(&ctx, batch, false).unwrap();+ let events = validate_events(&ctx, batch).unwrap();assert_eq!(events[0].result, EventResult::Ok);assert_eq!(events[0].options.disable_skew_correction, Some(true));}@@ -1637,7 +1726,7 @@ mod tests {capture_internal: None,batch: vec![ev],};- let events = validate_events(&ctx, batch, false).unwrap();+ let events = validate_events(&ctx, batch).unwrap();assert_eq!(events[0].result, EventResult::Drop);assert_eq!(events[0].details, Some("missing_event_name"));}@@ -1892,6 +1981,150 @@ mod tests {assert_eq!(ev.destination, expected_destination);}+ /// An AI event past the ceiling is dropped on its own: v1 reports per-event+ /// outcomes, so the rest of the batch still publishes and the client is told+ /// which event was refused. The legacy path refuses the whole request+ /// instead, matching each pipeline's own convention.+ #[tokio::test]+ async fn oversize_ai_events_drop_individually() {+ let mut oversized = wrapped_event("$ai_generation", "user-big");+ oversized.destination = Destination::AiEvents;+ oversized.event.properties =+ test_utils::raw_obj(&format!(r#"{{"$ai_input":"{}"}}"#, "x".repeat(800)));++ let mut small = wrapped_event("$ai_generation", "user-1");+ small.destination = Destination::AiEvents;++ let mut events = vec![oversized, small];++ apply_ai_event_size_limit(700, &mut events);++ let big = find_by_did(&events, "user-big");+ assert_eq!(big.result, EventResult::Drop);+ assert_eq!(big.destination, Destination::Drop);+ assert_eq!(big.details, Some(DETAIL_AI_EVENT_TOO_BIG));++ let kept = find_by_did(&events, "user-1");+ assert_eq!(+ kept.result,+ EventResult::Ok,+ "one oversize event must not take the rest of the batch with it"+ );+ }++ /// 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");+ oversized.destination = Destination::AiEvents;+ oversized.event.properties =+ test_utils::raw_obj(&format!(r#"{{"$ai_input":"{}"}}"#, "x".repeat(800)));++ let mut events = vec![oversized];+ apply_ai_event_size_limit(0, &mut events);++ assert_eq!(events[0].result, EventResult::Ok);+ assert_eq!(events[0].destination, Destination::AiEvents);+ }++ /// The size ceiling follows the same lane rule as the budget: an oversize+ /// AI event a restriction retargeted is still refused, because the ceiling+ /// exists to keep the producer from being handed something it will reject.+ #[tokio::test]+ async fn ai_size_ceiling_follows_the_lane_not_the_destination() {+ let mut oversized = wrapped_event("$ai_generation", "user-1");+ oversized.event.properties =+ test_utils::raw_obj(&format!(r#"{{"$ai_input":"{}"}}"#, "x".repeat(800)));+ oversized.destination = Destination::AiEventsOverflow;++ let mut events = vec![oversized];+ apply_ai_event_size_limit(700, &mut events);++ assert_eq!(events[0].result, EventResult::Drop);+ assert_eq!(events[0].destination, Destination::Drop);+ }++ /// Lane membership decides the charge, and a restriction that retargets an+ /// AI event does not buy the project a free lane. `force_overflow` keeps+ /// the event on the AI lane outright; a topic or DLQ redirect moves it off+ /// `AiEvents` but not off the wire. Gating on the destination instead would+ /// exempt every one of these, which is the whole point of the case list.+ #[rstest::rstest]+ #[case::ai_lane(Destination::AiEvents)]+ #[case::force_overflow_stays_on_the_lane(Destination::AiEventsOverflow)]+ #[case::topic_redirect_still_pays(Destination::Custom("ai_quarantine".to_string()))]+ #[case::dlq_redirect_still_pays(Destination::Dlq)]+ #[tokio::test]+ async fn ai_byte_limits_follow_the_lane_not_the_destination(#[case] destination: Destination) {+ // Each event weighs the flat envelope allowance plus its two-byte+ // properties, so one fits an 800-byte budget and the second does not.+ let limiter = GlobalRateLimiter::mock_budget(800);++ let mut events = vec![+ wrapped_event("$ai_generation", "user-1"),+ wrapped_event("$ai_generation", "user-2"),+ ];+ for event in events.iter_mut() {+ event.destination = destination.clone();+ }++ apply_ai_byte_limits(&limiter, "phc_token", &mut events).await;++ assert_eq!(events[0].result, EventResult::Ok);+ assert_eq!(events[0].destination, destination);+ assert_eq!(events[1].result, EventResult::Drop);+ assert_eq!(events[1].destination, Destination::Drop);+ }++ /// The mirror of the case above: an event that was never on the AI lane is+ /// never charged, however far over budget the project already is.+ #[tokio::test]+ async fn non_ai_events_are_never_charged() {+ let limiter = GlobalRateLimiter::mock_budget(1);++ let mut events = vec![+ wrapped_event("$pageview", "user-1"),+ wrapped_event("$pageview", "user-2"),+ ];++ apply_ai_byte_limits(&limiter, "phc_token", &mut events).await;++ for event in &events {+ assert_eq!(event.result, EventResult::Ok);+ assert_eq!(event.destination, Destination::AnalyticsMain);+ }+ }++ /// An event already dropped upstream keeps its destination on some paths —+ /// a validation drop is `Drop` on the AI lane — so the `Ok` guard is what+ /// keeps those bytes off the budget, leaving room for the events that+ /// still have somewhere to go.+ #[tokio::test]+ async fn ai_byte_limits_skip_events_dropped_upstream() {+ let limiter = GlobalRateLimiter::mock_budget(800);++ let mut already_dropped = wrapped_event("$ai_generation", "user-invalid");+ already_dropped.destination = Destination::AiEvents;+ already_dropped.result = EventResult::Drop;+ already_dropped.details = Some(DETAIL_INVALID_OPTIONS);++ let mut publishable = wrapped_event("$ai_generation", "user-1");+ publishable.destination = Destination::AiEvents;++ let mut events = vec![already_dropped, publishable];++ apply_ai_byte_limits(&limiter, "phc_token", &mut events).await;++ let ev = find_by_did(&events, "user-1");+ assert_eq!(+ ev.result,+ EventResult::Ok,+ "a dropped event's bytes must not shed a publishable one"+ );+ assert_eq!(ev.destination, Destination::AiEvents);+ }+#[tokio::test]async fn restrictions_redirect_to_dlq() {let service = restriction_service(@@ -2021,45 +2254,24 @@ mod tests {// --- destination_for_event_name ---#[rstest::rstest]- // Non-AI mappings are identical regardless of the AI routing flag.- #[case("$exception", false, Destination::ExceptionErrorTracking)]- #[case("$exception", true, Destination::ExceptionErrorTracking)]- #[case("$$heatmap", false, Destination::HeatmapMain)]- #[case("$$heatmap", true, Destination::HeatmapMain)]- #[case(- "$$client_ingestion_warning",- false,- Destination::ClientIngestionWarning- )]- #[case(- "$$client_ingestion_warning",- true,- Destination::ClientIngestionWarning- )]- #[case("$pageview", false, Destination::AnalyticsMain)]- #[case("$pageview", true, Destination::AnalyticsMain)]- #[case("custom_event", false, Destination::AnalyticsMain)]- #[case("$autocapture", false, Destination::AnalyticsMain)]- // Allowlisted AI events divert only when AI routing is enabled; otherwise stay on Main.- #[case("$ai_generation", true, Destination::AiEvents)]- #[case("$ai_span", true, Destination::AiEvents)]- #[case("$ai_trace", true, Destination::AiEvents)]- #[case("$ai_generation_summary", true, Destination::AiEvents)]- #[case("$ai_generation", false, Destination::AnalyticsMain)]+ #[case("$exception", Destination::ExceptionErrorTracking)]+ #[case("$$heatmap", Destination::HeatmapMain)]+ #[case("$$client_ingestion_warning", Destination::ClientIngestionWarning)]+ #[case("$pageview", Destination::AnalyticsMain)]+ #[case("custom_event", Destination::AnalyticsMain)]+ #[case("$autocapture", Destination::AnalyticsMain)]+ // Allowlisted AI events divert on every deployment.+ #[case("$ai_generation", Destination::AiEvents)]+ #[case("$ai_span", Destination::AiEvents)]+ #[case("$ai_trace", Destination::AiEvents)]+ #[case("$ai_generation_summary", Destination::AiEvents)]// $ai_ prefixed names absent from the allowlist stay on Main so the// ingestion AI pipeline doesn't DLQ them.- #[case("$ai_call", true, Destination::AnalyticsMain)]- #[case("$ai_generation_enriched", true, Destination::AnalyticsMain)]- #[case("$ai_model_failover", true, Destination::AnalyticsMain)]- fn destination_for_event_name_mapping(- #[case] event_name: &str,- #[case] route_ai_events: bool,- #[case] expected: Destination,- ) {- assert_eq!(- destination_for_event_name(event_name, route_ai_events),- expected- );+ #[case("$ai_call", Destination::AnalyticsMain)]+ #[case("$ai_generation_enriched", Destination::AnalyticsMain)]+ #[case("$ai_model_failover", Destination::AnalyticsMain)]+ fn destination_for_event_name_mapping(#[case] event_name: &str, #[case] expected: Destination) {+ assert_eq!(destination_for_event_name(event_name), expected);}// --- restrictions bypass pipeline-less events ---@@ -2907,7 +3119,7 @@ mod tests {};let batch = valid_batch(vec![normal_a, perf, normal_b, normal_c]);- let events = validate_events(&ctx, batch, false).unwrap();+ let events = validate_events(&ctx, batch).unwrap();assert_eq!(distinct_id_sequence(&events),@@ -2921,7 +3133,7 @@ mod tests {let ctx = test_utils::test_context();let (first, second) = test_utils::realistic_dup_uuid_pair();let batch = valid_batch(vec![first, second]);- let err = validate_events(&ctx, batch, false).unwrap_err();+ let err = validate_events(&ctx, batch).unwrap_err();assert!(matches!(err, Error::DuplicateEventUuid(_)));}@@ -3624,7 +3836,7 @@ mod tests {});}- /// process_batch wiring: an `$ai_*` event lands on the AI topic.+ /// process_batch wiring: an allowlisted AI event lands on the AI topic.#[tokio::test]async fn process_batch_routes_ai_events_to_ai_topic() {let ts = TestStateBuilder::new().build();@@ -3644,7 +3856,7 @@ mod tests {/// 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+ /// 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).@@ -3680,6 +3892,42 @@ mod tests {});}+ /// process_batch wiring: the AI byte budget runs in the v1 pipeline too, so+ /// a project past its budget stops reaching the AI topic while its+ /// analytics events are untouched.+ #[tokio::test]+ async fn process_batch_enforces_the_ai_byte_budget() {+ // The flat envelope allowance alone puts two events past an 800-byte+ // budget, so the first AI event fits and the second does not.+ let ts = TestStateBuilder::new()+ .with_ai_byte_rate_limiter(Arc::new(GlobalRateLimiter::mock_budget(800)))+ .build();+ let mut ctx = test_utils::test_analytics_context();+ let batch = valid_batch(vec![+ Event {+ event: "$ai_generation".to_string(),+ ..valid_event()+ },+ Event {+ event: "$ai_generation".to_string(),+ ..valid_event()+ },+ valid_event(),+ ]);++ process_batch(&ts.state, &mut ctx, batch).await.unwrap();++ ts.mock_producer.with_records(|records| {+ let mut topics: Vec<&str> = records.iter().map(|r| r.topic.as_str()).collect();+ topics.sort_unstable();+ assert_eq!(+ topics,+ vec!["ai_events", "events_main"],+ "the over-budget AI event must not reach the sink, and the analytics event must be untouched"+ );+ });+ }+// =========================================================================// merge_sink_results tests// =========================================================================@@ -3981,7 +4229,7 @@ mod tests {async fn import_mode_historical_batch_never_overflows() {// Import's no-overflow guarantee on the v1 path. Non-AI events in a// historical batch reroute to AnalyticsHistorical before overflow- // stamping (which only touches AnalyticsMain), and $ai_* events divert+ // stamping (which only touches AnalyticsMain), and AI events divert// to the AI lane, which cannot stamp overflow while the AI overflow// valve is unset — the capture-import config. Even with the burst// overflow limiter armed at burst=1 and all three events sharing one@@ -4024,7 +4272,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+ // 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-overflowdiff --git a/rust/capture/src/v1/quota_limiter_shim.rs b/rust/capture/src/v1/quota_limiter_shim.rsindex 6f9b67809147..aefc96cfb7c4 100644--- a/rust/capture/src/v1/quota_limiter_shim.rs+++ b/rust/capture/src/v1/quota_limiter_shim.rs@@ -242,6 +242,7 @@ mod tests {s3_fallback_endpoint: None,s3_fallback_prefix: String::new(),ai_max_sum_of_parts_bytes: 26_214_400,+ ai_max_event_bytes: 8_388_608,ai_gateway_signing_secret: None,http1_header_read_timeout_ms: Some(5000),body_chunk_read_timeout_ms: None,@@ -257,6 +258,10 @@ mod tests {capture_ingestion_warnings_kafka_topic: String::new(),capture_ingestion_warnings_kafka_hosts: String::new(),capture_ingestion_warnings_kafka_tls: false,+ ai_byte_limit_per_second: 0,+ ai_byte_limit_overrides_csv: None,+ ai_byte_limit_dry_run: false,+ ai_byte_limit_local_cache_max_entries: 300_000,}}diff --git a/rust/capture/src/v1/test_utils.rs b/rust/capture/src/v1/test_utils.rsindex 012b89c58da8..ad8620cbb196 100644--- a/rust/capture/src/v1/test_utils.rs+++ b/rust/capture/src/v1/test_utils.rs@@ -701,6 +701,7 @@ pub struct TestStateBuilder {historical_threshold_days: Option<i64>,restriction_service: Option<EventRestrictionService>,global_rate_limiter: Option<Arc<GlobalRateLimiter>>,+ ai_byte_rate_limiter: Option<Arc<GlobalRateLimiter>>,mock_producer: Option<Arc<MockProducer>>,ai_gateway_signing_secret: Option<String>,ingestion_warning_emitter: Option<Arc<dyn common_ingestion_warnings::WarningEmitter>>,@@ -724,6 +725,7 @@ impl TestStateBuilder {historical_threshold_days: None,restriction_service: None,global_rate_limiter: None,+ ai_byte_rate_limiter: None,mock_producer: None,ai_gateway_signing_secret: None,ingestion_warning_emitter: None,@@ -795,6 +797,12 @@ impl TestStateBuilder {self}+ /// Add the AI lane's byte-budget limiter.+ pub fn with_ai_byte_rate_limiter(mut self, limiter: Arc<GlobalRateLimiter>) -> Self {+ self.ai_byte_rate_limiter = Some(limiter);+ self+ }+/// Supply a pre-configured MockProducer (e.g. for error injection).pub fn with_mock_producer(mut self, producer: Arc<MockProducer>) -> Self {self.mock_producer = Some(producer);@@ -925,12 +933,14 @@ impl TestStateBuilder {is_mirror_deploy: false,verbose_sample_percent: 0.0,ai_max_sum_of_parts_bytes: 100 * 1024 * 1024,+ ai_max_event_bytes: 0,body_chunk_read_timeout: None,body_read_chunk_size_kb: 64,capture_v1_max_compressed_body_bytes: 2 * 1024 * 1024,capture_v1_max_decompressed_body_bytes: 20 * 1024 * 1024,overflow_limiter,ai_events_overflow_limiter,+ ai_byte_rate_limiter: self.ai_byte_rate_limiter,replay_overflow_limiter: None,v1_sink_router: Some(Arc::new(v1_router)),capture_v1_scatter_gather_min_batch: 8,diff --git a/rust/capture/tests/common/integration_utils.rs b/rust/capture/tests/common/integration_utils.rsindex 1a8164f210f2..8f29b604d8e5 100644--- a/rust/capture/tests/common/integration_utils.rs+++ b/rust/capture/tests/common/integration_utils.rs@@ -1110,12 +1110,14 @@ fn build_router_for_mode_at(mode: CaptureMode, fixed_time: &str) -> (Router, Memis_mirror_deploy,verbose_sample_percent,26_214_400, // 25MB default for AI endpoint+ 983_040, // ai_max_event_bytes (960KB, the previous hardcoded limit)None, // body_chunk_read_timeout_ms256, // body_read_chunk_size_kb10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytesNone, // overflow_limiterNone, // ai_events_overflow_limiter+ None, // ai_byte_rate_limiterNone, // replay_overflow_limiterNone, // v1_sink_router8, // capture_v1_scatter_gather_min_batchdiff --git a/rust/capture/tests/common/utils.rs b/rust/capture/tests/common/utils.rsindex f1e51ab3f31b..f6cdcda83d73 100644--- a/rust/capture/tests/common/utils.rs+++ b/rust/capture/tests/common/utils.rs@@ -160,6 +160,7 @@ pub static DEFAULT_CONFIG: Lazy<Config> = Lazy::new(|| Config {s3_fallback_endpoint: None,s3_fallback_prefix: String::new(),ai_max_sum_of_parts_bytes: 26_214_400, // 25MB default+ ai_max_event_bytes: 8_388_608, // 8MiB defaultai_gateway_signing_secret: None,http1_header_read_timeout_ms: Some(5000), // 5 seconds defaultbody_chunk_read_timeout_ms: None, // disabled by default in tests@@ -175,6 +176,10 @@ pub static DEFAULT_CONFIG: Lazy<Config> = Lazy::new(|| Config {capture_ingestion_warnings_kafka_topic: String::new(),capture_ingestion_warnings_kafka_hosts: String::new(),capture_ingestion_warnings_kafka_tls: false,+ ai_byte_limit_per_second: 0,+ ai_byte_limit_overrides_csv: None,+ ai_byte_limit_dry_run: false,+ ai_byte_limit_local_cache_max_entries: 300_000,});/// Build the per-sink env snapshot the v1 sink loader expects, with every@@ -304,7 +309,7 @@ impl ServerHandle {let mut config = DEFAULT_CONFIG.clone();config.capture_v1_sinks = "msk".to_string();config.ai_gateway_signing_secret = Some(secret.to_string());- // The gateway tests send `$ai_*` events, which route to the AI topic;+ // The gateway tests send AI events, which route to the AI topic;// point it at the same ephemeral topic so the consumer sees them.config.kafka.capture_analytics_ai_events_topic = topic.topic_name().to_string();let sink_env = v1_sink_env_for_topic("msk", topic.topic_name());diff --git a/rust/capture/tests/integration_ai_endpoint.rs b/rust/capture/tests/integration_ai_endpoint.rsindex 465c96f1103f..a4ec1438792f 100644--- a/rust/capture/tests/integration_ai_endpoint.rs+++ b/rust/capture/tests/integration_ai_endpoint.rs@@ -7,6 +7,7 @@ use axum::Router;use axum_test_helper::TestClient;use capture::api::CaptureError;use capture::config::CaptureMode;+use capture::global_rate_limiter::GlobalRateLimiter;use capture::quota_limiters::CaptureQuotaLimiter;use capture::router::router;use capture::sinks::Event;@@ -152,7 +153,7 @@ fn setup_ai_test_router() -> Router {let redis = Arc::new(MockRedisClient::new());let mut cfg = DEFAULT_CONFIG.clone();- cfg.capture_mode = CaptureMode::Events;+ cfg.capture_mode = CaptureMode::Ai;let quota_limiter =CaptureQuotaLimiter::new(&cfg, redis.clone(), Duration::from_secs(60 * 60 * 24 * 7));@@ -168,7 +169,7 @@ fn setup_ai_test_router() -> Router {TokenDropper::default(),None, // event_restriction_serviceNone, // recorder_handle- CaptureMode::Events,+ CaptureMode::Ai,None,25 * 1024 * 1024,false,@@ -176,12 +177,14 @@ 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)None, // body_chunk_read_timeout_ms256, // body_read_chunk_size_kb10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytesNone, // overflow_limiterNone, // ai_events_overflow_limiter+ None, // ai_byte_rate_limiterNone, // replay_overflow_limiterNone, // v1_sink_router8, // capture_v1_scatter_gather_min_batch@@ -204,7 +207,7 @@ fn setup_ai_router_collecting_warnings() -> (Router, Arc<CollectingEmitter>) {let redis = Arc::new(MockRedisClient::new());let mut cfg = DEFAULT_CONFIG.clone();- cfg.capture_mode = CaptureMode::Events;+ cfg.capture_mode = CaptureMode::Ai;let quota_limiter =CaptureQuotaLimiter::new(&cfg, redis.clone(), Duration::from_secs(60 * 60 * 24 * 7));@@ -223,7 +226,7 @@ fn setup_ai_router_collecting_warnings() -> (Router, Arc<CollectingEmitter>) {TokenDropper::default(),None, // event_restriction_serviceNone, // recorder_handle- CaptureMode::Events,+ CaptureMode::Ai,None,25 * 1024 * 1024,false,@@ -231,12 +234,14 @@ 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)None,256,10 * 1024 * 1024,50 * 1024 * 1024,None,None,+ None, // ai_byte_rate_limiterNone,None,8,@@ -1275,7 +1280,7 @@ fn setup_ai_test_router_with_capturing_sink() -> (Router, CapturingSink) {let redis = Arc::new(MockRedisClient::new());let mut cfg = DEFAULT_CONFIG.clone();- cfg.capture_mode = CaptureMode::Events;+ cfg.capture_mode = CaptureMode::Ai;let quota_limiter =CaptureQuotaLimiter::new(&cfg, redis.clone(), Duration::from_secs(60 * 60 * 24 * 7));@@ -1291,7 +1296,7 @@ fn setup_ai_test_router_with_capturing_sink() -> (Router, CapturingSink) {TokenDropper::default(),None, // event_restriction_serviceNone, // recorder_handle- CaptureMode::Events,+ CaptureMode::Ai,None,25 * 1024 * 1024,false,@@ -1299,12 +1304,14 @@ 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)None, // body_chunk_read_timeout_ms256, // body_read_chunk_size_kb10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytesNone, // overflow_limiterNone, // ai_events_overflow_limiter+ None, // ai_byte_rate_limiterNone, // replay_overflow_limiterNone, // v1_sink_router8, // capture_v1_scatter_gather_min_batch@@ -1943,7 +1950,7 @@ fn setup_ai_test_router_with_token_dropper(token_dropper: TokenDropper) -> (Routlet redis = Arc::new(MockRedisClient::new());let mut cfg = DEFAULT_CONFIG.clone();- cfg.capture_mode = CaptureMode::Events;+ cfg.capture_mode = CaptureMode::Ai;let quota_limiter =CaptureQuotaLimiter::new(&cfg, redis.clone(), Duration::from_secs(60 * 60 * 24 * 7));@@ -1959,7 +1966,7 @@ fn setup_ai_test_router_with_token_dropper(token_dropper: TokenDropper) -> (Routtoken_dropper,None, // event_restriction_serviceNone, // recorder_handle- CaptureMode::Events,+ CaptureMode::Ai,None, // concurrency_limit25 * 1024 * 1024, // event_size_limitfalse, // enable_historical_rerouting@@ -1967,12 +1974,14 @@ fn setup_ai_test_router_with_token_dropper(token_dropper: TokenDropper) -> (Routfalse, // is_mirror_deploy0.0, // verbose_sample_percent26_214_400, // ai_max_sum_of_parts_bytes+ 983_040, // ai_max_event_bytes (960KB, the previous hardcoded limit)None, // body_chunk_read_timeout_ms256, // body_read_chunk_size_kb10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytesNone, // overflow_limiterNone, // ai_events_overflow_limiter+ None, // ai_byte_rate_limiterNone, // replay_overflow_limiterNone, // v1_sink_router8, // capture_v1_scatter_gather_min_batch@@ -1984,6 +1993,123 @@ fn setup_ai_test_router_with_token_dropper(token_dropper: TokenDropper) -> (Rout(router, sink_clone)}+/// A real limiter whose local cache admits a key's first charge and limits+/// every one after it. A threshold of `0` is what makes the second charge+/// exceed the window with no Redis round trip and no clock, the same seam+/// `integration_person_processing_matrix` uses for the event limiter; the tick+/// is parked well past the requests so no background sync can race them.+fn setup_ai_test_router_with_byte_limiter() -> (Router, CapturingSink) {+ let (readiness, liveness, _monitor) = test_lifecycle_handlers();++ let sink = CapturingSink::new();+ let sink_clone = sink.clone();+ let timesource = FixedTime {+ time: DateTime::parse_from_rfc3339(DEFAULT_TEST_TIME)+ .expect("Invalid fixed time format")+ .with_timezone(&Utc),+ };+ let redis = Arc::new(MockRedisClient::new());++ let mut cfg = DEFAULT_CONFIG.clone();+ cfg.capture_mode = CaptureMode::Ai;+ cfg.ai_byte_limit_per_second = 0;+ cfg.global_rate_limit_tick_interval_ms = 600_000;++ let quota_limiter =+ CaptureQuotaLimiter::new(&cfg, redis.clone(), Duration::from_secs(60 * 60 * 24 * 7));+ let byte_limiter = Arc::new(+ GlobalRateLimiter::new_ai_bytes(&cfg, vec![redis.clone()])+ .expect("failed to build the AI byte limiter"),+ );++ let router = router(+ timesource,+ readiness,+ liveness,+ Arc::new(sink),+ redis,+ None,+ quota_limiter,+ TokenDropper::default(),+ None, // event_restriction_service+ None, // recorder_handle+ CaptureMode::Ai,+ None, // concurrency_limit+ 25 * 1024 * 1024, // event_size_limit+ false, // enable_historical_rerouting+ 1, // historical_rerouting_threshold_days+ false, // is_mirror_deploy+ 0.0, // verbose_sample_percent+ 26_214_400, // ai_max_sum_of_parts_bytes+ 983_040, // ai_max_event_bytes (960KB, the previous hardcoded limit)+ None, // body_chunk_read_timeout_ms+ 256, // body_read_chunk_size_kb+ 10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes+ 50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytes+ None, // overflow_limiter+ None, // ai_events_overflow_limiter+ Some(byte_limiter),+ None, // replay_overflow_limiter+ None, // v1_sink_router+ 8, // capture_v1_scatter_gather_min_batch+ None, // ai_gateway_signing_secret+ false, // ai_events_overflow_enabled+ None, // ingestion_warning_emitter+ );++ (router, sink_clone)+}++/// The byte budget reaches this endpoint. It builds its event at the handler and+/// never enters either analytics pipeline, so the charge has to be wired here or+/// a sender could spend unbounded bytes on `/i/v0/ai` while the same bytes are+/// capped on `/i/v0/ai/batch`.+///+/// An over-budget event answers 200 with no accepted parts, the shape this+/// handler already uses for the token dropper and for a `DropEvent` restriction:+/// a rate drop is ops-imposed and never surfaces as a request failure.+#[tokio::test]+async fn test_ai_endpoint_byte_budget_drops_the_over_budget_event() {+ let (router, sink) = setup_ai_test_router_with_byte_limiter();+ let test_client = TestClient::new(router);+ let token = "phc_VXRzc3poSG9GZm1JenRianJ6TTJFZGh4OWY2QXzx9f3";++ let send = async |client: &TestClient| {+ let form =+ create_ai_event_form("$ai_generation", "test_user", json!({"$ai_model": "gpt-4"}));+ send_multipart_request(client, form, Some(token)).await+ };++ // The limiter reads a cache miss as no prior data and fails open, so the+ // first event for a token is always admitted.+ let first = send(&test_client).await;+ assert_eq!(first.status(), StatusCode::OK);+ let accepted: serde_json::Value = first.json().await;+ assert!(+ !accepted["accepted_parts"].as_array().unwrap().is_empty(),+ "the first event is admitted and reports the parts it took"+ );+ assert_eq!(sink.get_events().await.len(), 1);++ let second = send(&test_client).await;+ assert_eq!(+ second.status(),+ StatusCode::OK,+ "a rate drop is not a request failure"+ );+ let refused: serde_json::Value = second.json().await;+ assert_eq!(+ refused["accepted_parts"].as_array().unwrap().len(),+ 0,+ "an over-budget event reports that nothing was accepted"+ );+ assert_eq!(+ sink.get_events().await.len(),+ 1,+ "the over-budget event must not reach the sink"+ );+}+#[tokio::test]async fn test_ai_endpoint_token_dropper_drops_matching_token() {// Configure token dropper to drop all events for a specific token@@ -2154,7 +2280,7 @@ fn setup_ai_test_router_with_llm_quota_limited(token: &str) -> (Router, CapturinArc::new(MockRedisClient::new().zrangebyscore_ret(&llm_key, vec![token.to_string()]));let mut cfg = DEFAULT_CONFIG.clone();- cfg.capture_mode = CaptureMode::Events;+ cfg.capture_mode = CaptureMode::Ai;let quota_limiter = CaptureQuotaLimiter::new(&cfg, redis.clone(), Duration::from_secs(60)).add_scoped_limiter(QuotaResource::LLMEvents, is_llm_event);@@ -2170,7 +2296,7 @@ fn setup_ai_test_router_with_llm_quota_limited(token: &str) -> (Router, CapturinTokenDropper::default(),None, // event_restriction_serviceNone, // recorder_handle- CaptureMode::Events,+ CaptureMode::Ai,None,25 * 1024 * 1024,false,@@ -2178,12 +2304,14 @@ fn setup_ai_test_router_with_llm_quota_limited(token: &str) -> (Router, Capturinfalse,0.0_f32,26_214_400,+ 983_040, // ai_max_event_bytes (960KB, the previous hardcoded limit)None, // body_chunk_read_timeout_ms256, // body_read_chunk_size_kb10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytesNone, // overflow_limiterNone, // ai_events_overflow_limiter+ None, // ai_byte_rate_limiterNone, // replay_overflow_limiterNone, // v1_sink_router8, // capture_v1_scatter_gather_min_batch@@ -2293,10 +2421,11 @@ async fn test_ai_endpoint_quota_limiter_returns_billing_limit_error_message() {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. Existing helpers still pass `None`; this+/// `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.fn setup_ai_test_router_with_overflow_limiter(- overflow_limiter: Arc<OverflowLimiter>,+ ai_events_overflow_limiter: Arc<OverflowLimiter>,) -> (Router, CapturingSink) {let (readiness, liveness, _monitor) = test_lifecycle_handlers();@@ -2310,7 +2439,7 @@ fn setup_ai_test_router_with_overflow_limiter(let redis = Arc::new(MockRedisClient::new());let mut cfg = DEFAULT_CONFIG.clone();- cfg.capture_mode = CaptureMode::Events;+ cfg.capture_mode = CaptureMode::Ai;let quota_limiter =CaptureQuotaLimiter::new(&cfg, redis.clone(), Duration::from_secs(60 * 60 * 24 * 7));@@ -2326,7 +2455,7 @@ fn setup_ai_test_router_with_overflow_limiter(TokenDropper::default(),None, // event_restriction_serviceNone, // recorder_handle- CaptureMode::Events,+ CaptureMode::Ai,None,25 * 1024 * 1024,false,@@ -2334,18 +2463,20 @@ 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)None,256,10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytes- Some(overflow_limiter),- None, // ai_events_overflow_limiter- None, // replay_overflow_limiter- None, // v1_sink_router- 8, // capture_v1_scatter_gather_min_batch- None, // ai_gateway_signing_secret- false, // ai_events_overflow_enabled- None, // ingestion_warning_emitter+ None, // overflow_limiter+ Some(ai_events_overflow_limiter),+ None, // ai_byte_rate_limiter+ None, // replay_overflow_limiter+ None, // v1_sink_router+ 8, // capture_v1_scatter_gather_min_batch+ None, // ai_gateway_signing_secret+ true, // ai_events_overflow_enabled+ None, // ingestion_warning_emitter);(router, sink_clone)@@ -2466,7 +2597,7 @@ fn ai_router(TokenDropper::default(),None,None, // recorder_handle- CaptureMode::Events,+ CaptureMode::Ai,None,25 * 1024 * 1024,false,@@ -2474,12 +2605,14 @@ fn ai_router(false,0.0_f32,26_214_400,+ 983_040, // ai_max_event_bytes (960KB, the previous hardcoded limit)None,256,10 * 1024 * 1024,50 * 1024 * 1024,None,None, // ai_events_overflow_limiter+ None, // ai_byte_rate_limiterNone,None,8,@@ -2501,7 +2634,7 @@ fn setup_ai_router_quota_limited_with_secret(token: &str) -> (Router, CapturingSlet redis =Arc::new(MockRedisClient::new().zrangebyscore_ret(&llm_key, vec![token.to_string()]));let mut cfg = DEFAULT_CONFIG.clone();- cfg.capture_mode = CaptureMode::Events;+ cfg.capture_mode = CaptureMode::Ai;let quota_limiter = CaptureQuotaLimiter::new(&cfg, redis.clone(), Duration::from_secs(60)).add_scoped_limiter(QuotaResource::LLMEvents, is_llm_event);ai_router(redis, quota_limiter)@@ -2512,7 +2645,7 @@ fn setup_ai_router_quota_limited_with_secret(token: &str) -> (Router, CapturingSfn setup_ai_router_with_secret() -> (Router, CapturingSink) {let redis = Arc::new(MockRedisClient::new());let mut cfg = DEFAULT_CONFIG.clone();- cfg.capture_mode = CaptureMode::Events;+ cfg.capture_mode = CaptureMode::Ai;let quota_limiter =CaptureQuotaLimiter::new(&cfg, redis.clone(), Duration::from_secs(60 * 60 * 24 * 7));ai_router(redis, quota_limiter)@@ -2629,7 +2762,7 @@ fn setup_ai_router_global_quota_limited_with_secret(token: &str) -> (Router, Caplet redis =Arc::new(MockRedisClient::new().zrangebyscore_ret(&events_key, vec![token.to_string()]));let mut cfg = DEFAULT_CONFIG.clone();- cfg.capture_mode = CaptureMode::Events;+ cfg.capture_mode = CaptureMode::Ai;let quota_limiter = CaptureQuotaLimiter::new(&cfg, redis.clone(), Duration::from_secs(60));ai_router(redis, quota_limiter)}diff --git a/rust/capture/tests/integration_ai_restrictions.rs b/rust/capture/tests/integration_ai_restrictions.rsindex 7af68e047b5f..d6b8c3a047b0 100644--- a/rust/capture/tests/integration_ai_restrictions.rs+++ b/rust/capture/tests/integration_ai_restrictions.rs@@ -135,7 +135,7 @@ async fn setup_ai_router_with_restriction(let redis = Arc::new(MockRedisClient::new());let mut cfg = DEFAULT_CONFIG.clone();- cfg.capture_mode = CaptureMode::Events;+ cfg.capture_mode = CaptureMode::Ai;let quota_limiter =CaptureQuotaLimiter::new(&cfg, redis.clone(), Duration::from_secs(60 * 60 * 24 * 7));@@ -165,7 +165,7 @@ async fn setup_ai_router_with_restriction(TokenDropper::default(),Some(service),None, // recorder_handle- CaptureMode::Events,+ CaptureMode::Ai,None,25 * 1024 * 1024,false,@@ -173,12 +173,14 @@ 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)None,256, // body_read_chunk_size_kb10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytesNone, // overflow_limiterNone, // ai_events_overflow_limiter+ None, // ai_byte_rate_limiterNone, // replay_overflow_limiterNone, // v1_sink_router8, // capture_v1_scatter_gather_min_batch@@ -310,7 +312,7 @@ async fn test_ai_redirect_to_dlq_restriction() {token: restricted_token,distinct_id: "test_user",event_name: "$ai_generation",- data_type: DataType::AnalyticsMain,+ data_type: DataType::AiEvents,force_overflow: false,skip_person_processing: false,redirect_to_dlq: true,@@ -347,7 +349,7 @@ async fn test_ai_force_overflow_restriction() {token: restricted_token,distinct_id: "test_user",event_name: "$ai_generation",- data_type: DataType::AnalyticsMain,+ data_type: DataType::AiEvents,force_overflow: true,skip_person_processing: false,redirect_to_dlq: false,@@ -385,7 +387,7 @@ async fn test_ai_skip_person_processing_restriction() {token: restricted_token,distinct_id: "test_user",event_name: "$ai_generation",- data_type: DataType::AnalyticsMain,+ data_type: DataType::AiEvents,force_overflow: false,skip_person_processing: true,redirect_to_dlq: false,@@ -427,7 +429,7 @@ async fn test_ai_restriction_does_not_apply_to_other_tokens() {token: "phc_not_restricted_token",distinct_id: "test_user",event_name: "$ai_generation",- data_type: DataType::AnalyticsMain,+ data_type: DataType::AiEvents,force_overflow: false,skip_person_processing: false,redirect_to_dlq: false,@@ -455,7 +457,7 @@ async fn setup_ai_router_with_redirect_to_topic(let redis = Arc::new(MockRedisClient::new());let mut cfg = DEFAULT_CONFIG.clone();- cfg.capture_mode = CaptureMode::Events;+ cfg.capture_mode = CaptureMode::Ai;let quota_limiter =CaptureQuotaLimiter::new(&cfg, redis.clone(), Duration::from_secs(60 * 60 * 24 * 7));@@ -485,7 +487,7 @@ async fn setup_ai_router_with_redirect_to_topic(TokenDropper::default(),Some(service),None, // recorder_handle- CaptureMode::Events,+ CaptureMode::Ai,None,25 * 1024 * 1024,false,@@ -493,12 +495,14 @@ 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)None,256, // body_read_chunk_size_kb10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytesNone, // overflow_limiterNone, // ai_events_overflow_limiter+ None, // ai_byte_rate_limiterNone, // replay_overflow_limiterNone, // v1_sink_router8, // capture_v1_scatter_gather_min_batch@@ -533,7 +537,7 @@ async fn setup_ai_router_with_force_overflow_and_limiter(let redis = Arc::new(MockRedisClient::new());let mut cfg = DEFAULT_CONFIG.clone();- cfg.capture_mode = CaptureMode::Events;+ cfg.capture_mode = CaptureMode::Ai;let quota_limiter =CaptureQuotaLimiter::new(&cfg, redis.clone(), Duration::from_secs(60 * 60 * 24 * 7));@@ -563,7 +567,7 @@ async fn setup_ai_router_with_force_overflow_and_limiter(TokenDropper::default(),Some(service),None, // recorder_handle- CaptureMode::Events,+ CaptureMode::Ai,None,25 * 1024 * 1024,false,@@ -571,12 +575,14 @@ 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)None,256,10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytes- Some(overflow_limiter), // overflow_limiter- None, // ai_events_overflow_limiter+ None, // overflow_limiter+ Some(overflow_limiter), // ai_events_overflow_limiter+ None, // ai_byte_rate_limiterNone, // replay_overflow_limiterNone, // v1_sink_router8, // capture_v1_scatter_gather_min_batch@@ -627,7 +633,7 @@ async fn test_ai_force_overflow_restriction_wins_over_overflow_limiter() {token: restricted_token,distinct_id,event_name: "$ai_generation",- data_type: DataType::AnalyticsMain,+ data_type: DataType::AiEvents,force_overflow: true,skip_person_processing: false,redirect_to_dlq: false,@@ -644,12 +650,12 @@ async fn test_ai_force_overflow_restriction_wins_over_overflow_limiter() {}#[tokio::test]-async fn test_ai_endpoint_keeps_events_on_analytics_main() {- // The AI endpoint's events are typed at the handler, not by the analytics- // $ai_* lane assignment: they stay on the AnalyticsMain lane and the- // OverflowLimiter applies by analytics rules. Catches a regression that- // types AI-endpoint events as DataType::AiEvents or gates their overflow- // on the analytics valve.+async fn test_ai_endpoint_keeps_events_on_the_ai_lane() {+ // The AI endpoint's events are typed at the handler, and they carry the+ // same lane as an AI event that arrives through the batch path — so+ // the AI overflow limiter is the one that applies. Catches a regression+ // that types AI-endpoint events as AnalyticsMain, which would put them on+ // the analytics topic and under analytics restrictions.let token = "phc_ai_endpoint_routing_leak_token";let distinct_id = "test_user";let hot_key = format!("{token}:{distinct_id}");@@ -680,13 +686,13 @@ async fn test_ai_endpoint_keeps_events_on_analytics_main() {assert_eq!(events.len(), 1);assert_eq!(events[0].metadata.data_type,- DataType::AnalyticsMain,- "analytics-deployment routing config must not divert AI-endpoint events"+ DataType::AiEvents,+ "AI-endpoint events belong on the AI lane");assert_eq!(events[0].metadata.overflow_reason,Some(OverflowReason::ForceLimited),- "the limiter must keep applying by AnalyticsMain rules, valve or not"+ "the AI lane's own limiter must apply once the valve is armed");}@@ -716,7 +722,7 @@ async fn test_ai_redirect_to_topic_restriction() {token: restricted_token,distinct_id: "test_user",event_name: "$ai_generation",- data_type: DataType::AnalyticsMain,+ data_type: DataType::AiEvents,force_overflow: false,skip_person_processing: false,redirect_to_dlq: false,diff --git a/rust/capture/tests/integration_ai_route_surface.rs b/rust/capture/tests/integration_ai_route_surface.rsnew file mode 100644index 000000000000..2db9f6c18b68--- /dev/null+++ b/rust/capture/tests/integration_ai_route_surface.rs@@ -0,0 +1,149 @@+//! Which paths each capture mode registers.+//!+//! Each deployment registers its own ingress and nothing else: the AI paths+//! belong to capture-ai, the analytics paths to capture-analytics and+//! capture-import. The ingress has always routed them that way, so the other+//! set was surface no traffic reached.+//!+//! It also has to stay in step with `Pipeline::for_capture_mode`, which loads+//! exactly the restriction slices each path set can produce to. A route on the+//! wrong deployment accepts traffic no restriction there governs, which is+//! silent rather than loud, so the split is asserted directly here.+//!+//! The pipeline-level gate in `events::analytics` covers the other half: an+//! event name off the AI allowlist arriving on a path that IS registered.++#[path = "common/integration_utils.rs"]+mod integration_utils;++use axum::http::StatusCode;+use axum_test_helper::TestClient;+use capture::config::CaptureMode;+use integration_utils::build_router_for_mode;+use rstest::rstest;+use serde_json::json;++/// A single `$ai_generation`, valid on any path that accepts a batch.+fn ai_batch_payload() -> String {+ json!({+ "api_key": "phc_route_surface_token",+ "batch": [{+ "event": "$ai_generation",+ "distinct_id": "test_user",+ "properties": {},+ }],+ })+ .to_string()+}++/// What a deployment must answer this file's payload on a given path.+///+/// [`Answer::Served`] names the real status rather than "anything but a 404",+/// so a positive case proves the intended handler ran: a 405 (the router+/// matched the path but not the method), a 5xx (no handler completed), and a+/// status from some other handler all fail it. [`Answer::Absent`] is the 404 a+/// router returns for a path it never registered.+#[derive(Debug, Clone, Copy)]+enum Answer {+ Served(StatusCode),+ Absent,+}++impl Answer {+ fn status(self) -> StatusCode {+ match self {+ Answer::Served(status) => status,+ Answer::Absent => StatusCode::NOT_FOUND,+ }+ }+}++/// Post the batch payload to `path` on a router built for `mode`, and pin what+/// comes back.+async fn assert_answer(mode: CaptureMode, path: &str, expected: Answer) {+ let status = TestClient::new(build_router_for_mode(mode))+ .post(path)+ .body(ai_batch_payload())+ .header("Content-Type", "application/json")+ // `InsecureClientIp` is a hard extractor on the analytics handlers, and+ // the test client provides no `ConnectInfo`, so without a forwarded+ // header every registered path answers 500 before its handler runs.+ .header("X-Forwarded-For", "127.0.0.1")+ .send()+ .await+ .status();++ assert_eq!(+ status,+ expected.status(),+ "{mode:?} answered {path} with {status}, expected {expected:?}"+ );+}++/// capture-ai must serve the AI batch path and nothing analytics-shaped.+///+/// The multipart and OTEL handlers answer 401 rather than 200: both read the+/// project token from an `Authorization: Bearer` header, and this file's payload+/// carries it in the body as `api_key`, the way the batch endpoints take it.+/// That is still a status only those handlers produce — reaching their auth step+/// means the router dispatched there — and pinning it is what makes these rows+/// assert something. Feeding each path a body it fully accepts would prove more,+/// but the payload shapes (multipart, protobuf) are what the endpoint suites+/// already cover; this file is about which paths exist.+#[rstest]+#[case::ai_batch("/i/v0/ai/batch", Answer::Served(StatusCode::OK))]+#[case::ai_batch_trailing_slash("/i/v0/ai/batch/", Answer::Served(StatusCode::OK))]+#[case::ai_multipart("/i/v0/ai", Answer::Served(StatusCode::UNAUTHORIZED))]+#[case::ai_otel("/i/v0/ai/otel", Answer::Served(StatusCode::UNAUTHORIZED))]+#[case::analytics_batch("/batch", Answer::Absent)]+#[case::analytics_event("/e", Answer::Absent)]+#[case::analytics_capture("/capture", Answer::Absent)]+#[case::analytics_track("/track", Answer::Absent)]+#[case::analytics_engage("/engage", Answer::Absent)]+#[case::analytics_v1("/i/v1/analytics/events", Answer::Absent)]+#[tokio::test]+async fn ai_mode_registers_only_the_ai_paths(#[case] path: &str, #[case] expected: Answer) {+ assert_answer(CaptureMode::Ai, path, expected).await;+}++/// capture-analytics serves the analytics paths and none of the AI ones. It+/// still ingests AI events — they arrive on `/batch` from SDKs that send+/// everything to one endpoint and divert by event name — so a passing+/// `/batch` case here is what keeps that route alive.+#[rstest]+#[case::analytics_batch("/batch", Answer::Served(StatusCode::OK))]+#[case::analytics_batch_trailing_slash("/batch/", Answer::Served(StatusCode::OK))]+#[case::analytics_event("/e", Answer::Served(StatusCode::OK))]+#[case::analytics_capture("/capture", Answer::Served(StatusCode::OK))]+#[case::analytics_track("/track", Answer::Served(StatusCode::OK))]+#[case::ai_batch("/i/v0/ai/batch", Answer::Absent)]+#[case::ai_multipart("/i/v0/ai", Answer::Absent)]+#[case::ai_otel("/i/v0/ai/otel", Answer::Absent)]+#[tokio::test]+async fn events_mode_registers_only_the_analytics_paths(+ #[case] path: &str,+ #[case] expected: Answer,+) {+ assert_answer(CaptureMode::Events, path, expected).await;+}++/// Import is an analytics deployment restricted to backfills, so it serves the+/// same paths as capture-analytics. The AI handlers are doubly excluded: they+/// belong to capture-ai, and they build their own context with+/// `historical_migration: false`, which would sidestep the import gates.+#[rstest]+#[case::analytics_batch("/batch", Answer::Served(StatusCode::OK))]+#[case::analytics_event("/e", Answer::Served(StatusCode::OK))]+#[case::analytics_v0_event("/i/v0/e", Answer::Served(StatusCode::OK))]+#[case::ai_batch("/i/v0/ai/batch", Answer::Absent)]+#[case::ai_multipart("/i/v0/ai", Answer::Absent)]+#[case::ai_multipart_trailing_slash("/i/v0/ai/", Answer::Absent)]+#[case::ai_otel("/i/v0/ai/otel", Answer::Absent)]+#[case::ai_otel_trailing_slash("/i/v0/ai/otel/", Answer::Absent)]+#[tokio::test]+async fn import_mode_registers_only_the_analytics_paths(+ #[case] path: &str,+ #[case] expected: Answer,+) {+ assert_answer(CaptureMode::Import, path, expected).await;+}diff --git a/rust/capture/tests/integration_analytics_ai_routing.rs b/rust/capture/tests/integration_analytics_ai_routing.rsindex d09734773b0a..e00d3646b302 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_*` routing on analytics deployments:+//! 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.+//! endpoint-level batch handling of mixed AI / non-AI payloads.#[path = "common/integration_utils.rs"]mod integration_utils;@@ -128,12 +128,14 @@ fn setup_router_for_mode(false,0.0_f32,26_214_400,+ 983_040, // ai_max_event_bytes (960KB, the previous hardcoded limit)None,256, // body_read_chunk_size_kb10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytesoverflow_limiter,ai_events_overflow_limiter,+ None, // ai_byte_rate_limiterNone, // replay_overflow_limiterNone, // v1_sink_router8, // capture_v1_scatter_gather_min_batch@@ -164,6 +166,27 @@ fn mixed_batch_payload() -> String {.to_string()}+// Two allowlisted AI event names. capture-ai rejects a batch carrying anything+// else, so its lane-assignment coverage has to use an all-AI batch.+fn ai_only_batch_payload() -> String {+ json!({+ "api_key": TOKEN,+ "batch": [+ {+ "event": "$ai_generation",+ "distinct_id": DISTINCT_ID,+ "properties": {"$ai_model": "gpt-4"}+ },+ {+ "event": "$ai_span",+ "distinct_id": DISTINCT_ID,+ "properties": {}+ }+ ]+ })+ .to_string()+}+// The same mixed batch flagged as a historical migration — the only kind of// batch Import mode accepts.fn historical_mixed_batch_payload() -> String {@@ -243,7 +266,7 @@ async fn legacy_routes_strip_forged_gateway_properties(#[case] path: &str) {assert!(data["properties"].get("$ai_gateway_request_id").is_none());}-/// A mixed batch must split lanes: `$ai_*` events divert to the AI lane on+/// 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.@@ -277,28 +300,58 @@ async fn mixed_batch_diverts_only_ai_events(#[case] ai_events_overflow_enabled:assert_eq!(pageview.metadata.data_type, DataType::AnalyticsMain);}-/// Ai-mode deployments don't divert: their main topic is already the AI-/// topic, so `$ai_*` events stay on the analytics lane alongside everything-/// else. Pins the no-divert path end-to-end; the `routes_ai_events()` unit-/// test alone can't catch the router failing to thread the mode into the-/// pipeline.+/// Capture mode does not change lane assignment: an Ai-mode deployment stamps+/// `AiEvents` exactly like an analytics one. Pins the invariant end-to-end, so+/// a deployment can never silently rejoin AI events to the analytics lane and+/// slip past every AI-lane gate (byte limiter, ai restrictions, AI overflow).+///+/// The batch is all-AI because capture-ai refuses anything else; the mixed-batch+/// half of the old version of this test now lives below.#[tokio::test]-async fn ai_mode_keeps_ai_events_on_the_analytics_lane() {+async fn ai_mode_diverts_ai_events_like_every_other_mode() {let (router, sink) = setup_router_for_mode(CaptureMode::Ai, false, None, None);let client = TestClient::new(router);- post_batch(&client, mixed_batch_payload()).await;+ let response = client+ .post("/i/v0/ai/batch")+ .header("Content-Type", "application/json")+ .header("X-Forwarded-For", "127.0.0.1")+ .body(ai_only_batch_payload())+ .send()+ .await;+ assert_eq!(response.status(), StatusCode::OK);let events = sink.get_events().await;assert_eq!(events.len(), 2);- for event in &events {- assert_eq!(- event.metadata.data_type,- DataType::AnalyticsMain,- "no event may divert on an Ai-mode deployment ({})",- event.metadata.event_name,- );- }+ assert!(+ events+ .iter()+ .all(|e| e.metadata.data_type == DataType::AiEvents),+ "every allowlisted AI event must land on the AI lane under Ai mode"+ );+}++/// The endpoint-level half of the AI-lane gate. The unit tests in+/// `events::analytics` call `process_events` directly, so only this proves the+/// 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 client = TestClient::new(router);++ let response = client+ .post("/i/v0/ai/batch")+ .header("Content-Type", "application/json")+ .header("X-Forwarded-For", "127.0.0.1")+ .body(mixed_batch_payload())+ .send()+ .await;++ assert_eq!(response.status(), StatusCode::BAD_REQUEST);+ assert!(+ sink.get_events().await.is_empty(),+ "rejecting the batch must not publish the AI event ahead of the offender"+ );}fn force_keyed_limiter() -> Arc<OverflowLimiter> {@@ -312,7 +365,7 @@ 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+/// 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@@ -360,7 +413,7 @@ async fn ai_lane_overflow_stamping_gated_on_valve(/// The two lanes consult separate limiter instances end-to-end: a key that/// the analytics limiter force-routes must not drag the same key's diverted-/// `$ai_*` event into AI overflow (and the pageview must still stamp).+/// AI event into AI overflow (and the pageview must still stamp)./// Catches the router wiring one limiter instance into both slots.#[tokio::test]async fn ai_lane_overflow_isolated_from_analytics_limiter() {@@ -404,7 +457,7 @@ 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+/// 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-keyeddiff --git a/rust/capture/tests/integration_analytics_restrictions.rs b/rust/capture/tests/integration_analytics_restrictions.rsindex 71a0c3c1d38a..722930ce849f 100644--- a/rust/capture/tests/integration_analytics_restrictions.rs+++ b/rust/capture/tests/integration_analytics_restrictions.rs@@ -123,12 +123,14 @@ 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)None,256, // body_read_chunk_size_kb10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytesNone, // overflow_limiterNone, // ai_events_overflow_limiter+ None, // ai_byte_rate_limiterNone, // replay_overflow_limiterNone, // v1_sink_router8, // capture_v1_scatter_gather_min_batch@@ -340,7 +342,7 @@ async fn test_analytics_force_overflow_restriction() {#[tokio::test]async fn test_analytics_force_overflow_restriction_applies_to_diverted_ai_event() {- // A $ai_* event diverted onto the AI lane is governed by ai-scoped+ // 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.//@@ -548,12 +550,14 @@ 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)None,256, // body_read_chunk_size_kb10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytesNone, // overflow_limiterNone, // ai_events_overflow_limiter+ None, // ai_byte_rate_limiterNone, // replay_overflow_limiterNone, // v1_sink_router8, // capture_v1_scatter_gather_min_batchdiff --git a/rust/capture/tests/integration_import_routes.rs b/rust/capture/tests/integration_import_routes.rsdeleted file mode 100644index 96a9c5d7cf95..000000000000--- a/rust/capture/tests/integration_import_routes.rs+++ /dev/null@@ -1,59 +0,0 @@-#[path = "common/integration_utils.rs"]-mod integration_utils;-use integration_utils::build_router_for_mode;--use axum::http::StatusCode;-use axum_test_helper::TestClient;-use capture::config::CaptureMode;--// Import mode must not register the AI or OTEL handlers: they build their own-// ProcessingContext with historical_migration: false, so they would bypass both-// Import gates (historical-only drop and GRL) and return a false 200 for traffic-// this deployment silently discards. Events mode keeps them.-#[tokio::test]-async fn test_import_mode_does_not_register_ai_or_otel_routes() {- let client = TestClient::new(build_router_for_mode(CaptureMode::Import));-- for path in ["/i/v0/ai", "/i/v0/ai/", "/i/v0/ai/otel", "/i/v0/ai/otel/"] {- let resp = client.post(path).body(vec![]).send().await;- assert_eq!(- StatusCode::NOT_FOUND,- resp.status(),- "Import mode must not register {path}, expected 404",- );- }-}--// The gated batch/event paths stay reachable in Import mode. /i/v0/ai/batch lives-// on batch_router (not ai_router) and dispatches to the gated v0_endpoint::event,-// so it survives the split. "Not 404" is the assertion: an empty body yields a 4xx-// from the handler, which still proves the route is registered.-#[tokio::test]-async fn test_import_mode_serves_gated_event_routes() {- let client = TestClient::new(build_router_for_mode(CaptureMode::Import));-- for path in ["/i/v0/e", "/batch", "/i/v0/ai/batch"] {- let resp = client.post(path).body(vec![]).send().await;- assert_ne!(- StatusCode::NOT_FOUND,- resp.status(),- "Import mode must serve {path}, got 404",- );- }-}--// Guard the contrast: Events mode does register the AI/OTEL routes, so the split-// above is the only thing withholding them from Import.-#[tokio::test]-async fn test_events_mode_registers_ai_and_otel_routes() {- let client = TestClient::new(build_router_for_mode(CaptureMode::Events));-- for path in ["/i/v0/ai", "/i/v0/ai/otel"] {- let resp = client.post(path).body(vec![]).send().await;- assert_ne!(- StatusCode::NOT_FOUND,- resp.status(),- "Events mode must register {path}, got 404",- );- }-}diff --git a/rust/capture/tests/integration_otel_endpoint.rs b/rust/capture/tests/integration_otel_endpoint.rsindex d5b5c8217693..83be090fc346 100644--- a/rust/capture/tests/integration_otel_endpoint.rs+++ b/rust/capture/tests/integration_otel_endpoint.rs@@ -9,6 +9,7 @@ use capture::event_restrictions::{EventRestrictionService, Pipeline, Restriction, RestrictionFilters, RestrictionManager,RestrictionScope, RestrictionType,};+use capture::global_rate_limiter::GlobalRateLimiter;use capture::quota_limiters::{is_llm_event, CaptureQuotaLimiter, EventInfo};use capture::router::router;use capture::sinks::Event;@@ -131,14 +132,21 @@ struct TestClientOptions {event_restriction_service: Option<EventRestrictionService>,quota_limiter: Option<CaptureQuotaLimiter>,ai_gateway_signing_secret: Option<String>,- // Opt-in OverflowLimiter wiring. `None` (default) matches production- // configs without `OVERFLOW_ENABLED=true` and exercises the no-op branch- // of `stamp_overflow_reason`.- overflow_limiter: Option<Arc<OverflowLimiter>>,+ // 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`.+ 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.+ 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.+ ai_byte_rate_limiter: Option<Arc<GlobalRateLimiter>>,}fn make_test_client(sink: &CapturingSink) -> TestClient {@@ -158,7 +166,7 @@ fn make_test_client_with_options(sink: &CapturingSink, options: TestClientOption.unwrap_or_else(|| Arc::new(MockRedisClient::new()));let mut cfg = DEFAULT_CONFIG.clone();- cfg.capture_mode = CaptureMode::Events;+ cfg.capture_mode = CaptureMode::Ai;let quota_limiter = options.quota_limiter.unwrap_or_else(|| {CaptureQuotaLimiter::new(&cfg, redis.clone(), Duration::from_secs(60 * 60 * 24 * 7))@@ -176,25 +184,27 @@ fn make_test_client_with_options(sink: &CapturingSink, options: TestClientOptionTokenDropper::default(),options.event_restriction_service,None, // recorder_handle- CaptureMode::Events,- None, // concurrency_limit- 25 * 1024 * 1024, // event_payload_size_limit- false, // enable_historical_rerouting- 1_i64, // historical_rerouting_threshold_days- false, // is_mirror_deploy- 0.0_f32, // verbose_sample_percent- 26_214_400, // ai_max_sum_of_parts_bytes- None, // body_chunk_read_timeout_ms- 256, // body_read_chunk_size_kb- 10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes- 50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytes- options.overflow_limiter, // overflow_limiter- None, // ai_events_overflow_limiter- None, // replay_overflow_limiter- None, // v1_sink_router- 8, // capture_v1_scatter_gather_min_batch+ CaptureMode::Ai,+ None, // concurrency_limit+ 25 * 1024 * 1024, // event_payload_size_limit+ false, // enable_historical_rerouting+ 1_i64, // historical_rerouting_threshold_days+ false, // is_mirror_deploy+ 0.0_f32, // verbose_sample_percent+ 26_214_400, // ai_max_sum_of_parts_bytes+ options.ai_max_event_bytes.unwrap_or(983_040), // ai_max_event_bytes+ None, // body_chunk_read_timeout_ms+ 256, // body_read_chunk_size_kb+ 10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes+ 50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytes+ None, // overflow_limiter+ options.ai_events_overflow_limiter,+ options.ai_byte_rate_limiter,+ None, // replay_overflow_limiter+ None, // v1_sink_router+ 8, // capture_v1_scatter_gather_min_batchoptions.ai_gateway_signing_secret,- false, // ai_events_overflow_enabled+ true, // ai_events_overflow_enabledoptions.ingestion_warning_emitter, // ingestion_warning_emitter);@@ -412,7 +422,7 @@ async fn test_single_span_produces_one_event() {assert_eq!(event.event.token, TOKEN);assert_eq!(event.event.event, "$ai_generation");assert_eq!(event.event.distinct_id, "user-1");- assert_eq!(event.metadata.data_type, DataType::AnalyticsMain);+ assert_eq!(event.metadata.data_type, DataType::AiEvents);assert_eq!(event.metadata.event_name, "$ai_generation");let data = parse_event_data(event);@@ -846,6 +856,101 @@ async fn test_mixed_requests_only_emit_relevant_ai_spans() {assert_eq!(events[0].event.event, "$ai_generation");}+/// A real limiter whose local cache admits a key's first charge and limits+/// every one after it, so a single multi-span export shows both outcomes.+///+/// A threshold of `0` is what makes the second charge exceed the window with no+/// Redis round trip and no clock, the same seam+/// `integration_person_processing_matrix` uses for the event limiter. The tick+/// is parked well past the request so no background sync can race it.+fn always_limits_after_the_first_span() -> Arc<GlobalRateLimiter> {+ let mut cfg = DEFAULT_CONFIG.clone();+ cfg.capture_mode = CaptureMode::Ai;+ cfg.ai_byte_limit_per_second = 0;+ cfg.global_rate_limit_tick_interval_ms = 600_000;+ Arc::new(+ GlobalRateLimiter::new_ai_bytes(&cfg, vec![Arc::new(MockRedisClient::new())])+ .expect("failed to build the AI byte limiter"),+ )+}++/// The byte budget reaches this endpoint. It builds its events at the handler+/// and never enters either analytics pipeline, so the charge has to be wired+/// here or a sender could spend unbounded bytes on `/i/v0/ai/otel` while the+/// same bytes are capped on the batch paths.+///+/// Over-budget spans are shed rather than the export refused, matching the size+/// ceiling and for the same reason: a collector retries a rejected export.+#[tokio::test]+async fn over_budget_spans_are_shed_while_the_export_succeeds() {+ let sink = CapturingSink::new();+ let client = make_test_client_with_options(+ &sink,+ TestClientOptions {+ ai_byte_rate_limiter: Some(always_limits_after_the_first_span()),+ ..Default::default()+ },+ );++ let status = send_request_with_client(&client, &make_two_span_request()).await;+ assert_eq!(status, 200, "the export must still be accepted");++ let events = sink.get_events().await;+ assert_eq!(+ events.len(),+ 1,+ "the first span is admitted on a cold key; the second is over budget"+ );+ assert_eq!(events[0].event.event, "$ai_generation");+}++/// Without a limiter configured, both spans publish — so the test above is+/// pinning the budget rather than some other filter in the handler.+#[tokio::test]+async fn both_spans_publish_when_no_byte_budget_is_configured() {+ let sink = CapturingSink::new();+ let client = make_test_client(&sink);++ let status = send_request_with_client(&client, &make_two_span_request()).await;+ assert_eq!(status, 200);+ assert_eq!(sink.get_events().await.len(), 2);+}++/// An oversized span is shed and the export still succeeds, so a collector is+/// never made to retry a span that can never fit. The warning is the only+/// feedback channel for that, which is why it is asserted alongside the drop:+/// without it the customer sees a 200 and silently missing spans.+#[tokio::test]+async fn oversized_spans_are_shed_and_warn_while_the_export_succeeds() {+ let sink = CapturingSink::new();+ let emitter = Arc::new(CollectingEmitter::default());+ let client = make_test_client_with_options(+ &sink,+ TestClientOptions {+ ingestion_warning_emitter: Some(emitter.clone()),+ ai_max_event_bytes: Some(64),+ ..Default::default()+ },+ );++ // A 64-byte ceiling is under the serialized size of even a minimal AI span.+ let status = send_request_with_client(&client, &make_single_span_request()).await;+ assert_eq!(status, 200, "the export must still be accepted");+ assert!(+ sink.get_events().await.is_empty(),+ "the oversized span must not reach the sink"+ );++ let emitted = emitter.emitted();+ assert_eq!(emitted.len(), 1);+ assert_eq!(emitted[0].warning, WarningType::MessageSizeTooLarge);+ assert_eq!(emitted[0].source, CAPTURE_AI_OTEL);+ assert_eq!(+ emitted[0].extra_details.get("droppedSpans"),+ Some(&json!(1))+ );+}+// The warning is the only feedback channel for this outcome: the OTLP contract// has no way to say "accepted, ingested nothing", so the exporter sees a 200.// Also proves the emit site is wired and that SDK attribution survives the trip@@ -1576,10 +1681,9 @@ async fn test_filtered_drop_restriction_rejects_otel_batch() {// ============================================================================//// `otel_handler` bypasses `events::analytics::process_events` and produces-// `DataType::AnalyticsMain` 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.+// `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@@ -1655,7 +1759,7 @@ async fn test_otel_batch_with_hot_token_stamps_force_limited_on_every_span() {let client = make_test_client_with_options(&sink,TestClientOptions {- overflow_limiter: Some(overflow_limiter),+ ai_events_overflow_limiter: Some(overflow_limiter),..Default::default()},);@@ -1677,7 +1781,7 @@ async fn test_otel_batch_with_hot_token_stamps_force_limited_on_every_span() {event.metadata.skip_person_processing,"span[{i}] ForceLimited implies skip_person_processing");- assert_eq!(event.metadata.data_type, DataType::AnalyticsMain);+ assert_eq!(event.metadata.data_type, DataType::AiEvents);}}@@ -1698,7 +1802,7 @@ async fn test_otel_batch_rate_limited_key_stamps_overbudget_spans() {let client = make_test_client_with_options(&sink,TestClientOptions {- overflow_limiter: Some(overflow_limiter),+ ai_events_overflow_limiter: Some(overflow_limiter),..Default::default()},);diff --git a/rust/capture/tests/integration_person_processing_matrix.rs b/rust/capture/tests/integration_person_processing_matrix.rsindex c055a59af26b..599ca77b5a1c 100644--- a/rust/capture/tests/integration_person_processing_matrix.rs+++ b/rust/capture/tests/integration_person_processing_matrix.rs@@ -254,12 +254,14 @@ 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)None,256,10 * 1024 * 1024,50 * 1024 * 1024,None,None,+ None, // ai_byte_rate_limiterNone,None,8,diff --git a/rust/capture/tests/integration_replay_restrictions.rs b/rust/capture/tests/integration_replay_restrictions.rsindex 8a919d6b9089..e013fdf73b4e 100644--- a/rust/capture/tests/integration_replay_restrictions.rs+++ b/rust/capture/tests/integration_replay_restrictions.rs@@ -120,12 +120,14 @@ 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)None,256, // body_read_chunk_size_kb10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytesNone, // overflow_limiterNone, // ai_events_overflow_limiter+ None, // ai_byte_rate_limiterNone, // replay_overflow_limiterNone, // v1_sink_router8, // capture_v1_scatter_gather_min_batch@@ -491,12 +493,14 @@ 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)None,256, // body_read_chunk_size_kb10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytesNone, // overflow_limiterNone, // ai_events_overflow_limiter+ None, // ai_byte_rate_limiterNone, // replay_overflow_limiterNone, // v1_sink_router8, // capture_v1_scatter_gather_min_batchdiff --git a/rust/capture/tests/integration_wire_body_limits.rs b/rust/capture/tests/integration_wire_body_limits.rsindex ba8b6013d864..234b2771dd34 100644--- a/rust/capture/tests/integration_wire_body_limits.rs+++ b/rust/capture/tests/integration_wire_body_limits.rs@@ -94,14 +94,18 @@ fn make_test_client(mode: CaptureMode) -> (TestClient, CapturingSink) {false,0.0_f32,26_214_400,+ // Far above any body this file sends: the AI-lane event ceiling must not+ // be what produces a 413 here, or the wire cap would go untested.+ BATCH_BODY_SIZE as u64 * 5, // ai_max_event_bytesNone,256,10 * 1024 * 1024,50 * 1024 * 1024,- None,- None,- None,- None,+ None, // overflow_limiter+ None, // ai_events_overflow_limiter+ None, // ai_byte_rate_limiter+ None, // replay_overflow_limiter+ None, // v1_sink_router8,None,false,@@ -114,14 +118,29 @@ fn make_test_client(mode: CaptureMode) -> (TestClient, CapturingSink) {/// A body of `len` bytes that is valid JSON, so nothing before the size check/// can reject it for a different reason.fn body_of_len(len: usize) -> String {- let envelope = r#"{"token":"phc_test","event":"e","distinct_id":"d","properties":{"big":""}}"#;+ named_body_of_len(len, "e")+}++/// The same, with the event name chosen. Capture-ai rejects any event outside the+/// `AI_EVENT_NAMES` allowlist with a 400 before the size check is reached, so an+/// AI-lane body has to carry a listed name to exercise the cap at all.+fn named_body_of_len(len: usize, event: &str) -> String {+ let envelope = format!(+ r#"{{"token":"phc_test","event":"{event}","distinct_id":"d","properties":{{"big":""}}}}"#+ );let padding = len.saturating_sub(envelope.len());format!(- r#"{{"token":"phc_test","event":"e","distinct_id":"d","properties":{{"big":"{}"}}}}"#,+ r#"{{"token":"phc_test","event":"{}","distinct_id":"d","properties":{{"big":"{}"}}}}"#,+ event,"a".repeat(padding))}+/// The analytics paths an Events-mode deployment registers. `/i/v0/ai/batch`+/// runs the same handler under the same cap, but only capture-ai serves it, so+/// it is swept separately below rather than from this list.+const ANALYTICS_ROUTES: [&str; 6] = ["/e", "/i/v0/e", "/batch", "/capture", "/track", "/engage"];+/// Every v0 analytics route shares one handler, so every one of them must share/// one wire cap. Before this was wired through, `DefaultBodyLimit` was the only/// thing carrying these numbers, and it does not apply to a `Body` extractor —@@ -131,15 +150,7 @@ async fn every_v0_analytics_route_rejects_a_body_over_the_wire_cap() {let (client, _sink) = make_test_client(CaptureMode::Events);let over = body_of_len(BATCH_BODY_SIZE + 1024);- for path in [- "/e",- "/i/v0/e",- "/batch",- "/i/v0/ai/batch",- "/capture",- "/track",- "/engage",- ] {+ for path in ANALYTICS_ROUTES {let res = client.post(path).header("Content-Type", "application/json")@@ -166,15 +177,7 @@ async fn every_v0_analytics_route_accepts_a_body_under_the_wire_cap() {let under = body_of_len(4 * 1024 * 1024);let mut ingested = 0usize;- for path in [- "/e",- "/i/v0/e",- "/batch",- "/i/v0/ai/batch",- "/capture",- "/track",- "/engage",- ] {+ for path in ANALYTICS_ROUTES {let res = client.post(path).header("Content-Type", "application/json")@@ -196,6 +199,47 @@ async fn every_v0_analytics_route_accepts_a_body_under_the_wire_cap() {}}+/// `/i/v0/ai/batch` carries the same handler and the same cap, but it lives in+/// its own router group that only capture-ai registers. That split is what makes+/// this worth pinning apart: a group added without the `WireBodyLimit` extension+/// falls back to the decompressed budget and reverts the fix on this one route,+/// and no Events-mode sweep would notice.+#[tokio::test]+async fn the_ai_batch_route_carries_the_same_wire_cap() {+ let (client, sink) = make_test_client(CaptureMode::Ai);++ let res = client+ .post("/i/v0/ai/batch")+ .header("Content-Type", "application/json")+ .header("X-Forwarded-For", "127.0.0.1")+ .body(named_body_of_len(BATCH_BODY_SIZE + 1024, "$ai_span"))+ .send()+ .await;+ assert_eq!(+ StatusCode::PAYLOAD_TOO_LARGE,+ res.status(),+ "/i/v0/ai/batch accepted a body over the wire cap"+ );++ let res = client+ .post("/i/v0/ai/batch")+ .header("Content-Type", "application/json")+ .header("X-Forwarded-For", "127.0.0.1")+ .body(named_body_of_len(4 * 1024 * 1024, "$ai_span"))+ .send()+ .await;+ assert_eq!(+ StatusCode::OK,+ res.status(),+ "/i/v0/ai/batch rejected a body inside the wire cap"+ );+ assert_eq!(+ 1,+ sink.count().await,+ "/i/v0/ai/batch returned 200 without producing the event"+ );+}+/// The drain exists so a rejection can be written on a connection the client/// keeps using. A small overshoot proves little, because hyper's own one-shot/// drain absorbs a few leftover bytes by itself. This overshoots by half the cap,diff --git a/rust/capture/tests/quota_limiters.rs b/rust/capture/tests/quota_limiters.rsindex fe45243a07db..2a823ceec06d 100644--- a/rust/capture/tests/quota_limiters.rs+++ b/rust/capture/tests/quota_limiters.rs@@ -142,12 +142,14 @@ async fn setup_router_with_limits(false, // is_mirror_deploy0.0, // verbose_sample_percent26_214_400, // ai_max_sum_of_parts_bytes (25MB)+ 983_040, // ai_max_event_bytes (960KB, the previous hardcoded limit)None, // body_chunk_read_timeout_ms256, // body_read_chunk_size_kb10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytesNone, // overflow_limiterNone, // ai_events_overflow_limiter+ None, // ai_byte_rate_limiterNone, // replay_overflow_limiterNone, // v1_sink_router8, // capture_v1_scatter_gather_min_batch@@ -1195,12 +1197,14 @@ 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)None, // body_chunk_read_timeout_ms256, // body_read_chunk_size_kb10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytesNone, // overflow_limiterNone, // ai_events_overflow_limiter+ None, // ai_byte_rate_limiterNone, // replay_overflow_limiterNone, // v1_sink_router8, // capture_v1_scatter_gather_min_batch@@ -1286,12 +1290,14 @@ 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)None, // body_chunk_read_timeout_ms256, // body_read_chunk_size_kb10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytesNone, // overflow_limiterNone, // ai_events_overflow_limiter+ None, // ai_byte_rate_limiterNone, // replay_overflow_limiterNone, // v1_sink_router8, // capture_v1_scatter_gather_min_batch@@ -1381,12 +1387,14 @@ 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)None, // body_chunk_read_timeout_ms256, // body_read_chunk_size_kb10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytesNone, // overflow_limiterNone, // ai_events_overflow_limiter+ None, // ai_byte_rate_limiterNone, // replay_overflow_limiterNone, // v1_sink_router8, // capture_v1_scatter_gather_min_batch@@ -1813,12 +1821,14 @@ 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)None, // body_chunk_read_timeout_ms256, // body_read_chunk_size_kb10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytesNone, // overflow_limiterNone, // ai_events_overflow_limiter+ None, // ai_byte_rate_limiterNone, // replay_overflow_limiterNone, // v1_sink_router8, // capture_v1_scatter_gather_min_batch