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): both v1 lanes refuse the other's events (#95466)

Eli Reisman9aace6e5ce60
diff --git a/frontend/src/scenes/data-management/ingestion-warnings/IngestionWarningsView.tsx b/frontend/src/scenes/data-management/ingestion-warnings/IngestionWarningsView.tsx
index c6dc0e71d0a5..186ed5ae54b7 100644
--- a/frontend/src/scenes/data-management/ingestion-warnings/IngestionWarningsView.tsx
+++ b/frontend/src/scenes/data-management/ingestion-warnings/IngestionWarningsView.tsx
@@ -58,6 +58,8 @@ export const WARNING_TYPE_TO_DESCRIPTION: Record<string, string> = {
high_volume_distinct_id: 'Skipped person profile processing for a high-volume distinct ID',
// Emitted by the capture service for its AI endpoints
invalid_ai_event: 'Discarded an AI event with an unsupported event name or no $ai_model',
+ misrouted_event:
+ 'Discarded an event sent to the wrong capture endpoint. Send events named $ai_* to the AI endpoint, and everything else to the analytics endpoint',
invalid_ai_payload: 'Rejected a malformed AI or OpenTelemetry request',
no_ai_spans_ingested: 'Accepted an OpenTelemetry export with no AI spans, so nothing was ingested',
// Emitted by the capture service for its session replay endpoint
diff --git a/nodejs/src/ingestion/common/ingestion-warning-types.ts b/nodejs/src/ingestion/common/ingestion-warning-types.ts
index b53a84cc7627..5fed2f96cdae 100644
--- a/nodejs/src/ingestion/common/ingestion-warning-types.ts
+++ b/nodejs/src/ingestion/common/ingestion-warning-types.ts
@@ -76,6 +76,13 @@ export const INGESTION_WARNING_TYPES = {
// rather than a JSON batch.
invalid_ai_event: { category: 'event', severity: 'error', captureProduced: true },
invalid_ai_payload: { category: 'event', severity: 'error', captureProduced: true },
+ // An event posted to the wrong capture endpoint, in either direction: an AI-lane
+ // event name on /i/v1/analytics/events, or a non-AI-lane name on /i/v1/ai/events.
+ // The event is well-formed -- only its destination is wrong -- so this is not an
+ // `invalid_*` type. One type covers both directions; the warning's `path` detail
+ // says which way the misroute went, and the emitting deployment (capture-analytics
+ // vs capture-ai) distinguishes them on the metric.
+ misrouted_event: { category: 'event', severity: 'error', captureProduced: true },
// Severity is 'warning', not 'error': the OTLP export succeeded and only
// non-AI spans were in it, so nothing the AI pipeline owns was dropped. The
// customer still needs to know their export produced no AI events.
diff --git a/products/ingestion/skills/resolving-ingestion-warnings/SKILL.md b/products/ingestion/skills/resolving-ingestion-warnings/SKILL.md
index 7f6f3c0d1016..378d477f5113 100644
--- a/products/ingestion/skills/resolving-ingestion-warnings/SKILL.md
+++ b/products/ingestion/skills/resolving-ingestion-warnings/SKILL.md
@@ -76,11 +76,12 @@ Those decisions come only from this skill's guidance and your own reasoning.
Emitted by capture for its two dedicated AI endpoints, `/i/v0/ai` (a single event per request, sent multipart) and `/i/v0/ai/otel` (OTLP traces). These reject at the edge, so the events never reach the pipeline and appear nowhere else. Read the `path` detail to tell the endpoints apart: it carries the request path, so `/i/v0/ai` or `/i/v0/ai/otel`.
-| Type | What happened | Fix |
-| ---------------------- | ------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| `invalid_ai_event` | Event rejected: the name isn't one of the six `$ai_*` types, or `$ai_model` is missing or not a string | Read [references/fixing-ai-endpoint-rejections.md](references/fixing-ai-endpoint-rejections.md) — usually ordinary analytics pointed at the AI endpoint |
-| `invalid_ai_payload` | Request rejected: malformed multipart or OTLP body, or too many spans in one export | Read [references/fixing-ai-endpoint-rejections.md](references/fixing-ai-endpoint-rejections.md) — `format`, `stage`, and `part` details name which check failed |
-| `no_ai_spans_ingested` | OTLP export accepted with a 200 but contained no AI spans, so nothing was ingested | Read [references/fixing-ai-endpoint-rejections.md](references/fixing-ai-endpoint-rejections.md) — instrumentation is emitting spans no AI provider convention matches |
+| Type | What happened | Fix |
+| ---------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
+| `invalid_ai_event` | Event rejected: the name isn't one of the six `$ai_*` types, or `$ai_model` is missing or not a string | Read [references/fixing-ai-endpoint-rejections.md](references/fixing-ai-endpoint-rejections.md) — usually ordinary analytics pointed at the AI endpoint |
+| `invalid_ai_payload` | Request rejected: malformed multipart or OTLP body, or too many spans in one export | Read [references/fixing-ai-endpoint-rejections.md](references/fixing-ai-endpoint-rejections.md) — `format`, `stage`, and `part` details name which check failed |
+| `no_ai_spans_ingested` | OTLP export accepted with a 200 but contained no AI spans, so nothing was ingested | Read [references/fixing-ai-endpoint-rejections.md](references/fixing-ai-endpoint-rejections.md) — instrumentation is emitting spans no AI provider convention matches |
+| `misrouted_event` | Event posted to the wrong v1 endpoint: an `$ai_`-prefixed name on `/i/v1/analytics/events`, or a name without that prefix on `/i/v1/ai/events`. A per-event drop inside a 200, so the rest of the batch still publishes | The event is well formed and only its destination is wrong. On v1 the caller picks an endpoint per event: `$ai_*` names go to `/i/v1/ai/events`, everything else to `/i/v1/analytics/events`. The `path` detail says which way the misroute went |
### Heatmaps (`event`)
diff --git a/rust/capture/src/event_restrictions/types.rs b/rust/capture/src/event_restrictions/types.rs
index e2ffe68e24b7..9bba4ff05a50 100644
--- a/rust/capture/src/event_restrictions/types.rs
+++ b/rust/capture/src/event_restrictions/types.rs
@@ -69,7 +69,7 @@ impl Pipeline {
// 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
+ // `drop_misrouted_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/v0_request.rs b/rust/capture/src/v0_request.rs
index 3290fb62b314..7beb0039b687 100644
--- a/rust/capture/src/v0_request.rs
+++ b/rust/capture/src/v0_request.rs
@@ -371,10 +371,13 @@ mod tests {
use super::{CaptureError, Compression, DataType, RawRequest};
- /// Mirrors v1's `destination_for_event_name` mapping tests: the
- /// 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.
+ /// v0 lane assignment: the 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.
+ ///
+ /// The prefixed-but-unlisted rows deliberately differ from the v1 mapping
+ /// test. Do not align them until the AI ingestion pipeline admits the
+ /// prefix, because today it drops names outside the allowlist.
#[rstest::rstest]
// Dedicated-name lanes are unaffected by the historical flag.
#[case("$exception", false, DataType::ExceptionErrorTracking)]
diff --git a/rust/capture/src/v1/analytics/constants.rs b/rust/capture/src/v1/analytics/constants.rs
index 12593951218e..c763b4d486aa 100644
--- a/rust/capture/src/v1/analytics/constants.rs
+++ b/rust/capture/src/v1/analytics/constants.rs
@@ -70,9 +70,18 @@ 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";
+/// Name prefix that puts an event on the AI lane. `process::is_ai_lane_name`
+/// documents why v1 gates on the prefix while v0 keeps its name allowlist.
+pub(super) const AI_LANE_NAME_PREFIX: &str = "$ai_";
+
+/// Detail tag for an event posted to the wrong capture endpoint, in either
+/// direction: an AI-lane event name on `/i/v1/analytics/events`, or a
+/// non-AI-lane name on `/i/v1/ai/events`. One tag covers both because the
+/// caller's mistake and its fix are the same in each case -- use the other
+/// capture method. The warning's `path` detail records which way it went, and
+/// on the metric the emitting deployment does (capture-analytics vs
+/// capture-ai), so neither loses the direction.
+pub(super) const DETAIL_MISROUTED_EVENT: &str = "misrouted_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/process.rs b/rust/capture/src/v1/analytics/process.rs
index 16df3a279cf6..91b3e191d358 100644
--- a/rust/capture/src/v1/analytics/process.rs
+++ b/rust/capture/src/v1/analytics/process.rs
@@ -7,12 +7,12 @@ use metrics::histogram;
use uuid::Uuid;
use super::constants::{
- CAPTURE_V1_DISTINCT_ID_MAX_SIZE, CAPTURE_V1_EVENTS_DROPPED,
+ AI_LANE_NAME_PREFIX, CAPTURE_V1_DISTINCT_ID_MAX_SIZE, CAPTURE_V1_EVENTS_DROPPED,
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_AI_BYTE_RATE_LIMITED, DETAIL_AI_EVENT_TOO_BIG,
- DETAIL_EVENT_RESTRICTION_DROP, DETAIL_INVALID_OPTIONS, DETAIL_NON_AI_EVENT,
+ DETAIL_EVENT_RESTRICTION_DROP, DETAIL_INVALID_OPTIONS, DETAIL_MISROUTED_EVENT,
DETAIL_NON_HISTORICAL_DROP, DETAIL_PERSON_PROCESSING_DISABLED, FUTURE_EVENT_HOURS_CUTOFF_MS,
ILLEGAL_DISTINCT_IDS,
};
@@ -21,7 +21,7 @@ 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::{exceeds_max_ai_event_bytes, is_ai_event};
+use crate::v0_request::exceeds_max_ai_event_bytes;
use limiters::overflow::{OverflowLimiter, OverflowLimiterResult};
use tracing::Level;
@@ -46,18 +46,32 @@ 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.
///
-/// AI events (per [`is_ai_event`]) are diverted to `Destination::AiEvents` on
-/// every deployment.
+/// AI events (per [`is_ai_lane_name`]) 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 is_ai_event(name) => Destination::AiEvents,
+ _ if is_ai_lane_name(name) => Destination::AiEvents,
_ => Destination::AnalyticsMain,
}
}
+/// Whether an event name belongs to the AI lane.
+///
+/// The prefix rather than v0's [`is_ai_event`] allowlist, because
+/// `quota_limiters::is_llm_event` already charges every `$ai_`-prefixed name to
+/// the LLM meter, and a v1 client picking an endpoint per event cannot hold a
+/// copy of the allowlist without drifting from it.
+///
+/// v0 keeps the allowlist, so the two disagree for a prefixed name off it. The
+/// AI ingestion pipeline drops what that allowlist does not cover, so it must
+/// admit the prefix before a client sends such a name to `/i/v1/ai/events`.
+fn is_ai_lane_name(name: &str) -> bool {
+ name.starts_with(AI_LANE_NAME_PREFIX)
+}
+
/// 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
@@ -119,8 +133,16 @@ async fn run_pipeline(
return Ok(events);
}
- if state.capture_mode == CaptureMode::Ai {
- drop_non_ai_events(state, context, &mut events);
+ // Each lane's endpoint refuses the other's traffic. v1 requires correct
+ // routing: unlike v0, it has a per-event response, so it can say which event
+ // was wrong instead of guessing on the caller's behalf. v0 keeps its
+ // divert-to-the-AI-topic shim -- this gate is v1-only and does not touch it.
+ // Import backfills historical data of either kind, and Recordings registers
+ // no v1 analytics route, so neither is gated.
+ match state.capture_mode {
+ CaptureMode::Ai => drop_misrouted_events(state, context, &mut events, true),
+ CaptureMode::Events => drop_misrouted_events(state, context, &mut events, false),
+ _ => {}
}
// Nothing left to process — return 200 with per-event drops.
@@ -848,17 +870,30 @@ async fn apply_restrictions(
}
}
-/// Drop every event an AI-mode deployment was sent that is not on the AI lane.
+/// Drop events posted to the wrong lane's endpoint, in whichever direction
+/// this deployment can be wrong about.
///
-/// 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]) {
+/// `serves_ai_lane` is the lane this deployment exists to serve, so an event is
+/// misrouted exactly when `on_ai_lane` disagrees with it. The two deployments
+/// produce to different Kafka clusters and cannot forward to each other, so a
+/// drop with a customer-visible warning is the whole remedy available here. The
+/// v0 path on an AI deployment rejects the whole request instead
+/// (`CaptureError::NonAiEventOnAiLane`), because its contract has no way to say
+/// less.
+///
+/// capture-ai also needs this for governance: it loads only the AI restriction
+/// slice (`Pipeline::for_capture_mode`), so an analytics event surviving there
+/// would ingest governed by nothing.
+///
+/// The gate runs before quota and restrictions, so a refused event spends
+/// neither. It tests `should_publish` rather than `result == Ok` so a Warning
+/// event, which also publishes, cannot ride the wrong lane out.
+fn drop_misrouted_events(
+ state: &router::State,
+ context: &Context,
+ events: &mut [WrappedEvent],
+ serves_ai_lane: bool,
+) {
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
@@ -866,18 +901,12 @@ fn drop_non_ai_events(state: &router::State, context: &Context, events: &mut [Wr
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) {
+ if !event.should_publish() || on_ai_lane(event) == serves_ai_lane {
continue;
}
event.result = EventResult::Drop;
event.destination = Destination::Drop;
- event.details = Some(DETAIL_NON_AI_EVENT);
+ event.details = Some(DETAIL_MISROUTED_EVENT);
dropped += 1;
single_offender = match dropped {
1 => Some((event.event.event.clone(), event.uuid)),
@@ -889,22 +918,21 @@ fn drop_non_ai_events(state: &router::State, context: &Context, events: &mut [Wr
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.
+ // One reason for both directions: the emitting deployment already
+ // distinguishes them on every metric series.
+ metrics::counter!(CAPTURE_V1_EVENTS_DROPPED, "reason" => "misrouted_event").increment(dropped);
+ // DEBUG, not WARN: a client posting to the wrong endpoint is a client
+ // problem, not an operator one, and it is expected to fire at client volume
+ // while callers migrate onto the per-lane endpoints. 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"
+ serves_ai_lane = serves_ai_lane,
+ "dropped events posted to the wrong 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(
@@ -913,11 +941,13 @@ fn drop_non_ai_events(state: &router::State, context: &Context, events: &mut [Wr
);
details.insert("eventUuid".to_string(), serde_json::json!(uuid.to_string()));
}
+ // `path` rides along in the warning context, so the reader can tell which
+ // way the misroute went without a second warning type.
emit_request_warning(
state.ingestion_warning_emitter.as_deref(),
&context.warning_context(),
CAPTURE_V1_ANALYTICS,
- WarningType::InvalidAiEvent,
+ WarningType::MisroutedEvent,
details,
dropped,
);
@@ -930,10 +960,13 @@ fn drop_non_ai_events(state: &router::State, context: &Context, events: &mut [Wr
/// 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.
+/// The name is the stable answer, so the gate, the size ceiling and the byte
+/// budget all charge and measure the same set no matter where an operator
+/// pointed an event.
+///
+/// See [`is_ai_lane_name`] for why membership is the `$ai_` prefix on v1.
fn on_ai_lane(event: &WrappedEvent) -> bool {
- is_ai_event(&event.event.event)
+ is_ai_lane_name(&event.event.event)
}
/// Drop AI-lane events past the deployment's per-event size ceiling.
@@ -2369,16 +2402,18 @@ mod tests {
#[case("$pageview", Destination::AnalyticsMain)]
#[case("custom_event", Destination::AnalyticsMain)]
#[case("$autocapture", Destination::AnalyticsMain)]
- // Allowlisted AI events divert on every deployment.
+ // Every $ai_ prefixed name diverts, listed by v0 or not. The v0 mapping
+ // test asserts the unlisted three stay on Main there.
#[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", Destination::AnalyticsMain)]
- #[case("$ai_generation_enriched", Destination::AnalyticsMain)]
- #[case("$ai_model_failover", Destination::AnalyticsMain)]
+ #[case("$ai_call", Destination::AiEvents)]
+ #[case("$ai_generation_enriched", Destination::AiEvents)]
+ #[case("$ai_model_failover", Destination::AiEvents)]
+ #[case("ai_generation", Destination::AnalyticsMain)]
+ #[case("$ainotcounted", Destination::AnalyticsMain)]
+ #[case("my$ai_event", Destination::AnalyticsMain)]
fn destination_for_event_name_mapping(#[case] event_name: &str, #[case] expected: Destination) {
assert_eq!(destination_for_event_name(event_name), expected);
}
@@ -3890,6 +3925,7 @@ mod tests {
let distinct_id = "user-1";
let now = Utc::now();
let ts = TestStateBuilder::new()
+ .with_capture_mode(CaptureMode::Ai)
.with_ai_gateway_signing_secret(GW_SECRET)
.build();
let signed_at = now.to_rfc3339();
@@ -3930,6 +3966,7 @@ mod tests {
let token = "phc_test_token";
let now = Utc::now();
let ts = TestStateBuilder::new()
+ .with_capture_mode(CaptureMode::Ai)
.with_ai_gateway_signing_secret(GW_SECRET)
.build();
let mut ctx = gateway_context(token, now, None);
@@ -3961,7 +3998,11 @@ mod tests {
/// 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();
+ // AI-lane behaviour, so it belongs on the AI deployment: on v1 the
+ // analytics lane refuses AI events outright (see the misrouting gate).
+ let ts = TestStateBuilder::new()
+ .with_capture_mode(CaptureMode::Ai)
+ .build();
let mut ctx = gateway_context("phc_test_token", Utc::now(), None);
let batch = valid_batch(vec![Event {
event: "$ai_generation".to_string(),
@@ -3985,11 +4026,12 @@ mod tests {
#[tokio::test]
async fn process_batch_routes_ai_overflow_with_only_ai_limiter_armed() {
let ts = TestStateBuilder::new()
+ .with_capture_mode(CaptureMode::Ai)
.with_ai_events_overflow_limiter(1, 1)
.build();
let mut ctx = test_utils::test_analytics_context();
- // All three events share the token:distinct_id overflow key; burst=1
- // lets the first AI event through and overflows the second.
+ // Both events share the token:distinct_id overflow key; burst=1 lets the
+ // first AI event through and overflows the second.
let batch = valid_batch(vec![
Event {
event: "$ai_generation".to_string(),
@@ -3999,7 +4041,6 @@ mod tests {
event: "$ai_generation".to_string(),
..valid_event()
},
- valid_event(),
]);
process_batch(&ts.state, &mut ctx, batch).await.unwrap();
@@ -4007,10 +4048,7 @@ mod tests {
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", "ai_events_overflow", "events_main"]
- );
+ assert_eq!(topics, vec!["ai_events", "ai_events_overflow"]);
});
}
@@ -4022,6 +4060,7 @@ mod tests {
// 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_capture_mode(CaptureMode::Ai)
.with_ai_byte_rate_limiter(Arc::new(GlobalRateLimiter::mock_budget(800)))
.build();
let mut ctx = test_utils::test_analytics_context();
@@ -4034,18 +4073,16 @@ mod tests {
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();
+ let topics: Vec<&str> = records.iter().map(|r| r.topic.as_str()).collect();
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"
+ vec!["ai_events"],
+ "the first AI event fits the budget; the over-budget one must not reach the sink"
);
});
}
@@ -4476,7 +4513,7 @@ mod tests {
assert_eq!(entry.result, EventResult::Ok);
} else {
assert_eq!(entry.result, EventResult::Drop);
- assert_eq!(entry.details, Some(DETAIL_NON_AI_EVENT));
+ assert_eq!(entry.details, Some(DETAIL_MISROUTED_EVENT));
}
}
assert!(!resp.has_retry, "a gated batch must not signal retry");
@@ -4487,18 +4524,18 @@ mod tests {
});
}
- /// 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.
+ /// Lane membership is the `$ai_` prefix, so a prefixed name v0 does not
+ /// list is accepted here like any other AI event.
#[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::listed_by_v0("$ai_generation", EventResult::Ok)]
+ #[case::listed_by_v0_span("$ai_span", EventResult::Ok)]
+ #[case::prefixed_but_unlisted("$ai_not_a_real_event", EventResult::Ok)]
#[case::analytics("$pageview", EventResult::Drop)]
#[case::exception("$exception", EventResult::Drop)]
#[case::heatmap("$$heatmap", EventResult::Drop)]
+ #[case::prefix_is_not_a_substring("my$ai_event", EventResult::Drop)]
#[tokio::test]
- async fn ai_mode_gates_on_the_ai_event_allowlist(
+ async fn ai_mode_gates_on_the_ai_name_prefix(
#[case] event_name: &str,
#[case] expected: EventResult,
) {
@@ -4513,30 +4550,59 @@ mod tests {
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));
+ assert_eq!(entry.details, Some(DETAIL_MISROUTED_EVENT));
}
}
- /// The control proving the gate is mode-scoped, not a change to how the
- /// shared pipeline treats these names.
+ /// The analytics deployment's half of the gate, end to end through
+ /// `process_batch`: an AI-lane name is refused, everything else publishes,
+ /// and the refusal does not take the rest of the batch with it.
+ ///
+ /// `$ai_cache_usage` is prefixed but absent from v0's list, so refusing it
+ /// alongside `$ai_generation` is what distinguishes a prefix gate from an
+ /// allowlist gate.
#[tokio::test]
- async fn events_mode_leaves_non_ai_events_alone() {
+ async fn events_mode_refuses_ai_lane_events_and_publishes_the_rest() {
let ts = TestStateBuilder::new().build();
let mut ctx = test_utils::test_analytics_context();
+ let ai_event = named_event("$ai_generation");
+ let ai_uuid = ai_event.uuid.clone();
+ let prefixed_unlisted = named_event("$ai_cache_usage");
+ let prefixed_unlisted_uuid = prefixed_unlisted.uuid.clone();
let batch = valid_batch(vec![
- named_event("$ai_generation"),
+ ai_event,
named_event("$pageview"),
named_event("$exception"),
+ prefixed_unlisted,
]);
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);
+ for (uuid, entry) in resp.entries() {
+ let uuid = uuid.to_string();
+ if uuid == ai_uuid || uuid == prefixed_unlisted_uuid {
+ assert_eq!(
+ entry.result,
+ EventResult::Drop,
+ "no $ai_ name belongs on the analytics endpoint"
+ );
+ assert_eq!(entry.details, Some(DETAIL_MISROUTED_EVENT));
+ } else {
+ assert_eq!(
+ entry.result,
+ EventResult::Ok,
+ "the rest of the batch is unaffected"
+ );
+ assert_eq!(entry.details, None);
+ }
}
- ts.mock_producer
- .with_records(|records| assert_eq!(records.len(), 3));
+ ts.mock_producer.with_records(|records| {
+ assert_eq!(records.len(), 2, "both $ai_ names are withheld");
+ assert!(
+ records.iter().all(|r| r.topic != "ai_events"),
+ "the analytics deployment publishes nothing to the AI topic on v1"
+ );
+ });
}
/// A batch with nothing but non-AI events leaves no event publishable, so
@@ -4553,7 +4619,7 @@ mod tests {
let batch = valid_batch(vec![
named_event("$pageview"),
named_event("$exception"),
- named_event("$ai_not_a_real_event"),
+ named_event("$$heatmap"),
]);
let resp = process_batch(&ts.state, &mut ctx, batch).await.unwrap();
@@ -4562,7 +4628,7 @@ mod tests {
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_eq!(entry.details, Some(DETAIL_MISROUTED_EVENT));
}
assert!(!resp.has_retry, "a fully gated batch must not signal retry");
ts.mock_producer
@@ -4594,7 +4660,7 @@ mod tests {
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);
+ drop_misrouted_events(&ts.state, &ctx, &mut events, true);
assert_eq!(
events[0].result,
@@ -4605,6 +4671,49 @@ mod tests {
assert_eq!(events[0].details, None);
}
+ /// Pins the direction parameter itself, both ways. Production only calls
+ /// this with `serves_ai_lane = true` today, so without this an inverted or
+ /// widened predicate would go unnoticed until the analytics-side arm is
+ /// switched on.
+ #[rstest::rstest]
+ #[case::ai_lane_keeps_ai_events(true, "$ai_generation", EventResult::Ok, None)]
+ #[case::ai_lane_drops_analytics_events(
+ true,
+ "$pageview",
+ EventResult::Drop,
+ Some(DETAIL_MISROUTED_EVENT)
+ )]
+ #[case::analytics_lane_keeps_analytics_events(false, "$pageview", EventResult::Ok, None)]
+ #[case::analytics_lane_drops_ai_events(
+ false,
+ "$ai_generation",
+ EventResult::Drop,
+ Some(DETAIL_MISROUTED_EVENT)
+ )]
+ #[case::ai_lane_keeps_prefixed_unlisted(true, "$ai_cache_usage", EventResult::Ok, None)]
+ #[case::analytics_lane_drops_prefixed_unlisted(
+ false,
+ "$ai_cache_usage",
+ EventResult::Drop,
+ Some(DETAIL_MISROUTED_EVENT)
+ )]
+ #[tokio::test]
+ async fn the_gate_drops_only_the_other_lane_s_events(
+ #[case] serves_ai_lane: bool,
+ #[case] event_name: &str,
+ #[case] expected: EventResult,
+ #[case] expected_details: Option<&str>,
+ ) {
+ let ts = TestStateBuilder::new().build();
+ let ctx = test_utils::test_analytics_context();
+ let mut events = vec![test_utils::wrapped_event(event_name, "user-1")];
+
+ drop_misrouted_events(&ts.state, &ctx, &mut events, serves_ai_lane);
+
+ assert_eq!(events[0].result, expected);
+ assert_eq!(events[0].details, expected_details);
+ }
+
/// 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]
@@ -4616,15 +4725,15 @@ mod tests {
let mut events = vec![test_utils::wrapped_event("$pageview", "user-1")
.with_destination(Destination::AiEvents)];
- drop_non_ai_events(&ts.state, &ctx, &mut events);
+ drop_misrouted_events(&ts.state, &ctx, &mut events, true);
assert_eq!(events[0].result, EventResult::Drop);
assert_eq!(events[0].destination, Destination::Drop);
- assert_eq!(events[0].details, Some(DETAIL_NON_AI_EVENT));
+ assert_eq!(events[0].details, Some(DETAIL_MISROUTED_EVENT));
}
#[tokio::test]
- async fn ai_mode_non_ai_drop_emits_the_invalid_ai_event_warning() {
+ async fn ai_mode_non_ai_drop_emits_the_misrouted_event_warning() {
let collector = Arc::new(CollectingEmitter::new());
let ts = TestStateBuilder::new()
.with_capture_mode(CaptureMode::Ai)
@@ -4639,7 +4748,7 @@ mod tests {
let emitted = collector.emitted();
assert_eq!(emitted.len(), 1);
- assert_eq!(emitted[0].warning, WarningType::InvalidAiEvent);
+ assert_eq!(emitted[0].warning, WarningType::MisroutedEvent);
assert_eq!(emitted[0].count, 1);
assert_eq!(
emitted[0].extra_details.get("eventName"),
@@ -4653,17 +4762,17 @@ mod tests {
/// 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)]
+ /// same warning through the drop tag.
+ ///
+ /// AI-deployment only. On v1 the analytics lane refuses AI events at the
+ /// misrouting gate, which runs before the size limiter, so an oversized AI
+ /// event never reaches the ceiling there -- it is reported as
+ /// `misrouted_event`, not `ai_event_too_big`.
#[tokio::test]
- async fn oversize_ai_event_emits_the_message_size_warning(#[case] capture_mode: CaptureMode) {
+ async fn oversize_ai_event_emits_the_message_size_warning() {
let collector = Arc::new(CollectingEmitter::new());
let ts = TestStateBuilder::new()
- .with_capture_mode(capture_mode)
+ .with_capture_mode(CaptureMode::Ai)
.with_ai_max_event_bytes(700)
.with_ingestion_warning_emitter(collector.clone())
.build();
@@ -4739,7 +4848,7 @@ mod tests {
/// 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() {
+ async fn ai_mode_several_misroutes_report_a_count_without_identifiers() {
let collector = Arc::new(CollectingEmitter::new());
let ts = TestStateBuilder::new()
.with_capture_mode(CaptureMode::Ai)
@@ -4752,7 +4861,7 @@ mod tests {
let emitted = collector.emitted();
assert_eq!(emitted.len(), 1);
- assert_eq!(emitted[0].warning, WarningType::InvalidAiEvent);
+ assert_eq!(emitted[0].warning, WarningType::MisroutedEvent);
assert_eq!(emitted[0].count, 2);
assert!(!emitted[0].extra_details.contains_key("eventName"));
assert!(!emitted[0].extra_details.contains_key("eventUuid"));
diff --git a/rust/capture/tests/common/utils.rs b/rust/capture/tests/common/utils.rs
index 84e1427910f0..700cfdde44d6 100644
--- a/rust/capture/tests/common/utils.rs
+++ b/rust/capture/tests/common/utils.rs
@@ -310,6 +310,10 @@ impl ServerHandle {
let mut config = DEFAULT_CONFIG.clone();
config.capture_v1_sinks = "msk".to_string();
config.ai_gateway_signing_secret = Some(secret.to_string());
+ // Gateway provenance is AI-lane behaviour, and on v1 the AI lane is
+ // reachable only from an AI-mode deployment: the analytics endpoint
+ // refuses AI-lane event names outright.
+ config.capture_mode = CaptureMode::Ai;
// 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();
@@ -415,7 +419,31 @@ impl ServerHandle {
.expect("failed to send request")
}
- /// Like `capture_v1`, plus the AI-gateway provenance headers.
+ /// `capture_v1` against the AI lane's endpoint, for AI-mode deployments.
+ /// Same envelope and headers -- only the path differs.
+ pub async fn capture_v1_ai<T: Into<reqwest::Body>>(
+ &self,
+ token: &str,
+ body: T,
+ ) -> reqwest::Response {
+ self.client
+ .post(format!("http://{:?}/i/v1/ai/events", self.addr))
+ .header("authorization", format!("Bearer {token}"))
+ .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:00.000Z")
+ .header("content-type", "application/json")
+ .header("user-agent", "test-client/1.0")
+ .body(body)
+ .send()
+ .await
+ .expect("failed to send request")
+ }
+
+ /// Like `capture_v1`, plus the AI-gateway provenance headers. Posts to the
+ /// AI endpoint: gateway-signed events are AI-lane events, which v1 accepts
+ /// only there.
#[allow(clippy::too_many_arguments)]
pub async fn capture_v1_with_gateway_headers<T: Into<reqwest::Body>>(
&self,
@@ -426,7 +454,7 @@ impl ServerHandle {
request_id: &str,
) -> reqwest::Response {
self.client
- .post(format!("http://{:?}/i/v1/analytics/events", self.addr))
+ .post(format!("http://{:?}/i/v1/ai/events", self.addr))
.header("authorization", format!("Bearer {token}"))
.header("PostHog-Sdk-Info", "posthog-rs/1.0.0")
.header("PostHog-Attempt", "1")
diff --git a/rust/capture/tests/v1_http_integration.rs b/rust/capture/tests/v1_http_integration.rs
index 034642572227..0b3313f71dcc 100644
--- a/rust/capture/tests/v1_http_integration.rs
+++ b/rust/capture/tests/v1_http_integration.rs
@@ -101,6 +101,61 @@ async fn v1_http_single_event_to_kafka() -> Result<()> {
Ok(())
}
+// ---------------------------------------------------------------------------
+// Lane gate: the analytics endpoint refuses AI-lane events, HTTP -> Kafka
+// ---------------------------------------------------------------------------
+
+/// The v1 analytics endpoint refuses an AI-lane event name and says so
+/// per-event, while the rest of the batch still publishes.
+///
+/// `$ai_cache_usage` is deliberately in the batch: `$ai_`-prefixed but off the
+/// name list v0 routes by. It is refused here alongside `$ai_generation`, which
+/// is what proves the endpoint gates on the prefix rather than that list.
+#[tokio::test]
+async fn v1_http_analytics_endpoint_refuses_ai_lane_events() -> Result<()> {
+ setup_tracing();
+ let topic = EphemeralTopic::new().await;
+ let server = ServerHandle::for_v1_topic(&topic).await;
+
+ let ai = named("lane-user", "$ai_generation");
+ let ai_uuid = ai.uuid.clone();
+ let prefixed = named("lane-user", "$ai_cache_usage");
+ let prefixed_uuid = prefixed.uuid.clone();
+ let analytics = pageview("lane-user");
+ let analytics_uuid = analytics.uuid.clone();
+ let payload = batch_payload(&[ai, prefixed, analytics]);
+
+ let res = server.capture_v1(TOKEN, payload).await;
+ assert_eq!(
+ res.status(),
+ reqwest::StatusCode::OK,
+ "a misrouted event is a per-event verdict, never a request-level error"
+ );
+
+ let body = parse_body(res).await;
+ for uuid in [ai_uuid.as_str(), prefixed_uuid.as_str()] {
+ assert_eq!(
+ body["results"][uuid]["result"], "drop",
+ "no $ai_ name belongs on the analytics endpoint: {body}"
+ );
+ assert_eq!(
+ body["results"][uuid]["details"], "misrouted_event",
+ "the drop must name the reason so the caller can fix the routing: {body}"
+ );
+ }
+ assert_eq!(
+ body["results"][analytics_uuid.as_str()]["result"],
+ "ok",
+ "the rest of the batch is unaffected: {body}"
+ );
+
+ // Only the analytics event reaches Kafka.
+ let first: CapturedEvent = serde_json::from_value(topic.next_event()?)?;
+ assert_eq!(first.event, "$pageview");
+ topic.assert_empty();
+ Ok(())
+}
+
// ---------------------------------------------------------------------------
// Small batch: HTTP -> real Kafka round trip
// ---------------------------------------------------------------------------
@@ -209,7 +264,7 @@ async fn v1_http_forged_gateway_marker_is_stripped_in_kafka() -> Result<()> {
ev.properties = raw_obj(r#"{"$ai_model":"claude","$ai_gateway_verified":true}"#);
let payload = batch_payload(std::slice::from_ref(&ev));
- let res = server.capture_v1(TOKEN, payload).await;
+ let res = server.capture_v1_ai(TOKEN, payload).await;
assert_eq!(res.status(), reqwest::StatusCode::OK);
let captured: CapturedEvent = serde_json::from_value(topic.next_event()?)?;
diff --git a/rust/common/ingestion_warnings/src/registry.rs b/rust/common/ingestion_warnings/src/registry.rs
index 68171e699a20..dd2aa3e3024a 100644
--- a/rust/common/ingestion_warnings/src/registry.rs
+++ b/rust/common/ingestion_warnings/src/registry.rs
@@ -35,7 +35,9 @@ impl WarningType {
/// would mean inventing an error that never gets returned.
/// * Ones from a pipeline that has no tag vocabulary. The AI endpoints
/// reject via their own typed conditions, not `v1::Error`, so their tags
- /// would be strings no `Error` ever produces. The replay endpoint is the
+ /// would be strings no `Error` ever produces. `MisroutedEvent` is the
+ /// same shape: a per-event drop detail set by the lane gates, never an
+ /// `Error`. The replay endpoint is the
/// same case from the other direction: its conditions are `CaptureError`
/// variants v1 analytics never returns, so no `Error::tag()` names them.
///
@@ -44,10 +46,11 @@ impl WarningType {
/// This list exists so the trust-allowlist invariant below can still be
/// airtight: `captureProduced` must equal "reachable by one of capture's two
/// emit routes", and without this the direct route would be invisible to it.
- pub const DIRECT_EMIT: [Self; 8] = [
+ pub const DIRECT_EMIT: [Self; 9] = [
Self::HighVolumeDistinctId,
Self::DistinctIdTruncated,
Self::InvalidAiEvent,
+ Self::MisroutedEvent,
Self::InvalidAiPayload,
Self::NoAiSpansIngested,
Self::MissingSessionId,
diff --git a/rust/common/ingestion_warnings/warning_types.generated.json b/rust/common/ingestion_warnings/warning_types.generated.json
index 9bf6611378b3..229128e1ac4d 100644
--- a/rust/common/ingestion_warnings/warning_types.generated.json
+++ b/rust/common/ingestion_warnings/warning_types.generated.json
@@ -235,6 +235,12 @@
"severity": "warning",
"captureProduced": false
},
+ {
+ "type": "misrouted_event",
+ "category": "event",
+ "severity": "error",
+ "captureProduced": true
+ },
{
"type": "missing_distinct_id",
"category": "event",