:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(capture): stop v1 refusing ai events sent with capture() (#102511)
Eli Reisman2a1b999b6efc
diff --git a/frontend/src/scenes/data-management/ingestion-warnings/IngestionWarningsView.tsx b/frontend/src/scenes/data-management/ingestion-warnings/IngestionWarningsView.tsxindex 186ed5ae54b7..c6dc0e71d0a5 100644--- a/frontend/src/scenes/data-management/ingestion-warnings/IngestionWarningsView.tsx+++ b/frontend/src/scenes/data-management/ingestion-warnings/IngestionWarningsView.tsx@@ -58,8 +58,6 @@ 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 endpointsinvalid_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 endpointdiff --git a/nodejs/src/ingestion/common/ingestion-warning-types.ts b/nodejs/src/ingestion/common/ingestion-warning-types.tsindex 5fed2f96cdae..b53a84cc7627 100644--- a/nodejs/src/ingestion/common/ingestion-warning-types.ts+++ b/nodejs/src/ingestion/common/ingestion-warning-types.ts@@ -76,13 +76,6 @@ 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/posthog/api/capture.py b/posthog/api/capture.pyindex 219ab48f4802..0003ff32ab62 100644--- a/posthog/api/capture.py+++ b/posthog/api/capture.py@@ -358,9 +358,10 @@ def _validate_event(ev: dict[str, Any], *, event_source: str, ai_lane: bool) ->f"{fn} ({event_source}): '{event_name}' is a replay event; use the replay capture path")- # The `$ai_` prefix, matching capture's own v1 rule. A prefixed name capture- # does not recognise still reaches the AI endpoint and is reported there as- # `misrouted_event`, so the authority stays server-side.+ # The `$ai_` prefix, matching what billing's `is_llm_event` already keys on.+ # Capture's AI endpoint admits a narrower allowlist, so a prefixed name it+ # does not recognise is refused there as `non_ai_event`, which keeps the+ # authority server-side.is_ai_event_name = event_name.startswith(AI_EVENT_NAME_PREFIX)if ai_lane and not is_ai_event_name:raise CaptureInternalError(@@ -398,10 +399,9 @@ def prepare_capture_internal_batch(results map.``ai_lane`` selects which lane the batch is bound for and, with it, which- event names are admissible. The two lanes are mutually exclusive: capture's- v1 endpoints each refuse the other's traffic, so sending an event to the- wrong one earns a per-event ``misrouted_event`` drop. Catching it here- turns that into an immediate, actionable error at the call site instead.+ event names are admissible. Capture's v1 AI endpoint refuses analytics+ traffic with a per-event ``non_ai_event`` drop. Catching it here turns that+ into an immediate, actionable error at the call site instead."""_validate_batch_inputs(events, token=token, event_source=event_source, ai_lane=ai_lane)diff --git a/products/ingestion/skills/resolving-ingestion-warnings/SKILL.md b/products/ingestion/skills/resolving-ingestion-warnings/SKILL.mdindex 378d477f5113..7f6f3c0d1016 100644--- a/products/ingestion/skills/resolving-ingestion-warnings/SKILL.md+++ b/products/ingestion/skills/resolving-ingestion-warnings/SKILL.md@@ -76,12 +76,11 @@ 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 |-| `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 |+| 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 |### Heatmaps (`event`)diff --git a/rust/capture/src/event_restrictions/types.rs b/rust/capture/src/event_restrictions/types.rsindex 9bba4ff05a50..e2ffe68e24b7 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_misrouted_events` drops only the offenders, because it can+ // `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/v0_request.rs b/rust/capture/src/v0_request.rsindex 7beb0039b687..3290fb62b314 100644--- a/rust/capture/src/v0_request.rs+++ b/rust/capture/src/v0_request.rs@@ -371,13 +371,10 @@ mod tests {use super::{CaptureError, Compression, DataType, RawRequest};- /// 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.+ /// 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.#[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.rsindex c763b4d486aa..12593951218e 100644--- a/rust/capture/src/v1/analytics/constants.rs+++ b/rust/capture/src/v1/analytics/constants.rs@@ -70,18 +70,9 @@ 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";-/// 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 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/process.rs b/rust/capture/src/v1/analytics/process.rsindex 91b3e191d358..16df3a279cf6 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::{- AI_LANE_NAME_PREFIX, CAPTURE_V1_DISTINCT_ID_MAX_SIZE, CAPTURE_V1_EVENTS_DROPPED,+ 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_MISROUTED_EVENT,+ 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,};@@ -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;+use crate::v0_request::{exceeds_max_ai_event_bytes, is_ai_event};use limiters::overflow::{OverflowLimiter, OverflowLimiterResult};use tracing::Level;@@ -46,32 +46,18 @@ 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_lane_name`]) are diverted to `Destination::AiEvents`-/// on every deployment.+/// AI events (per [`is_ai_event`]) are diverted to `Destination::AiEvents` on+/// every deployment.fn destination_for_event_name(name: &str) -> Destination {match name {"$exception" => Destination::ExceptionErrorTracking,"$$heatmap" => Destination::HeatmapMain,"$$client_ingestion_warning" => Destination::ClientIngestionWarning,- _ if is_ai_lane_name(name) => Destination::AiEvents,+ _ if is_ai_event(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@@ -133,16 +119,8 @@ async fn run_pipeline(return Ok(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),- _ => {}+ if state.capture_mode == CaptureMode::Ai {+ drop_non_ai_events(state, context, &mut events);}// Nothing left to process — return 200 with per-event drops.@@ -870,30 +848,17 @@ async fn apply_restrictions(}}-/// Drop events posted to the wrong lane's endpoint, in whichever direction-/// this deployment can be wrong about.+/// Drop every event an AI-mode deployment was sent that is not on the AI lane.///-/// `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,-) {+/// 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@@ -901,12 +866,18 @@ fn drop_misrouted_events(let mut single_offender: Option<(String, Uuid)> = None;for event in events.iter_mut() {- if !event.should_publish() || on_ai_lane(event) == serves_ai_lane {+ // 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_MISROUTED_EVENT);+ event.details = Some(DETAIL_NON_AI_EVENT);dropped += 1;single_offender = match dropped {1 => Some((event.event.event.clone(), event.uuid)),@@ -918,21 +889,22 @@ fn drop_misrouted_events(return;}- // 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.+ 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,- serves_ai_lane = serves_ai_lane,- "dropped events posted to the wrong lane"+ "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(@@ -941,13 +913,11 @@ fn drop_misrouted_events();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::MisroutedEvent,+ WarningType::InvalidAiEvent,details,dropped,);@@ -960,13 +930,10 @@ fn drop_misrouted_events(/// 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 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.+/// The allowlist is the same source v0 stamps `DataType::AiEvents` from, so+/// both pipelines charge and measure the same set.fn on_ai_lane(event: &WrappedEvent) -> bool {- is_ai_lane_name(&event.event.event)+ is_ai_event(&event.event.event)}/// Drop AI-lane events past the deployment's per-event size ceiling.@@ -2402,18 +2369,16 @@ mod tests {#[case("$pageview", Destination::AnalyticsMain)]#[case("custom_event", Destination::AnalyticsMain)]#[case("$autocapture", Destination::AnalyticsMain)]- // Every $ai_ prefixed name diverts, listed by v0 or not. The v0 mapping- // test asserts the unlisted three stay on Main there.+ // Allowlisted AI events divert on every deployment.#[case("$ai_generation", Destination::AiEvents)]#[case("$ai_span", Destination::AiEvents)]#[case("$ai_trace", Destination::AiEvents)]#[case("$ai_generation_summary", Destination::AiEvents)]- #[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)]+ // $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)]fn destination_for_event_name_mapping(#[case] event_name: &str, #[case] expected: Destination) {assert_eq!(destination_for_event_name(event_name), expected);}@@ -3925,7 +3890,6 @@ 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();@@ -3966,7 +3930,6 @@ 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);@@ -3998,11 +3961,7 @@ 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() {- // 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 ts = TestStateBuilder::new().build();let mut ctx = gateway_context("phc_test_token", Utc::now(), None);let batch = valid_batch(vec![Event {event: "$ai_generation".to_string(),@@ -4026,12 +3985,11 @@ 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();- // Both events share the token:distinct_id overflow key; burst=1 lets the- // first AI event through and overflows the second.+ // All three 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(),@@ -4041,6 +3999,7 @@ mod tests {event: "$ai_generation".to_string(),..valid_event()},+ valid_event(),]);process_batch(&ts.state, &mut ctx, batch).await.unwrap();@@ -4048,7 +4007,10 @@ 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"]);+ assert_eq!(+ topics,+ vec!["ai_events", "ai_events_overflow", "events_main"]+ );});}@@ -4060,7 +4022,6 @@ 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();@@ -4073,16 +4034,18 @@ 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 topics: Vec<&str> = records.iter().map(|r| r.topic.as_str()).collect();+ let mut topics: Vec<&str> = records.iter().map(|r| r.topic.as_str()).collect();+ topics.sort_unstable();assert_eq!(topics,- vec!["ai_events"],- "the first AI event fits the budget; the over-budget one must not reach the sink"+ vec!["ai_events", "events_main"],+ "the over-budget AI event must not reach the sink, and the analytics event must be untouched");});}@@ -4513,7 +4476,7 @@ mod tests {assert_eq!(entry.result, EventResult::Ok);} else {assert_eq!(entry.result, EventResult::Drop);- assert_eq!(entry.details, Some(DETAIL_MISROUTED_EVENT));+ assert_eq!(entry.details, Some(DETAIL_NON_AI_EVENT));}}assert!(!resp.has_retry, "a gated batch must not signal retry");@@ -4524,18 +4487,18 @@ mod tests {});}- /// Lane membership is the `$ai_` prefix, so a prefixed name v0 does not- /// list is accepted here like any other AI event.+ /// 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::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::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)]- #[case::prefix_is_not_a_substring("my$ai_event", EventResult::Drop)]#[tokio::test]- async fn ai_mode_gates_on_the_ai_name_prefix(+ async fn ai_mode_gates_on_the_ai_event_allowlist(#[case] event_name: &str,#[case] expected: EventResult,) {@@ -4550,59 +4513,30 @@ 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_MISROUTED_EVENT));+ assert_eq!(entry.details, Some(DETAIL_NON_AI_EVENT));}}- /// 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.+ /// 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_refuses_ai_lane_events_and_publishes_the_rest() {+ async fn events_mode_leaves_non_ai_events_alone() {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![- ai_event,+ named_event("$ai_generation"),named_event("$pageview"),named_event("$exception"),- prefixed_unlisted,]);let resp = process_batch(&ts.state, &mut ctx, batch).await.unwrap();- 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);- }+ 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(), 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"- );- });+ ts.mock_producer+ .with_records(|records| assert_eq!(records.len(), 3));}/// A batch with nothing but non-AI events leaves no event publishable, so@@ -4619,7 +4553,7 @@ mod tests {let batch = valid_batch(vec![named_event("$pageview"),named_event("$exception"),- named_event("$$heatmap"),+ named_event("$ai_not_a_real_event"),]);let resp = process_batch(&ts.state, &mut ctx, batch).await.unwrap();@@ -4628,7 +4562,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_MISROUTED_EVENT));+ assert_eq!(entry.details, Some(DETAIL_NON_AI_EVENT));}assert!(!resp.has_retry, "a fully gated batch must not signal retry");ts.mock_producer@@ -4660,7 +4594,7 @@ mod tests {let mut events = vec![test_utils::wrapped_event("$ai_generation", "user-1").with_destination(destination.clone())];- drop_misrouted_events(&ts.state, &ctx, &mut events, true);+ drop_non_ai_events(&ts.state, &ctx, &mut events);assert_eq!(events[0].result,@@ -4671,49 +4605,6 @@ 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]@@ -4725,15 +4616,15 @@ mod tests {let mut events = vec![test_utils::wrapped_event("$pageview", "user-1").with_destination(Destination::AiEvents)];- drop_misrouted_events(&ts.state, &ctx, &mut events, true);+ 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_MISROUTED_EVENT));+ assert_eq!(events[0].details, Some(DETAIL_NON_AI_EVENT));}#[tokio::test]- async fn ai_mode_non_ai_drop_emits_the_misrouted_event_warning() {+ 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)@@ -4748,7 +4639,7 @@ mod tests {let emitted = collector.emitted();assert_eq!(emitted.len(), 1);- assert_eq!(emitted[0].warning, WarningType::MisroutedEvent);+ assert_eq!(emitted[0].warning, WarningType::InvalidAiEvent);assert_eq!(emitted[0].count, 1);assert_eq!(emitted[0].extra_details.get("eventName"),@@ -4762,17 +4653,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.- ///- /// 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`.+ /// 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() {+ 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(CaptureMode::Ai)+ .with_capture_mode(capture_mode).with_ai_max_event_bytes(700).with_ingestion_warning_emitter(collector.clone()).build();@@ -4848,7 +4739,7 @@ mod tests {/// only the count rides along, the same rule the validation-drop warnings/// follow.#[tokio::test]- async fn ai_mode_several_misroutes_report_a_count_without_identifiers() {+ 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)@@ -4861,7 +4752,7 @@ mod tests {let emitted = collector.emitted();assert_eq!(emitted.len(), 1);- assert_eq!(emitted[0].warning, WarningType::MisroutedEvent);+ 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"));diff --git a/rust/capture/tests/common/utils.rs b/rust/capture/tests/common/utils.rsindex 700cfdde44d6..84e1427910f0 100644--- a/rust/capture/tests/common/utils.rs+++ b/rust/capture/tests/common/utils.rs@@ -310,10 +310,6 @@ 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();@@ -419,31 +415,7 @@ impl ServerHandle {.expect("failed to send request")}- /// `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.+ /// Like `capture_v1`, plus the AI-gateway provenance headers.#[allow(clippy::too_many_arguments)]pub async fn capture_v1_with_gateway_headers<T: Into<reqwest::Body>>(&self,@@ -454,7 +426,7 @@ impl ServerHandle {request_id: &str,) -> reqwest::Response {self.client- .post(format!("http://{:?}/i/v1/ai/events", self.addr))+ .post(format!("http://{:?}/i/v1/analytics/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.rsindex 0b3313f71dcc..034642572227 100644--- a/rust/capture/tests/v1_http_integration.rs+++ b/rust/capture/tests/v1_http_integration.rs@@ -101,61 +101,6 @@ 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// ---------------------------------------------------------------------------@@ -264,7 +209,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_ai(TOKEN, payload).await;+ let res = server.capture_v1(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.rsindex dd2aa3e3024a..68171e699a20 100644--- a/rust/common/ingestion_warnings/src/registry.rs+++ b/rust/common/ingestion_warnings/src/registry.rs@@ -35,9 +35,7 @@ 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. `MisroutedEvent` is the- /// same shape: a per-event drop detail set by the lane gates, never an- /// `Error`. The replay endpoint is the+ /// would be strings no `Error` ever produces. 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.///@@ -46,11 +44,10 @@ 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; 9] = [+ pub const DIRECT_EMIT: [Self; 8] = [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.jsonindex 229128e1ac4d..9bf6611378b3 100644--- a/rust/common/ingestion_warnings/warning_types.generated.json+++ b/rust/common/ingestion_warnings/warning_types.generated.json@@ -235,12 +235,6 @@"severity": "warning","captureProduced": false},- {- "type": "misrouted_event",- "category": "event",- "severity": "error",- "captureProduced": true- },{"type": "missing_distinct_id","category": "event",