Skip to content

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

feat(capture): add /i/v1/ai/events endpoint for the AI lane (#87034)

Paweł Ledwońd76c9bb83095
diff --git a/rust/capture/src/event_restrictions/types.rs b/rust/capture/src/event_restrictions/types.rs
index 25385d454184..e2ffe68e24b7 100644
--- a/rust/capture/src/event_restrictions/types.rs
+++ b/rust/capture/src/event_restrictions/types.rs
@@ -61,10 +61,17 @@ impl Pipeline {
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.
+ // capture-ai registers only the AI routes, and both pipelines
+ // refuse an event off the AI lane before restrictions are applied,
+ // so no event there ever resolves to another pipeline. Loading the
+ // analytics and error-tracking slices would only cost memory.
+ //
+ // The two refuse differently, each fitting its own response
+ // contract: v0's `process_events` rejects the whole request
+ // (`CaptureError::NonAiEventOnAiLane`, 400), while v1's
+ // `drop_non_ai_events` drops only the offenders, because it can
+ // report per-event outcomes. The guarantee relied on here is the
+ // same either way.
CaptureMode::Ai => vec![Self::Ai],
}
}
diff --git a/rust/capture/src/router.rs b/rust/capture/src/router.rs
index efe7f29e55b9..8fbb86b03bdb 100644
--- a/rust/capture/src/router.rs
+++ b/rust/capture/src/router.rs
@@ -461,19 +461,19 @@ pub fn router<TZ: TimeSource + Send + Sync + 'static, R: Client + Send + Sync +
// scoped to v0/status routes; v1 ships its own policy.
router = router.layer(cors);
- // The v1 analytics endpoint is only routable when a v1 sink is
- // configured. Without a sink the handler can't publish, so we keep
- // the path unregistered (404) rather than advertising an endpoint
- // that can only ever return 503. This also isolates the route to
- // deployments that opt in via CAPTURE_V1_SINKS.
+ // The v1 endpoints are only routable when a v1 sink is configured.
+ // Without a sink the handler can't publish, so we keep the paths
+ // unregistered (404) rather than advertising endpoints that can only
+ // ever return 503. This also isolates the routes to deployments that
+ // opt in via CAPTURE_V1_SINKS.
//
// Merged after every legacy layer above: the v1 router owns its full
// middleware stack (CORS, limits) and applies the same per-route
// concurrency cap to its own routes.
//
// Matched exhaustively, like the legacy route gating above: a new capture
- // mode must declare whether it serves the v1 analytics endpoint instead of
- // silently defaulting to "no v1 routes" and 404ing its traffic.
+ // mode must declare whether it serves each v1 endpoint instead of silently
+ // defaulting to "no v1 routes" and 404ing its traffic.
let serves_v1_analytics = match capture_mode {
CaptureMode::Events | CaptureMode::Import => true,
// `/i/v1/analytics/events` is an analytics endpoint: it accepts any
@@ -481,10 +481,20 @@ pub fn router<TZ: TimeSource + Send + Sync + 'static, R: Client + Send + Sync +
// which capture-ai no longer loads.
CaptureMode::Ai | CaptureMode::Recordings => false,
};
- if serves_v1_analytics && state.v1_sink_router.is_some() {
+ let serves_v1_ai_events = match capture_mode {
+ // `/i/v1/ai/events` belongs to capture-ai the way the v0 AI paths do:
+ // that deployment produces straight to the AI topic and sizes its
+ // ceilings for AI events. See `v1::analytics::router::ai_routes` for
+ // why the shared handler needs no AI-specific branch.
+ CaptureMode::Ai => true,
+ CaptureMode::Events | CaptureMode::Import | CaptureMode::Recordings => false,
+ };
+ if (serves_v1_analytics || serves_v1_ai_events) && state.v1_sink_router.is_some() {
router = router.merge(crate::v1::router::router(crate::v1::router::RouterConfig {
concurrency_limit,
max_compressed_body_bytes: state.capture_v1_max_compressed_body_bytes,
+ serves_analytics: serves_v1_analytics,
+ serves_ai_events: serves_v1_ai_events,
}));
}
diff --git a/rust/capture/src/setup.rs b/rust/capture/src/setup.rs
index 0c961976616a..def4a2ba3c65 100644
--- a/rust/capture/src/setup.rs
+++ b/rust/capture/src/setup.rs
@@ -483,6 +483,48 @@ fn warn_if_ai_ceiling_exceeds_producer_cap(config: &Config) {
}
}
+/// Every v1 sink whose `message_max_bytes` sits at or below the AI ceiling,
+/// sorted by sink name so the result is stable to assert on.
+fn v1_sinks_below_ai_ceiling(
+ config: &Config,
+ sinks_cfg: &crate::v1::sinks::Sinks,
+) -> Vec<(crate::v1::sinks::SinkName, u32)> {
+ let ceiling = config.ai_max_event_bytes;
+ // `0` disables the ceiling, so there is no ordering to be wrong about.
+ if ceiling == 0 {
+ return Vec::new();
+ }
+ let mut offenders: Vec<(crate::v1::sinks::SinkName, u32)> = sinks_cfg
+ .configs
+ .iter()
+ .filter(|(_, cfg)| ceiling >= cfg.kafka.message_max_bytes as u64)
+ .map(|(name, cfg)| (*name, cfg.kafka.message_max_bytes))
+ .collect();
+ offenders.sort_by_key(|(name, _)| name.as_str());
+ offenders
+}
+
+/// The v1-sink counterpart to [`warn_if_ai_ceiling_exceeds_producer_cap`].
+///
+/// That check reads `KAFKA_PRODUCER_MESSAGE_MAX_BYTES`, which governs only the
+/// v0 producer. Every v1 sink carries its own `message_max_bytes`
+/// (`CAPTURE_V1_SINK_<NAME>_KAFKA_MESSAGE_MAX_BYTES`, default 1MB), so a
+/// deployment whose AI traffic runs on a v1 sink can pass the v0 check with a
+/// correctly-raised cap on a producer it never uses, and still have every event
+/// between the sink cap and the ceiling refused by the broker.
+fn warn_if_ai_ceiling_exceeds_v1_sink_caps(config: &Config, sinks_cfg: &crate::v1::sinks::Sinks) {
+ for (name, message_max_bytes) in v1_sinks_below_ai_ceiling(config, sinks_cfg) {
+ warn!(
+ sink = name.as_str(),
+ ai_max_event_bytes = config.ai_max_event_bytes,
+ message_max_bytes,
+ "AI_MAX_EVENT_BYTES is at or above this v1 sink's MESSAGE_MAX_BYTES; \
+ events between the sink 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
@@ -530,6 +572,8 @@ fn create_v1_sink_router(
.clone();
}
+ warn_if_ai_ceiling_exceeds_v1_sink_caps(config, &sinks_cfg);
+
let mut sink_map: HashMap<crate::v1::sinks::SinkName, Box<dyn crate::v1::sinks::sink::Sink>> =
HashMap::new();
@@ -1296,6 +1340,60 @@ mod tests {
assert_eq!(ai_ceiling_exceeds_producer_cap(&config), expected);
}
+ /// The v0 check above reads `KAFKA_PRODUCER_MESSAGE_MAX_BYTES`, which a
+ /// v1-sink-only deployment never produces through. capture-ai is exactly
+ /// that shape, so without this the AI ceiling is checked against a producer
+ /// the deployment does not use while the sink that does the producing keeps
+ /// its 1MB default.
+ #[rstest::rstest]
+ #[case::sink_at_default_is_flagged(8_388_608, 1_000_000, true)]
+ #[case::sink_raised_above_ceiling_is_clear(8_388_608, 10_485_760, false)]
+ #[case::equal_still_flags(1_000_000, 1_000_000, true)]
+ #[case::disabled_ceiling_never_flags(0, 1_000_000, false)]
+ fn ai_ceiling_is_checked_against_each_v1_sink_cap(
+ #[case] ceiling: u64,
+ #[case] sink_cap: u32,
+ #[case] expected_flagged: 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;
+ // Raised well above the ceiling, so a v0-only check would say "clear"
+ // and any flag below must have come from the v1 sink.
+ config.kafka.kafka_producer_message_max_bytes = 20_971_520;
+
+ let mut sink_cfg = crate::v1::sinks::Config {
+ produce_timeout: std::time::Duration::from_secs(30),
+ kafka: crate::v1::test_utils::test_kafka_config(),
+ };
+ sink_cfg.kafka.message_max_bytes = sink_cap;
+ let sinks_cfg = crate::v1::sinks::Sinks {
+ default: crate::v1::sinks::SinkName::Ws,
+ configs: [(crate::v1::sinks::SinkName::Ws, sink_cfg)]
+ .into_iter()
+ .collect(),
+ };
+
+ assert!(
+ !ai_ceiling_exceeds_producer_cap(&config),
+ "v0 producer is raised, so only the v1 sink can be the offender"
+ );
+ let offenders = v1_sinks_below_ai_ceiling(&config, &sinks_cfg);
+ assert_eq!(offenders.is_empty(), !expected_flagged);
+ if expected_flagged {
+ assert_eq!(offenders[0].1, sink_cap);
+ }
+ }
+
/// 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.
diff --git a/rust/capture/src/v1/analytics/constants.rs b/rust/capture/src/v1/analytics/constants.rs
index 00ea08a3494e..12593951218e 100644
--- a/rust/capture/src/v1/analytics/constants.rs
+++ b/rust/capture/src/v1/analytics/constants.rs
@@ -18,6 +18,24 @@ pub const CAPTURE_V1_PATH: &str = "/i/v1/analytics/events";
/// Trailing-slash variant registered so both URL forms resolve to the same handler.
pub(super) const CAPTURE_V1_PATH_TRAILING: &str = "/i/v1/analytics/events/";
+/// Primary route path for the v1 endpoint on the AI lane. Served only by
+/// `CaptureMode::Ai`; `crate::router` owns the mode gating and
+/// [`super::router::ai_routes`] the rationale.
+pub const CAPTURE_V1_AI_PATH: &str = "/i/v1/ai/events";
+
+/// Trailing-slash variant registered so both URL forms resolve to the same handler.
+pub(super) const CAPTURE_V1_AI_PATH_TRAILING: &str = "/i/v1/ai/events/";
+
+/// Every path the v1 batch handler serves. `pin_static_path` resolves a
+/// request's `MatchedPath` against this list to the `&'static str` label the
+/// request's metrics and warnings carry.
+pub(super) const CAPTURE_V1_PATHS: &[&str] = &[
+ CAPTURE_V1_PATH,
+ CAPTURE_V1_PATH_TRAILING,
+ CAPTURE_V1_AI_PATH,
+ CAPTURE_V1_AI_PATH_TRAILING,
+];
+
// ---------------------------------------------------------------------------
// Metrics keys
// ---------------------------------------------------------------------------
@@ -52,6 +70,10 @@ pub(super) const DETAIL_EVENT_RESTRICTION_DROP: &str = "event_restriction_drop";
/// were not flagged `historical_migration: true`.
pub(super) const DETAIL_NON_HISTORICAL_DROP: &str = "non_historical_import_drop";
+/// Detail tag for events dropped by an AI-mode deployment because they are not
+/// on the AI lane.
+pub(super) const DETAIL_NON_AI_EVENT: &str = "non_ai_event";
+
/// Detail tag for events dropped due to uncoercible options fields.
pub(super) const DETAIL_INVALID_OPTIONS: &str = "invalid_options";
diff --git a/rust/capture/src/v1/analytics/handler.rs b/rust/capture/src/v1/analytics/handler.rs
index e10c1f9f35b5..d5a83ccf1b72 100644
--- a/rust/capture/src/v1/analytics/handler.rs
+++ b/rust/capture/src/v1/analytics/handler.rs
@@ -4,7 +4,7 @@ use axum::http::{header, HeaderMap, Method};
use axum::response::IntoResponse;
use axum_client_ip::InsecureClientIp;
-use super::constants::{CAPTURE_V1_PATH, CAPTURE_V1_PATH_TRAILING};
+use super::constants::{CAPTURE_V1_PATH, CAPTURE_V1_PATHS};
use super::context::Context;
use super::types::Batch;
use tracing::Level;
@@ -21,14 +21,7 @@ pub async fn handle_request(
path: MatchedPath,
body: Body,
) -> Result<axum::response::Response, v1::Error> {
- let static_path: &'static str = match path.as_str() {
- CAPTURE_V1_PATH => CAPTURE_V1_PATH,
- CAPTURE_V1_PATH_TRAILING => CAPTURE_V1_PATH_TRAILING,
- other => {
- tracing::warn!(path = other, "unexpected matched path");
- CAPTURE_V1_PATH
- }
- };
+ let static_path = pin_static_path(path.as_str());
let mut context = Context::new(
&headers,
&ip,
@@ -110,6 +103,25 @@ pub async fn handle_request(
}
}
+/// Resolve a matched route pattern to its `&'static str`, which the Context
+/// carries into every metric and warning this request emits.
+///
+/// `MatchedPath` borrows from the request, so a label taken straight from it
+/// could not be `&'static`; matching it back against the registered set is what
+/// keeps the label a fixed-cardinality literal no matter what the client sent.
+/// An unknown pattern means a route was registered without being listed, which
+/// is a bug rather than client input, so falling back keeps the request served
+/// and the warning says where to look.
+fn pin_static_path(matched: &str) -> &'static str {
+ match CAPTURE_V1_PATHS.iter().find(|p| **p == matched) {
+ Some(path) => path,
+ None => {
+ tracing::warn!(path = matched, "unexpected matched path");
+ CAPTURE_V1_PATH
+ }
+ }
+}
+
/// Logs a header-validation error before a Context could be constructed.
/// Manually extracts raw header values for structured logging, then bumps
/// the error metric with no Context path (falls back to "unknown").
@@ -445,4 +457,33 @@ mod tests {
assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE);
}
+
+ /// Every registered route must map to its own `&'static` label. The
+ /// fallback is silent apart from a log line, so a route registered without
+ /// being added to `CAPTURE_V1_PATHS` would quietly report AI traffic under
+ /// the analytics path -- on metrics and on ingestion warnings alike.
+ #[rstest::rstest]
+ #[case(CAPTURE_V1_PATH)]
+ #[case(crate::v1::analytics::constants::CAPTURE_V1_PATH_TRAILING)]
+ #[case(crate::v1::analytics::constants::CAPTURE_V1_AI_PATH)]
+ #[case(crate::v1::analytics::constants::CAPTURE_V1_AI_PATH_TRAILING)]
+ fn pin_static_path_round_trips_every_registered_route(#[case] path: &str) {
+ assert_eq!(super::pin_static_path(path), path);
+ }
+
+ /// The AI path must not collapse onto the analytics label, which is what
+ /// the fallback would do.
+ #[test]
+ fn pin_static_path_keeps_the_ai_path_distinct() {
+ let ai = super::pin_static_path(crate::v1::analytics::constants::CAPTURE_V1_AI_PATH);
+ assert_ne!(ai, CAPTURE_V1_PATH);
+ assert_eq!(ai, "/i/v1/ai/events");
+ }
+
+ /// An unregistered pattern falls back rather than panicking, so a routing
+ /// mistake degrades a metric label instead of dropping the request.
+ #[test]
+ fn pin_static_path_falls_back_for_an_unregistered_route() {
+ assert_eq!(super::pin_static_path("/i/v1/not/a/route"), CAPTURE_V1_PATH);
+ }
}
diff --git a/rust/capture/src/v1/analytics/process.rs b/rust/capture/src/v1/analytics/process.rs
index ab3e84f50bd0..6aa8ed2c7d12 100644
--- a/rust/capture/src/v1/analytics/process.rs
+++ b/rust/capture/src/v1/analytics/process.rs
@@ -12,8 +12,9 @@ use super::constants::{
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_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,
+ DETAIL_EVENT_RESTRICTION_DROP, DETAIL_INVALID_OPTIONS, DETAIL_NON_AI_EVENT,
+ 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};
@@ -25,7 +26,8 @@ use limiters::overflow::{OverflowLimiter, OverflowLimiterResult};
use tracing::Level;
use super::context::Context;
-use crate::ingestion_warnings::emit_rate_limit_warning;
+use crate::config::CaptureMode;
+use crate::ingestion_warnings::{bounded_detail, emit_rate_limit_warning};
use crate::router;
use crate::v1::context::RequestContext;
use crate::v1::sinks::event::Event as SinkEvent;
@@ -56,11 +58,29 @@ fn destination_for_event_name(name: &str) -> Destination {
}
}
+/// Run the batch through the pipeline, then report its drops and build the
+/// response. The pipeline itself only decides each event's outcome; whatever
+/// stage it exits from, the warnings sweep sees the final outcomes exactly
+/// once, here.
pub async fn process_batch(
state: &router::State,
context: &mut Context,
batch: Batch,
) -> Result<BatchResponse, Error> {
+ let events = run_pipeline(state, context, batch).await?;
+ emit_drop_warnings(state, context, &events);
+ Ok(BatchResponse::build(context, &events))
+}
+
+/// Every stage of the v1 pipeline, from validation to publishing. Returns the
+/// events with their final per-event outcomes; a whole-batch failure is the
+/// `Err`. Stages that leave nothing to publish return early with what they
+/// have, so the 200 with per-event drops still comes from `process_batch`.
+async fn run_pipeline(
+ state: &router::State,
+ context: &mut Context,
+ batch: Batch,
+) -> Result<Vec<WrappedEvent>, Error> {
let processing_start = Instant::now();
crate::ctx_log!(Level::INFO, context, "process_batch called");
@@ -79,10 +99,6 @@ pub async fn process_batch(
}
};
- // Best-effort v2 ingestion warnings for validation drops, emitted before
- // the all-dropped early return so those batches are covered too.
- emit_validation_drop_warnings(state, context, &events);
-
// Import mode ingests only historical backfills: drop any batch not flagged
// `historical_migration` (a batch-level flag) by marking every event Drop and
// returning 200 (accept-and-discard) so the batch-import-worker doesn't retry.
@@ -100,12 +116,16 @@ pub async fn process_batch(
dropped_events = events.len(),
"import mode dropped non-historical batch"
);
- return Ok(BatchResponse::build(context, &events));
+ return Ok(events);
+ }
+
+ if state.capture_mode == CaptureMode::Ai {
+ drop_non_ai_events(state, context, &mut events);
}
// Nothing left to process — return 200 with per-event drops.
if events.iter().all(|ev| ev.result != EventResult::Ok) {
- return Ok(BatchResponse::build(context, &events));
+ return Ok(events);
}
// Verify gateway provenance before the quota limiter so verified events can
@@ -209,7 +229,7 @@ pub async fn process_batch(
all_results.extend(sink_results);
merge_sink_results(&mut events, &all_results);
- Ok(BatchResponse::build(context, &events))
+ Ok(events)
}
// Verify gateway provenance on each `$ai_*` event: a fresh, valid signature stamps
@@ -362,16 +382,17 @@ fn emit_batch_abort_warning(
);
}
-/// Best-effort v2 ingestion warnings for per-event validation drops: one
-/// message per registered drop tag with the deduped occurrence count.
+/// Best-effort v2 ingestion warnings for per-event drops: one message per
+/// registered drop tag with the deduped occurrence count.
/// `distinctId`/`eventUuid` are included only when a tag matched exactly one
/// event — with multiple events they would be ambiguous, so they are omitted.
/// Skips entirely when the emitter is off or the batch had no drops.
-fn emit_validation_drop_warnings(
- state: &router::State,
- context: &Context,
- events: &[WrappedEvent],
-) {
+///
+/// Runs once per batch, from `process_batch`, after the pipeline has settled
+/// every outcome, so a stage reports a drop by tagging it and nothing else.
+/// Whether the tag turns into a warning is decided in one place,
+/// `WarningType::from_tag`.
+fn emit_drop_warnings(state: &router::State, context: &Context, events: &[WrappedEvent]) {
let emitter = state.ingestion_warning_emitter.as_deref();
if emitter.is_none() {
// Checked up front so a deployment with warnings off doesn't pay for the
@@ -827,6 +848,81 @@ async fn apply_restrictions(
}
}
+/// Drop every event an AI-mode deployment was sent that is not on the AI lane.
+///
+/// capture-ai loads only the AI restriction slice (`Pipeline::for_capture_mode`),
+/// so an analytics, exception, or heatmap event reaching it would ingest
+/// governed by nothing. Refusing it is what keeps "which restrictions apply"
+/// answerable from the event name alone, on every deployment. Only the
+/// offenders drop, since v1 reports per-event outcomes; the v0 path on this
+/// deployment rejects the whole request (`CaptureError::NonAiEventOnAiLane`)
+/// because its contract has no way to say less. The gate runs before quota and
+/// restrictions so a refused event spends neither.
+fn drop_non_ai_events(state: &router::State, context: &Context, events: &mut [WrappedEvent]) {
+ let mut dropped: u64 = 0;
+ // Identifiers for the warning, kept only while exactly one event offended.
+ // With several they would be an arbitrary pick, and the count already says
+ // how many there were.
+ let mut single_offender: Option<(String, Uuid)> = None;
+
+ for event in events.iter_mut() {
+ // Gate on the event name, not the destination: `on_ai_lane` documents
+ // why the destination is the wrong question. `should_publish` rather
+ // than `result == Ok` so a Warning event -- which also publishes --
+ // cannot ride an analytics lane out of an AI deployment. Neither case
+ // is reachable at this point today; both make the gate correct on its
+ // own terms rather than on its position in the pipeline.
+ if !event.should_publish() || on_ai_lane(event) {
+ continue;
+ }
+ event.result = EventResult::Drop;
+ event.destination = Destination::Drop;
+ event.details = Some(DETAIL_NON_AI_EVENT);
+ dropped += 1;
+ single_offender = match dropped {
+ 1 => Some((event.event.event.clone(), event.uuid)),
+ _ => None,
+ };
+ }
+
+ if dropped == 0 {
+ return;
+ }
+
+ metrics::counter!(CAPTURE_V1_EVENTS_DROPPED, "reason" => "non_ai_event").increment(dropped);
+ // DEBUG, not WARN: a client sending the wrong event name is not an operator
+ // problem, and the SDKs route on the `$ai_` prefix while this gate is the
+ // narrower name allowlist, so it is expected to fire at client volume. The
+ // counter above carries the alerting signal and the warning below tells the
+ // project owner.
+ crate::ctx_log!(
+ Level::DEBUG,
+ context,
+ dropped_events = dropped,
+ "dropped non-AI events sent to the AI lane"
+ );
+
+ // The same `invalid_ai_event` type the v0 AI endpoint emits for an event
+ // name off the allowlist: identical mistake, so a reader of the v2 warnings
+ // table doesn't have to learn a second vocabulary for it.
+ let mut details = serde_json::Map::new();
+ if let Some((event_name, uuid)) = single_offender {
+ details.insert(
+ "eventName".to_string(),
+ serde_json::json!(bounded_detail(&event_name)),
+ );
+ details.insert("eventUuid".to_string(), serde_json::json!(uuid.to_string()));
+ }
+ emit_request_warning(
+ state.ingestion_warning_emitter.as_deref(),
+ &context.warning_context(),
+ CAPTURE_V1_ANALYTICS,
+ WarningType::InvalidAiEvent,
+ details,
+ dropped,
+ );
+}
+
/// Whether this event rides the AI lane, independent of where restrictions
/// have since pointed it.
///
@@ -4317,6 +4413,322 @@ mod tests {
);
}
+ // =========================================================================
+ // AI-mode process_batch tests — the non-AI event gate
+ // =========================================================================
+
+ fn named_event(name: &str) -> Event {
+ Event {
+ event: name.to_string(),
+ ..valid_event()
+ }
+ }
+
+ #[tokio::test]
+ async fn ai_mode_drops_non_ai_events_and_publishes_the_rest() {
+ let ts = TestStateBuilder::new()
+ .with_capture_mode(CaptureMode::Ai)
+ .build();
+ let mut ctx = test_utils::test_analytics_context();
+ let ai = named_event("$ai_generation");
+ let ai_uuid = ai.uuid.clone();
+ let batch = valid_batch(vec![
+ ai,
+ named_event("$pageview"),
+ named_event("$exception"),
+ ]);
+
+ let resp = process_batch(&ts.state, &mut ctx, batch).await.unwrap();
+
+ let entries = resp.entries();
+ assert_eq!(entries.len(), 3);
+ for (uuid, entry) in entries {
+ if uuid.to_string() == ai_uuid {
+ assert_eq!(entry.result, EventResult::Ok);
+ } else {
+ assert_eq!(entry.result, EventResult::Drop);
+ assert_eq!(entry.details, Some(DETAIL_NON_AI_EVENT));
+ }
+ }
+ assert!(!resp.has_retry, "a gated batch must not signal retry");
+
+ ts.mock_producer.with_records(|records| {
+ assert_eq!(records.len(), 1, "only the AI event may publish");
+ assert_eq!(records[0].topic, "ai_events");
+ });
+ }
+
+ /// Lane membership is the `AI_EVENT_NAMES` allowlist, so an `$ai_`-prefixed
+ /// name that is not on it is dropped like any other non-AI event; the Node
+ /// AI pipeline would DLQ it anyway.
+ #[rstest::rstest]
+ #[case::allowlisted("$ai_generation", EventResult::Ok)]
+ #[case::allowlisted_span("$ai_span", EventResult::Ok)]
+ #[case::prefixed_but_unlisted("$ai_not_a_real_event", EventResult::Drop)]
+ #[case::analytics("$pageview", EventResult::Drop)]
+ #[case::exception("$exception", EventResult::Drop)]
+ #[case::heatmap("$$heatmap", EventResult::Drop)]
+ #[tokio::test]
+ async fn ai_mode_gates_on_the_ai_event_allowlist(
+ #[case] event_name: &str,
+ #[case] expected: EventResult,
+ ) {
+ let ts = TestStateBuilder::new()
+ .with_capture_mode(CaptureMode::Ai)
+ .build();
+ let mut ctx = test_utils::test_analytics_context();
+ let batch = valid_batch(vec![named_event(event_name)]);
+
+ let resp = process_batch(&ts.state, &mut ctx, batch).await.unwrap();
+
+ let (_, entry) = &resp.entries()[0];
+ assert_eq!(entry.result, expected, "event={event_name}");
+ if expected == EventResult::Drop {
+ assert_eq!(entry.details, Some(DETAIL_NON_AI_EVENT));
+ }
+ }
+
+ /// The control proving the gate is mode-scoped, not a change to how the
+ /// shared pipeline treats these names.
+ #[tokio::test]
+ async fn events_mode_leaves_non_ai_events_alone() {
+ let ts = TestStateBuilder::new().build();
+ let mut ctx = test_utils::test_analytics_context();
+ let batch = valid_batch(vec![
+ named_event("$ai_generation"),
+ named_event("$pageview"),
+ named_event("$exception"),
+ ]);
+
+ let resp = process_batch(&ts.state, &mut ctx, batch).await.unwrap();
+
+ for (_, entry) in resp.entries() {
+ assert_eq!(entry.result, EventResult::Ok);
+ assert_eq!(entry.details, None);
+ }
+ ts.mock_producer
+ .with_records(|records| assert_eq!(records.len(), 3));
+ }
+
+ /// A batch with nothing but non-AI events leaves no event publishable, so
+ /// the gate hands straight to the all-dropped early return. Every other
+ /// AI-mode test keeps at least one `$ai_` event, so this is the only one
+ /// that exercises that path: the response must still be a 200 carrying a
+ /// per-event verdict for each event, not an error.
+ #[tokio::test]
+ async fn ai_mode_batch_of_only_non_ai_events_returns_200_with_every_event_dropped() {
+ let ts = TestStateBuilder::new()
+ .with_capture_mode(CaptureMode::Ai)
+ .build();
+ let mut ctx = test_utils::test_analytics_context();
+ let batch = valid_batch(vec![
+ named_event("$pageview"),
+ named_event("$exception"),
+ named_event("$ai_not_a_real_event"),
+ ]);
+
+ let resp = process_batch(&ts.state, &mut ctx, batch).await.unwrap();
+
+ let entries = resp.entries();
+ assert_eq!(entries.len(), 3, "every event still gets a verdict");
+ for (_, entry) in entries {
+ assert_eq!(entry.result, EventResult::Drop);
+ assert_eq!(entry.details, Some(DETAIL_NON_AI_EVENT));
+ }
+ assert!(!resp.has_retry, "a fully gated batch must not signal retry");
+ ts.mock_producer
+ .with_records(|records| assert!(records.is_empty(), "nothing may publish"));
+ }
+
+ /// The gate keys on the event name, not the destination, so a restriction
+ /// that has already retargeted an AI event cannot smuggle it into the
+ /// non-AI drop. `force_overflow` sends it to `AiEventsOverflow`,
+ /// `redirect_to_topic` to `Custom`, a DLQ restriction to `Dlq` -- all three
+ /// are still the AI lane.
+ ///
+ /// `apply_restrictions` runs after the gate, so this state is not reachable
+ /// through `process_batch`. The gate is called directly here so the
+ /// invariant holds on its own terms rather than on stage ordering: if the
+ /// two stages were ever reordered, nothing else in the suite would fail.
+ #[rstest::rstest]
+ #[case::force_overflow(Destination::AiEventsOverflow)]
+ #[case::redirect_to_topic(Destination::Custom("some_other_topic".to_string()))]
+ #[case::redirect_to_dlq(Destination::Dlq)]
+ #[tokio::test]
+ async fn ai_lane_events_survive_the_gate_wherever_restrictions_pointed_them(
+ #[case] destination: Destination,
+ ) {
+ let ts = TestStateBuilder::new()
+ .with_capture_mode(CaptureMode::Ai)
+ .build();
+ let ctx = test_utils::test_analytics_context();
+ let mut events = vec![test_utils::wrapped_event("$ai_generation", "user-1")
+ .with_destination(destination.clone())];
+
+ drop_non_ai_events(&ts.state, &ctx, &mut events);
+
+ assert_eq!(
+ events[0].result,
+ EventResult::Ok,
+ "an allowlisted AI event stays on the lane wherever it was pointed"
+ );
+ assert_eq!(events[0].destination, destination);
+ assert_eq!(events[0].details, None);
+ }
+
+ /// The other direction: a destination of `AiEvents` does not put a non-AI
+ /// event on the lane. Only the event name decides membership.
+ #[tokio::test]
+ async fn a_non_ai_event_pointed_at_the_ai_destination_is_still_dropped() {
+ let ts = TestStateBuilder::new()
+ .with_capture_mode(CaptureMode::Ai)
+ .build();
+ let ctx = test_utils::test_analytics_context();
+ let mut events = vec![test_utils::wrapped_event("$pageview", "user-1")
+ .with_destination(Destination::AiEvents)];
+
+ drop_non_ai_events(&ts.state, &ctx, &mut events);
+
+ assert_eq!(events[0].result, EventResult::Drop);
+ assert_eq!(events[0].destination, Destination::Drop);
+ assert_eq!(events[0].details, Some(DETAIL_NON_AI_EVENT));
+ }
+
+ #[tokio::test]
+ async fn ai_mode_non_ai_drop_emits_the_invalid_ai_event_warning() {
+ let collector = Arc::new(CollectingEmitter::new());
+ let ts = TestStateBuilder::new()
+ .with_capture_mode(CaptureMode::Ai)
+ .with_ingestion_warning_emitter(collector.clone())
+ .build();
+ let mut ctx = test_utils::test_analytics_context();
+ let offender = named_event("$pageview");
+ let offender_uuid = offender.uuid.clone();
+ let batch = valid_batch(vec![named_event("$ai_generation"), offender]);
+
+ process_batch(&ts.state, &mut ctx, batch).await.unwrap();
+
+ let emitted = collector.emitted();
+ assert_eq!(emitted.len(), 1);
+ assert_eq!(emitted[0].warning, WarningType::InvalidAiEvent);
+ assert_eq!(emitted[0].count, 1);
+ assert_eq!(
+ emitted[0].extra_details.get("eventName"),
+ Some(&serde_json::json!("$pageview"))
+ );
+ assert_eq!(
+ emitted[0].extra_details.get("eventUuid"),
+ Some(&serde_json::json!(offender_uuid))
+ );
+ }
+
+ /// An oversized AI event must stay visible to the project owner. v0 maps
+ /// `CaptureError::AiEventTooBig` to `MessageSizeTooLarge`; v1 reaches the
+ /// same warning through the drop tag. The ceiling applies on every
+ /// deployment that carries AI events, so the warning does too: SDKs send
+ /// `$ai_*` events through the analytics endpoint as well.
+ #[rstest::rstest]
+ #[case::ai_deployment(CaptureMode::Ai)]
+ #[case::analytics_deployment(CaptureMode::Events)]
+ #[tokio::test]
+ async fn oversize_ai_event_emits_the_message_size_warning(#[case] capture_mode: CaptureMode) {
+ let collector = Arc::new(CollectingEmitter::new());
+ let ts = TestStateBuilder::new()
+ .with_capture_mode(capture_mode)
+ .with_ai_max_event_bytes(700)
+ .with_ingestion_warning_emitter(collector.clone())
+ .build();
+ let mut ctx = test_utils::test_analytics_context();
+
+ let mut oversized = named_event("$ai_generation");
+ oversized.properties =
+ test_utils::raw_obj(&format!(r#"{{"$ai_input":"{}"}}"#, "x".repeat(800)));
+ let oversized_uuid = oversized.uuid.clone();
+ let batch = valid_batch(vec![oversized, named_event("$ai_generation")]);
+
+ let resp = process_batch(&ts.state, &mut ctx, batch).await.unwrap();
+
+ let dropped: Vec<_> = resp
+ .entries()
+ .iter()
+ .filter(|(_, e)| e.result == EventResult::Drop)
+ .collect();
+ assert_eq!(dropped.len(), 1, "only the oversized event drops");
+ assert_eq!(dropped[0].1.details, Some(DETAIL_AI_EVENT_TOO_BIG));
+
+ let emitted = collector.emitted();
+ assert_eq!(emitted.len(), 1, "exactly one warning, not one per pass");
+ assert_eq!(emitted[0].warning, WarningType::MessageSizeTooLarge);
+ assert_eq!(emitted[0].count, 1);
+ assert_eq!(
+ emitted[0].extra_details.get("eventUuid"),
+ Some(&serde_json::json!(oversized_uuid))
+ );
+ }
+
+ /// Drops from different stages of one batch each surface once. Validation
+ /// and the AI size ceiling both drop an event here; the single end-of-batch
+ /// sweep reports both without repeating either.
+ #[tokio::test]
+ async fn drops_from_several_stages_each_surface_once() {
+ let collector = Arc::new(CollectingEmitter::new());
+ let ts = TestStateBuilder::new()
+ .with_capture_mode(CaptureMode::Ai)
+ .with_ai_max_event_bytes(700)
+ .with_ingestion_warning_emitter(collector.clone())
+ .build();
+ let mut ctx = test_utils::test_analytics_context();
+
+ let mut oversized = named_event("$ai_generation");
+ oversized.properties =
+ test_utils::raw_obj(&format!(r#"{{"$ai_input":"{}"}}"#, "x".repeat(800)));
+ let mut no_distinct_id = named_event("$ai_generation");
+ no_distinct_id.distinct_id = String::new();
+
+ let batch = valid_batch(vec![
+ oversized,
+ no_distinct_id,
+ named_event("$ai_generation"),
+ ]);
+
+ process_batch(&ts.state, &mut ctx, batch).await.unwrap();
+
+ let emitted = collector.emitted();
+ let mut seen: Vec<_> = emitted.iter().map(|e| e.warning).collect();
+ seen.sort_by_key(|w| w.as_str());
+ let unique: std::collections::HashSet<_> = seen.iter().collect();
+ assert_eq!(
+ seen.len(),
+ unique.len(),
+ "each warning type may be emitted at most once: {seen:?}"
+ );
+ assert!(seen.contains(&WarningType::MessageSizeTooLarge));
+ assert!(seen.contains(&WarningType::MissingDistinctId));
+ }
+
+ /// With several offenders the identifiers would be an arbitrary pick, so
+ /// only the count rides along, the same rule the validation-drop warnings
+ /// follow.
+ #[tokio::test]
+ async fn ai_mode_several_non_ai_drops_report_a_count_without_identifiers() {
+ let collector = Arc::new(CollectingEmitter::new());
+ let ts = TestStateBuilder::new()
+ .with_capture_mode(CaptureMode::Ai)
+ .with_ingestion_warning_emitter(collector.clone())
+ .build();
+ let mut ctx = test_utils::test_analytics_context();
+ let batch = valid_batch(vec![named_event("$pageview"), named_event("$exception")]);
+
+ process_batch(&ts.state, &mut ctx, batch).await.unwrap();
+
+ let emitted = collector.emitted();
+ assert_eq!(emitted.len(), 1);
+ assert_eq!(emitted[0].warning, WarningType::InvalidAiEvent);
+ assert_eq!(emitted[0].count, 2);
+ assert!(!emitted[0].extra_details.contains_key("eventName"));
+ assert!(!emitted[0].extra_details.contains_key("eventUuid"));
+ }
+
// =========================================================================
// Ingestion warning emission — process_batch with a CollectingEmitter
// =========================================================================
diff --git a/rust/capture/src/v1/analytics/router.rs b/rust/capture/src/v1/analytics/router.rs
index 95499781380b..3a892fb69447 100644
--- a/rust/capture/src/v1/analytics/router.rs
+++ b/rust/capture/src/v1/analytics/router.rs
@@ -1,6 +1,8 @@
use axum::Router;
-use super::constants::{CAPTURE_V1_PATH, CAPTURE_V1_PATH_TRAILING};
+use super::constants::{
+ CAPTURE_V1_AI_PATH, CAPTURE_V1_AI_PATH_TRAILING, CAPTURE_V1_PATH, CAPTURE_V1_PATH_TRAILING,
+};
use crate::router::State;
/// Route declarations only. The shared v1 middleware stack (headers, metrics,
@@ -16,3 +18,26 @@ pub fn routes() -> Router<State> {
axum::routing::post(super::handler::handle_request),
)
}
+
+/// The AI lane's v1 endpoint. Same handler, same request and response
+/// contract, same middleware; only the path differs, so the ingress can send
+/// v1 AI traffic to capture-ai, which produces straight to the AI topic and
+/// applies its own `AI_MAX_EVENT_BYTES` ceiling.
+///
+/// The handler needs no AI-specific branch: every AI behavior in the v1
+/// pipeline (gateway provenance, the llm_events quota exemption, `Pipeline::Ai`
+/// restrictions, the per-event size ceiling, the byte-rate limiter, and the
+/// `Destination::AiEvents` lane itself) keys off the event name, not the path.
+/// What the path decides is which deployment answers, which `crate::router`
+/// gates on the capture mode.
+pub fn ai_routes() -> Router<State> {
+ Router::new()
+ .route(
+ CAPTURE_V1_AI_PATH,
+ axum::routing::post(super::handler::handle_request),
+ )
+ .route(
+ CAPTURE_V1_AI_PATH_TRAILING,
+ axum::routing::post(super::handler::handle_request),
+ )
+}
diff --git a/rust/capture/src/v1/router.rs b/rust/capture/src/v1/router.rs
index 26a30f11194b..cfad0964b4a1 100644
--- a/rust/capture/src/v1/router.rs
+++ b/rust/capture/src/v1/router.rs
@@ -24,8 +24,15 @@ pub struct RouterConfig {
/// Backstop only: `v1::util` enforces the real compressed-size limit and
/// returns the 413 envelope before this extractor-level limit can trip.
pub max_compressed_body_bytes: usize,
+ /// Mount `/i/v1/analytics/events`.
+ pub serves_analytics: bool,
+ /// Mount `/i/v1/ai/events`.
+ pub serves_ai_events: bool,
}
+/// Builds the v1 router for the endpoints this deployment mounts. The choice
+/// is made per capture mode in `crate::router`, which owns the
+/// route-to-deployment split for every path capture serves.
pub fn router(cfg: RouterConfig) -> Router<State> {
// v1 endpoints are POST-only; preflight is answered by the CORS layer.
let cors = CorsLayer::new()
@@ -34,8 +41,15 @@ pub fn router(cfg: RouterConfig) -> Router<State> {
.allow_credentials(true)
.allow_origin(AllowOrigin::mirror_request());
- let mut router = crate::v1::analytics::router::routes()
- .layer(DefaultBodyLimit::max(cfg.max_compressed_body_bytes));
+ let mut routes = Router::new();
+ if cfg.serves_analytics {
+ routes = routes.merge(crate::v1::analytics::router::routes());
+ }
+ if cfg.serves_ai_events {
+ routes = routes.merge(crate::v1::analytics::router::ai_routes());
+ }
+
+ let mut router = routes.layer(DefaultBodyLimit::max(cfg.max_compressed_body_bytes));
if let Some(limit) = cfg.concurrency_limit {
router = router.layer(ConcurrencyLimitLayer::new(limit));
@@ -71,6 +85,8 @@ mod tests {
RouterConfig {
concurrency_limit: Some(8),
max_compressed_body_bytes: 1024 * 1024,
+ serves_analytics: true,
+ serves_ai_events: false,
}
}
diff --git a/rust/capture/src/v1/test_utils.rs b/rust/capture/src/v1/test_utils.rs
index 4b1f98f73649..4b52413552c9 100644
--- a/rust/capture/src/v1/test_utils.rs
+++ b/rust/capture/src/v1/test_utils.rs
@@ -705,6 +705,7 @@ pub struct TestStateBuilder {
ai_gateway_signing_secret: Option<String>,
ingestion_warning_emitter: Option<Arc<dyn common_ingestion_warnings::WarningEmitter>>,
capture_mode: CaptureMode,
+ ai_max_event_bytes: u64,
}
impl Default for TestStateBuilder {
@@ -729,6 +730,7 @@ impl TestStateBuilder {
ai_gateway_signing_secret: None,
ingestion_warning_emitter: None,
capture_mode: CaptureMode::Events,
+ ai_max_event_bytes: 0,
}
}
@@ -823,6 +825,12 @@ impl TestStateBuilder {
self
}
+ /// Set the per-event AI ceiling (defaults to `0`, which disables it).
+ pub fn with_ai_max_event_bytes(mut self, bytes: u64) -> Self {
+ self.ai_max_event_bytes = bytes;
+ self
+ }
+
pub fn build(self) -> TestState {
let mut manager = lifecycle::Manager::builder("test_state")
.with_trap_signals(false)
@@ -933,7 +941,7 @@ 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,
+ ai_max_event_bytes: self.ai_max_event_bytes,
body_chunk_read_timeout: None,
body_read_chunk_size_kb: 64,
capture_v1_max_compressed_body_bytes: 2 * 1024 * 1024,
diff --git a/rust/capture/tests/common/integration_utils.rs b/rust/capture/tests/common/integration_utils.rs
index 6a7a90d3c3af..229aff1e1712 100644
--- a/rust/capture/tests/common/integration_utils.rs
+++ b/rust/capture/tests/common/integration_utils.rs
@@ -13,6 +13,7 @@ use capture::{
router::router,
time::TimeSource,
v0_request::{DataType, ProcessedEvent},
+ v1::test_utils::TestStateBuilder,
};
use chrono::{DateTime, Utc};
@@ -1054,16 +1055,32 @@ pub fn test_lifecycle_handlers() -> (
}
fn setup_capture_router(unit: &TestCase) -> (Router, MemorySink) {
- build_router_for_mode_at(unit.mode, unit.fixed_time)
+ build_router_for_mode_at(unit.mode, unit.fixed_time, None)
}
// Builds a capture router for a given mode with test defaults, so route-registration
// tests can assert which paths a mode serves without constructing a full TestCase.
pub fn build_router_for_mode(mode: CaptureMode) -> Router {
- build_router_for_mode_at(mode, DEFAULT_TEST_TIME).0
+ build_router_for_mode_at(mode, DEFAULT_TEST_TIME, None).0
}
-fn build_router_for_mode_at(mode: CaptureMode, fixed_time: &str) -> (Router, MemorySink) {
+// Same, plus a v1 sink router. The v1 paths stay unregistered without one, so a
+// mode-gating assertion needs a sink to tell "this mode does not serve the path"
+// apart from "this deployment has no v1 sink".
+pub fn build_router_for_mode_with_v1_sink(mode: CaptureMode) -> Router {
+ let v1_sink_router = TestStateBuilder::new()
+ .with_capture_mode(mode)
+ .build()
+ .state
+ .v1_sink_router;
+ build_router_for_mode_at(mode, DEFAULT_TEST_TIME, v1_sink_router).0
+}
+
+fn build_router_for_mode_at(
+ mode: CaptureMode,
+ fixed_time: &str,
+ v1_sink_router: Option<Arc<capture::v1::sinks::Router>>,
+) -> (Router, MemorySink) {
let (readiness, liveness, _monitor) = test_lifecycle_handlers();
let sink = MemorySink::default();
let timesource = FixedTime {
@@ -1114,11 +1131,11 @@ fn build_router_for_mode_at(mode: CaptureMode, fixed_time: &str) -> (Router, Mem
None, // 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
- false, // ai_events_overflow_enabled
- None, // ingestion_warning_emitter
+ v1_sink_router,
+ 8, // capture_v1_scatter_gather_min_batch
+ None, // ai_gateway_signing_secret
+ false, // ai_events_overflow_enabled
+ None, // ingestion_warning_emitter
),
sink,
)
diff --git a/rust/capture/tests/integration_ai_route_surface.rs b/rust/capture/tests/integration_ai_route_surface.rs
index 2db9f6c18b68..a9dc57152d61 100644
--- a/rust/capture/tests/integration_ai_route_surface.rs
+++ b/rust/capture/tests/integration_ai_route_surface.rs
@@ -10,8 +10,9 @@
//! 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.
+//! The pipeline-level gates cover the other half — an event name off the AI
+//! allowlist arriving on a path that IS registered: `events::analytics` for the
+//! v0 paths, `v1::analytics::process` for `/i/v1/ai/events`.
#[path = "common/integration_utils.rs"]
mod integration_utils;
@@ -19,7 +20,7 @@ mod integration_utils;
use axum::http::StatusCode;
use axum_test_helper::TestClient;
use capture::config::CaptureMode;
-use integration_utils::build_router_for_mode;
+use integration_utils::{build_router_for_mode, build_router_for_mode_with_v1_sink};
use rstest::rstest;
use serde_json::json;
@@ -100,7 +101,6 @@ async fn assert_answer(mode: CaptureMode, path: &str, expected: Answer) {
#[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;
@@ -147,3 +147,97 @@ async fn import_mode_registers_only_the_analytics_paths(
) {
assert_answer(CaptureMode::Import, path, expected).await;
}
+
+// ---------------------------------------------------------------------------
+// v1 endpoints
+// ---------------------------------------------------------------------------
+
+/// Post a real v1 batch to `path` on a router built for `mode` with a v1 sink
+/// wired, and pin what comes back.
+///
+/// Unlike the v0 cases above, the payload is one the endpoint fully accepts, so
+/// [`Answer::Served`] is the 200 a completed publish returns rather than a status
+/// from some earlier validation step. The event is an `$ai_generation`, which
+/// both endpoints accept: the analytics endpoint diverts it to the AI lane by
+/// name, and the AI endpoint's non-AI gate lets it through.
+async fn assert_v1_answer(mode: CaptureMode, path: &str, expected: Answer) {
+ let mut event = capture::v1::test_utils::valid_event();
+ event.event = "$ai_generation".to_string();
+ let payload = capture::v1::test_utils::batch_payload(&[event]);
+
+ let status = TestClient::new(build_router_for_mode_with_v1_sink(mode))
+ .post(path)
+ .body(payload)
+ .header("Authorization", "Bearer phc_route_surface_token")
+ .header("Content-Type", "application/json")
+ .header("X-Forwarded-For", "127.0.0.1")
+ .header("PostHog-Sdk-Info", "posthog-rs/1.0.0")
+ .header("PostHog-Attempt", "1")
+ .header("PostHog-Request-Id", uuid::Uuid::new_v4().to_string())
+ .header("PostHog-Request-Timestamp", "2026-03-19T14:30:00Z")
+ .header("User-Agent", "test-agent/1.0")
+ .send()
+ .await
+ .status();
+
+ assert_eq!(
+ status,
+ expected.status(),
+ "{mode:?} answered {path} with {status}, expected {expected:?}"
+ );
+}
+
+/// capture-ai serves the v1 contract on its own path only. It must not also
+/// serve `/i/v1/analytics/events`: that endpoint accepts any event name and its
+/// traffic is governed by analytics restrictions, which capture-ai does not load.
+#[rstest]
+#[case::ai_events("/i/v1/ai/events", Answer::Served(StatusCode::OK))]
+#[case::ai_events_trailing_slash("/i/v1/ai/events/", Answer::Served(StatusCode::OK))]
+#[case::analytics_events("/i/v1/analytics/events", Answer::Absent)]
+#[case::analytics_events_trailing_slash("/i/v1/analytics/events/", Answer::Absent)]
+#[tokio::test]
+async fn ai_mode_serves_only_the_v1_ai_endpoint(#[case] path: &str, #[case] expected: Answer) {
+ assert_v1_answer(CaptureMode::Ai, path, expected).await;
+}
+
+/// The mirror image: the analytics deployments keep the analytics endpoint and
+/// never register the AI one. They still ingest `$ai_*` events, which divert to
+/// the AI lane by event name on the analytics path.
+#[rstest]
+#[case::events_analytics(
+ CaptureMode::Events,
+ "/i/v1/analytics/events",
+ Answer::Served(StatusCode::OK)
+)]
+#[case::events_ai(CaptureMode::Events, "/i/v1/ai/events", Answer::Absent)]
+#[case::events_ai_trailing_slash(CaptureMode::Events, "/i/v1/ai/events/", Answer::Absent)]
+#[case::import_analytics(
+ CaptureMode::Import,
+ "/i/v1/analytics/events",
+ Answer::Served(StatusCode::OK)
+)]
+#[case::import_ai(CaptureMode::Import, "/i/v1/ai/events", Answer::Absent)]
+#[case::recordings_analytics(CaptureMode::Recordings, "/i/v1/analytics/events", Answer::Absent)]
+#[case::recordings_ai(CaptureMode::Recordings, "/i/v1/ai/events", Answer::Absent)]
+#[tokio::test]
+async fn non_ai_modes_never_serve_the_v1_ai_endpoint(
+ #[case] mode: CaptureMode,
+ #[case] path: &str,
+ #[case] expected: Answer,
+) {
+ assert_v1_answer(mode, path, expected).await;
+}
+
+/// Without a v1 sink the paths stay unregistered on every mode, which is what
+/// makes the sink-wired assertions above say something about the mode gating
+/// rather than about sink presence.
+#[rstest]
+#[case::ai(CaptureMode::Ai, "/i/v1/ai/events")]
+#[case::events(CaptureMode::Events, "/i/v1/analytics/events")]
+#[tokio::test]
+async fn v1_paths_stay_unregistered_without_a_v1_sink(
+ #[case] mode: CaptureMode,
+ #[case] path: &str,
+) {
+ assert_answer(mode, path, Answer::Absent).await;
+}
diff --git a/rust/capture/tests/integration_person_processing_matrix.rs b/rust/capture/tests/integration_person_processing_matrix.rs
index 0dade80b71c1..178161b72e75 100644
--- a/rust/capture/tests/integration_person_processing_matrix.rs
+++ b/rust/capture/tests/integration_person_processing_matrix.rs
@@ -335,6 +335,8 @@ async fn run_v1(inputs: Inputs, distinct_ids: &[&str]) -> Batch {
let router = v1_router(V1RouterConfig {
concurrency_limit: None,
max_compressed_body_bytes: 10 * 1024 * 1024,
+ serves_analytics: true,
+ serves_ai_events: false,
})
.with_state(ts.state.clone());
diff --git a/rust/common/ingestion_warnings/src/registry.rs b/rust/common/ingestion_warnings/src/registry.rs
index 023df533336b..68171e699a20 100644
--- a/rust/common/ingestion_warnings/src/registry.rs
+++ b/rust/common/ingestion_warnings/src/registry.rs
@@ -74,6 +74,13 @@ impl WarningType {
"invalid_event_uuid" => Some(Self::InvalidEventUuid),
"duplicate_event_uuid" => Some(Self::DuplicateEventUuid),
"message_size_too_large" => Some(Self::MessageSizeTooLarge),
+ // The v1 AI lane's per-event ceiling. v0 reports the same condition
+ // as `CaptureError::AiEventTooBig`, which already maps here, so
+ // moving AI traffic onto the v1 endpoint keeps the warning a
+ // project owner already sees for an oversized event. An alias, not
+ // a second route: `MessageSizeTooLarge` stays tag-derived, so the
+ // one-route-per-type invariant below is untouched.
+ "ai_event_too_big" => Some(Self::MessageSizeTooLarge),
_ => None,
}
}
@@ -120,7 +127,13 @@ mod tests {
}
// Excluded on purpose: intentional drops, auth/transport/server errors, and
- // post-validation drops are not data-quality signals for the v2 surface.
+ // ops-imposed drops are not data-quality signals for the v2 surface.
+ //
+ // "Post-validation" is not itself the test -- customer-actionable is.
+ // `event_restriction` is excluded because the operator caused it and the
+ // project owner cannot act on it; `ai_event_too_big` is included, after the
+ // same stage, because the customer sent an oversized event and v0 already
+ // tells them so.
#[rstest]
#[case::intentional_drop("dropped_performance_event")]
#[case::auth("invalid_api_token")]