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): register ingestion warning types for the AI endpoints (#76145)

Eli Reisman8da0bbdea6c1
diff --git a/nodejs/src/ingestion/common/ingestion-warning-types.ts b/nodejs/src/ingestion/common/ingestion-warning-types.ts
index 249a8b08501d..d9d1b957a3e7 100644
--- a/nodejs/src/ingestion/common/ingestion-warning-types.ts
+++ b/nodejs/src/ingestion/common/ingestion-warning-types.ts
@@ -64,6 +64,16 @@ export const INGESTION_WARNING_TYPES = {
missing_event_uuid: { category: 'event', severity: 'error', captureProduced: true },
invalid_event_uuid: { category: 'event', severity: 'error', captureProduced: true },
duplicate_event_uuid: { category: 'event', severity: 'error', captureProduced: true },
+ // Capture's AI endpoints (/i/v0/ai, /i/v0/ai/otel), which validate more
+ // strictly than the analytics paths: they accept only the six `$ai_*` event
+ // names and require `$ai_model`, and their payloads are multipart or OTLP
+ // rather than a JSON batch.
+ invalid_ai_event: { category: 'event', severity: 'error', captureProduced: true },
+ invalid_ai_payload: { 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.
+ no_ai_spans_ingested: { category: 'event', severity: 'warning', captureProduced: true },
ignored_invalid_timestamp: { category: 'event', severity: 'warning' },
schema_validation_failed: { category: 'event', severity: 'error' },
skipping_event_invalid_distinct_id: { category: 'event', severity: 'error' },
diff --git a/rust/capture/src/ai_endpoint.rs b/rust/capture/src/ai_endpoint.rs
index c03c84cd34a3..3d7e060efc38 100644
--- a/rust/capture/src/ai_endpoint.rs
+++ b/rust/capture/src/ai_endpoint.rs
@@ -23,12 +23,17 @@ const AI_BLOB_SIZE_BYTES: &str = "capture_ai_blob_size_bytes";
const AI_BLOB_TOTAL_BYTES_PER_EVENT: &str = "capture_ai_blob_total_bytes_per_event";
const AI_BLOB_EVENTS_TOTAL: &str = "capture_ai_blob_events_total";
+use common_ingestion_warnings::WarningRequestContext;
+
+use crate::ai_rejection::{AiFailure, AiRejection, ALLOWED_AI_EVENTS};
use crate::api::{CaptureError, CaptureResponse, CaptureResponseCode};
use crate::event_restrictions::{
AppliedRestrictions, EventContext as RestrictionEventContext, Pipeline,
};
use crate::events::overflow_stamping::stamp_overflow_reason;
use crate::extractors::extract_body_with_timeout;
+use crate::ingestion_warnings::ai::emit_ai_failure_warning;
+use crate::ingestion_warnings::{unknown_if_missing, within_bound};
use crate::payload::decompression::decompress_gzip_to_bytes;
use crate::prometheus::{report_dropped_events, report_internal_error_metrics};
use crate::router::State as AppState;
@@ -129,9 +134,27 @@ pub async fn ai_handler(
headers: HeaderMap,
body: Body,
) -> Result<Json<AIEndpointResponse>, CaptureError> {
- ai_handler_inner(state, ip, path, headers, body)
- .await
- .inspect_err(|err| report_internal_error_metrics(err.to_metric_tag(), "ai"))
+ let emitter = state.ingestion_warning_emitter.clone();
+ // Filled by the inner handler once the token is known, and enriched once the
+ // event part parses. Staying `None` is what keeps pre-token failures — an
+ // oversized body, a missing Bearer header — from emitting a warning nobody
+ // can be attributed for.
+ let mut attribution = None;
+
+ let result = ai_handler_inner(state, ip, path, headers, body, &mut attribution).await;
+
+ let failure = match result {
+ Ok(response) => return Ok(response),
+ Err(failure) => failure,
+ };
+
+ if let Some(request) = attribution.as_ref() {
+ emit_ai_failure_warning(emitter.as_deref(), request, &failure);
+ }
+
+ let err = CaptureError::from(failure);
+ report_internal_error_metrics(err.to_metric_tag(), "ai");
+ Err(err)
}
async fn ai_handler_inner(
@@ -140,7 +163,8 @@ async fn ai_handler_inner(
path: MatchedPath,
headers: HeaderMap,
body: Body,
-) -> Result<Json<AIEndpointResponse>, CaptureError> {
+ attribution: &mut Option<WarningRequestContext>,
+) -> Result<Json<AIEndpointResponse>, AiFailure> {
debug!("Received request to /i/v0/ai endpoint");
// Extract body with timed streaming (same pattern as analytics/recordings handlers)
@@ -157,7 +181,7 @@ async fn ai_handler_inner(
// Check for empty body
if body.is_empty() {
- return Err(CaptureError::EmptyPayload);
+ return Err(CaptureError::EmptyPayload.into());
}
// Authenticate before any CPU/memory-intensive decompression work
@@ -167,11 +191,16 @@ async fn ai_handler_inner(
.unwrap_or("");
if !auth_header.starts_with("Bearer ") {
- return Err(CaptureError::NoTokenError);
+ return Err(CaptureError::NoTokenError.into());
}
let token = &auth_header[7..]; // Remove "Bearer " prefix
- validate_token(token)?;
+ validate_token(token).map_err(CaptureError::from)?;
+
+ // Everything from here on is attributable. SDK identity isn't known yet —
+ // it lives in the event part's properties — so warnings raised before that
+ // part parses stamp the unknown fallback.
+ *attribution = Some(ai_request_context(token, path.as_str(), None));
// Check for Content-Encoding header and decompress if needed
let content_encoding = headers
@@ -193,15 +222,12 @@ async fn ai_handler_inner(
.unwrap_or("");
if !content_type.starts_with("multipart/form-data") {
- return Err(CaptureError::RequestDecodingError(
- "Content-Type must be multipart/form-data".to_string(),
- ));
+ return Err(AiRejection::NotMultipart.into());
}
// Extract boundary from Content-Type header using multer's built-in parser
- let boundary = parse_boundary(content_type).map_err(|e| {
- CaptureError::RequestDecodingError(format!("Invalid boundary in Content-Type: {e}"))
- })?;
+ let boundary =
+ parse_boundary(content_type).map_err(|e| AiRejection::InvalidBoundary(e.to_string()))?;
// Capture body size for logging (before we move the Bytes)
let body_size = decompressed_body.len();
@@ -215,6 +241,14 @@ async fn ai_handler_inner(
// Step 1: Retrieve event metadata (parses only the first 'event' part)
let event_metadata = retrieve_event_metadata(&mut multipart).await?;
+ // The event part carries $lib/$lib_version, so attribution can be upgraded
+ // from the unknown fallback for everything that fails after this point.
+ *attribution = Some(ai_request_context(
+ token,
+ path.as_str(),
+ Some(&event_metadata.event_json),
+ ));
+
// Step 2: Check event restrictions early - before parsing remaining parts
let applied_restrictions = if let Some(ref service) = state.event_restriction_service {
let uuid_str = event_metadata.event_uuid();
@@ -283,7 +317,7 @@ async fn ai_handler_inner(
.is_quota_limited_v1(token, &QuotaResource::Events)
.await
{
- return Err(CaptureError::BillingLimit);
+ return Err(CaptureError::BillingLimit.into());
}
event_metadata
} else {
@@ -472,23 +506,45 @@ pub async fn options() -> Result<CaptureResponse, CaptureError> {
})
}
+/// Warning attribution for an AI request.
+///
+/// The endpoint has no `PostHog-Sdk-Info` contract, so SDK identity comes from
+/// the event's own `$lib`/`$lib_version` properties. `event` is `None` before the
+/// event part has parsed, which is when several rejections fire, so both fields
+/// fall back to the unknown placeholder rather than dropping the keys.
+fn ai_request_context(token: &str, path: &str, event: Option<&Value>) -> WarningRequestContext {
+ let properties = event
+ .and_then(|e| e.as_object())
+ .and_then(|obj| obj.get("properties"))
+ .and_then(|props| props.as_object());
+ let property = |key: &str| {
+ properties
+ .and_then(|props| props.get(key))
+ .and_then(|v| v.as_str())
+ .and_then(|v| within_bound(v.to_string()))
+ };
+
+ WarningRequestContext {
+ token: token.to_string(),
+ lib: unknown_if_missing(property("$lib").as_deref()),
+ lib_version: unknown_if_missing(property("$lib_version").as_deref()),
+ path: path.to_string(),
+ }
+}
+
/// Retrieve event metadata from the first multipart part for early checks.
/// This parses only the 'event' part to extract event_name and distinct_id
/// before processing the rest of the multipart body.
/// The multipart parser is passed in and will be reused for remaining parts.
async fn retrieve_event_metadata(
multipart: &mut Multipart<'_>,
-) -> Result<EventMetadata, CaptureError> {
+) -> Result<EventMetadata, AiRejection> {
// Get the first field - must be 'event'
let field = multipart
.next_field()
.await
- .map_err(|e| CaptureError::RequestDecodingError(format!("Multipart parsing failed: {e}")))?
- .ok_or_else(|| {
- CaptureError::RequestParsingError(
- "Missing required 'event' part in multipart data".to_string(),
- )
- })?;
+ .map_err(|e| AiRejection::MultipartParseFailed(e.to_string()))?
+ .ok_or(AiRejection::MissingEventPart)?;
let field_name = field.name().unwrap_or("unknown").to_string();
let content_type = field.content_type().map(|ct| ct.to_string());
@@ -500,39 +556,32 @@ async fn retrieve_event_metadata(
// Validate that the first part is the event part
if field_name != "event" {
- return Err(CaptureError::RequestParsingError(format!(
- "First part must be 'event', got '{field_name}'"
- )));
+ return Err(AiRejection::FirstPartNotEvent(field_name));
}
// Read the field data
- let field_data = field.bytes().await.map_err(|e| {
- CaptureError::RequestDecodingError(format!("Failed to read field data: {e}"))
- })?;
+ let field_data = field
+ .bytes()
+ .await
+ .map_err(|e| AiRejection::FieldDataUnreadable(e.to_string()))?;
// Process the event part
let (event_json, event_part_info) =
process_event_part(field_data, content_type, content_encoding)?;
// Extract event_name and distinct_id
- let event_obj = event_json.as_object().ok_or_else(|| {
- CaptureError::RequestParsingError("Event must be a JSON object".to_string())
- })?;
+ let event_obj = event_json.as_object().ok_or(AiRejection::EventNotObject)?;
let event_name = event_obj
.get("event")
.and_then(|v| v.as_str())
- .ok_or_else(|| {
- CaptureError::RequestParsingError("Event missing 'event' field".to_string())
- })?
+ .ok_or(AiRejection::EventMissingName)?
.to_string();
let distinct_id = event_obj
.get("distinct_id")
.and_then(|v| v.as_str())
- .ok_or_else(|| {
- CaptureError::RequestParsingError("Event missing 'distinct_id' field".to_string())
- })?
+ .ok_or(AiRejection::EventMissingDistinctId)?
.to_string();
Ok(EventMetadata {
@@ -654,26 +703,25 @@ fn process_event_part(
field_data: Bytes,
content_type: Option<String>,
content_encoding: Option<String>,
-) -> Result<(Value, PartInfo), CaptureError> {
+) -> Result<(Value, PartInfo), AiRejection> {
const MAX_EVENT_SIZE: usize = 32 * 1024; // 32KB
let event_size = field_data.len();
// Check event size limit
if event_size > MAX_EVENT_SIZE {
- return Err(CaptureError::EventTooBig(format!(
- "Event part size ({event_size} bytes) exceeds maximum allowed size ({MAX_EVENT_SIZE} bytes)"
- )));
+ return Err(AiRejection::EventPartTooBig {
+ size: event_size,
+ max: MAX_EVENT_SIZE,
+ });
}
// Parse the event JSON
- let event_json_str = std::str::from_utf8(&field_data).map_err(|_| {
- CaptureError::RequestParsingError("Event part must be valid UTF-8".to_string())
- })?;
+ let event_json_str =
+ std::str::from_utf8(&field_data).map_err(|_| AiRejection::EventPartNotUtf8)?;
- let event_json = serde_json::from_str(event_json_str).map_err(|_| {
- CaptureError::RequestParsingError("Event part must be valid JSON".to_string())
- })?;
+ let event_json =
+ serde_json::from_str(event_json_str).map_err(|_| AiRejection::EventPartNotJson)?;
let part_info = PartInfo {
name: "event".to_string(),
@@ -691,15 +739,13 @@ fn process_properties_part(
field_data: Bytes,
content_type: Option<String>,
content_encoding: Option<String>,
-) -> Result<(Value, PartInfo), CaptureError> {
+) -> Result<(Value, PartInfo), AiRejection> {
// Parse the properties JSON
- let properties_json_str = std::str::from_utf8(&field_data).map_err(|_| {
- CaptureError::RequestParsingError("Properties part must be valid UTF-8".to_string())
- })?;
+ let properties_json_str =
+ std::str::from_utf8(&field_data).map_err(|_| AiRejection::PropertiesPartNotUtf8)?;
- let properties_json = serde_json::from_str(properties_json_str).map_err(|_| {
- CaptureError::RequestParsingError("Properties part must be valid JSON".to_string())
- })?;
+ let properties_json = serde_json::from_str(properties_json_str)
+ .map_err(|_| AiRejection::PropertiesPartNotJson)?;
let part_info = PartInfo {
name: "event.properties".to_string(),
@@ -718,19 +764,18 @@ fn process_blob_part(
field_data: Bytes,
content_type: Option<String>,
content_encoding: Option<String>,
-) -> Result<(BlobPart, PartInfo), CaptureError> {
+) -> Result<(BlobPart, PartInfo), AiRejection> {
// Validate content type for blob parts - it's required
if let Some(ref ct) = content_type {
let ct_lower = ct.to_lowercase();
if !is_valid_blob_content_type(&ct_lower) {
- return Err(CaptureError::RequestParsingError(
- format!("Unsupported content type for blob part '{field_name}': '{ct}'. Supported types: application/octet-stream, application/json, text/plain"),
- ));
+ return Err(AiRejection::BlobContentTypeUnsupported {
+ field: field_name,
+ content_type: ct.clone(),
+ });
}
} else {
- return Err(CaptureError::RequestParsingError(format!(
- "Missing required Content-Type header for blob part '{field_name}'"
- )));
+ return Err(AiRejection::BlobContentTypeMissing(field_name));
}
// Get length before moving data
@@ -738,9 +783,7 @@ fn process_blob_part(
// Reject empty blobs
if field_data_len == 0 {
- return Err(CaptureError::RequestParsingError(format!(
- "Blob part '{field_name}' cannot be empty (0 bytes)"
- )));
+ return Err(AiRejection::BlobEmpty(field_name));
}
// Create part info (clones needed for response)
@@ -770,7 +813,7 @@ async fn retrieve_multipart_parts(
multipart: &mut Multipart<'_>,
max_sum_of_parts_bytes: usize,
event_metadata: EventMetadata,
-) -> Result<RetrievedMultipartParts, CaptureError> {
+) -> Result<RetrievedMultipartParts, AiRejection> {
// Size limits
const MAX_COMBINED_SIZE: usize = 1024 * 1024 - 64 * 1024; // 1MB - 64KB = 960KB
@@ -790,7 +833,7 @@ async fn retrieve_multipart_parts(
while let Some(field) = multipart
.next_field()
.await
- .map_err(|e| CaptureError::RequestDecodingError(format!("Multipart parsing failed: {e}")))?
+ .map_err(|e| AiRejection::MultipartParseFailed(e.to_string()))?
{
part_count += 1;
@@ -810,15 +853,14 @@ async fn retrieve_multipart_parts(
// Event part was already consumed by retrieve_event_metadata - reject duplicates
if field_name == "event" {
- return Err(CaptureError::RequestParsingError(
- "Duplicate 'event' part found".to_string(),
- ));
+ return Err(AiRejection::DuplicateEventPart);
}
// Read the field data to get the length (this consumes the field)
- let field_data = field.bytes().await.map_err(|e| {
- CaptureError::RequestDecodingError(format!("Failed to read field data: {e}"))
- })?;
+ let field_data = field
+ .bytes()
+ .await
+ .map_err(|e| AiRejection::FieldDataUnreadable(e.to_string()))?;
// Track sum of all part sizes
sum_of_parts_bytes += field_data.len();
@@ -834,16 +876,12 @@ async fn retrieve_multipart_parts(
// Extract the property name after "event.properties."
// Validate that the property name doesn't contain dots (enforce top-level properties only)
if property_name.contains('.') {
- return Err(CaptureError::RequestParsingError(format!(
- "Blob property '{field_name}' contains nested properties (dots). Only top-level properties are allowed."
- )));
+ return Err(AiRejection::BlobPropertyNested(field_name));
}
// Check for duplicates before processing
if seen_property_names.contains(&field_name) {
- return Err(CaptureError::RequestParsingError(format!(
- "Duplicate blob property: {field_name}"
- )));
+ return Err(AiRejection::BlobPropertyDuplicate(field_name));
}
let (blob_part, part_info) = process_blob_part(
@@ -858,25 +896,25 @@ async fn retrieve_multipart_parts(
accepted_parts.push(part_info);
} else {
// Reject unknown fields that don't match expected patterns
- return Err(CaptureError::RequestParsingError(format!(
- "Unknown multipart field: '{field_name}'. Expected 'event', 'event.properties', or 'event.properties.<property_name>'"
- )));
+ return Err(AiRejection::UnknownField(field_name));
}
}
// Check combined size limit
let combined_size = event_size + properties_size;
if combined_size > MAX_COMBINED_SIZE {
- return Err(CaptureError::EventTooBig(format!(
- "Combined event and properties size ({combined_size} bytes) exceeds maximum allowed size ({MAX_COMBINED_SIZE} bytes)"
- )));
+ return Err(AiRejection::EventAndPropertiesTooBig {
+ size: combined_size,
+ max: MAX_COMBINED_SIZE,
+ });
}
// Check sum of all parts limit
if sum_of_parts_bytes > max_sum_of_parts_bytes {
- return Err(CaptureError::EventTooBig(format!(
- "Sum of all parts ({sum_of_parts_bytes} bytes) exceeds maximum allowed size ({max_sum_of_parts_bytes} bytes)"
- )));
+ return Err(AiRejection::SumOfPartsTooBig {
+ size: sum_of_parts_bytes,
+ max: max_sum_of_parts_bytes,
+ });
}
// Use the event JSON from the pre-parsed metadata
@@ -889,10 +927,7 @@ async fn retrieve_multipart_parts(
.is_some();
if has_embedded_properties && properties_json.is_some() {
- return Err(CaptureError::RequestParsingError(
- "Event cannot have both embedded properties and a separate 'event.properties' part"
- .to_string(),
- ));
+ return Err(AiRejection::ConflictingProperties);
}
// Determine which properties to use:
@@ -927,15 +962,13 @@ async fn retrieve_multipart_parts(
/// Returns parsed data with blob_parts for later S3 upload.
fn parse_multipart_data(
parts: RetrievedMultipartParts,
-) -> Result<ParsedMultipartData, CaptureError> {
+) -> Result<ParsedMultipartData, AiRejection> {
// Merge properties into the event
let mut event = parts.event_json;
if let Some(event_obj) = event.as_object_mut() {
event_obj.insert("properties".to_string(), parts.properties_json);
} else {
- return Err(CaptureError::RequestParsingError(
- "Event must be a JSON object".to_string(),
- ));
+ return Err(AiRejection::EventNotObject);
}
// Now validate the complete event structure
@@ -946,14 +979,14 @@ fn parse_multipart_data(
.as_object()
.and_then(|obj| obj.get("event"))
.and_then(|v| v.as_str())
- .ok_or_else(|| CaptureError::RequestParsingError("Event name is required".to_string()))?
+ .ok_or(AiRejection::EventNameRequired)?
.to_string();
let distinct_id = event
.as_object()
.and_then(|obj| obj.get("distinct_id"))
.and_then(|v| v.as_str())
- .ok_or_else(|| CaptureError::RequestParsingError("distinct_id is required".to_string()))?
+ .ok_or(AiRejection::DistinctIdRequired)?
.to_string();
// Extract and validate UUID
@@ -961,10 +994,9 @@ fn parse_multipart_data(
.as_object()
.and_then(|obj| obj.get("uuid"))
.and_then(|v| v.as_str())
- .ok_or_else(|| CaptureError::RequestParsingError("Event UUID is required".to_string()))
+ .ok_or(AiRejection::EventUuidRequired)
.and_then(|uuid_str| {
- Uuid::parse_str(uuid_str)
- .map_err(|e| CaptureError::RequestParsingError(format!("Invalid UUID format: {e}")))
+ Uuid::parse_str(uuid_str).map_err(|e| AiRejection::EventUuidInvalid(e.to_string()))
})?;
let timestamp = event
@@ -998,84 +1030,52 @@ fn parse_multipart_data(
}
/// Validate the structure and content of an AI event
-fn validate_event_structure(event: &Value) -> Result<(), CaptureError> {
+fn validate_event_structure(event: &Value) -> Result<(), AiRejection> {
// Check if event is an object
- let event_obj = event.as_object().ok_or_else(|| {
- CaptureError::RequestParsingError("Event must be a JSON object".to_string())
- })?;
+ let event_obj = event.as_object().ok_or(AiRejection::EventNotObject)?;
// Validate event name
let event_name = event_obj
.get("event")
.and_then(|v| v.as_str())
- .ok_or_else(|| {
- CaptureError::RequestParsingError("Event missing 'event' field".to_string())
- })?;
+ .ok_or(AiRejection::EventMissingName)?;
if event_name.is_empty() {
- return Err(CaptureError::RequestParsingError(
- "Event name cannot be empty".to_string(),
- ));
+ return Err(AiRejection::EventNameEmpty);
}
- // Only accept specific AI event types
- const ALLOWED_AI_EVENTS: [&str; 6] = [
- "$ai_generation",
- "$ai_trace",
- "$ai_span",
- "$ai_embedding",
- "$ai_metric",
- "$ai_feedback",
- ];
-
if !ALLOWED_AI_EVENTS.contains(&event_name) {
- return Err(CaptureError::RequestParsingError(format!(
- "Event name must be one of: {}, got '{}'",
- ALLOWED_AI_EVENTS.join(", "),
- event_name
- )));
+ return Err(AiRejection::EventNameNotAllowed(event_name.to_string()));
}
// Validate distinct_id
let distinct_id = event_obj
.get("distinct_id")
.and_then(|v| v.as_str())
- .ok_or_else(|| {
- CaptureError::RequestParsingError("Event missing 'distinct_id' field".to_string())
- })?;
+ .ok_or(AiRejection::EventMissingDistinctId)?;
if distinct_id.is_empty() {
- return Err(CaptureError::RequestParsingError(
- "distinct_id cannot be empty".to_string(),
- ));
+ return Err(AiRejection::DistinctIdEmpty);
}
// Validate properties object
let properties = event_obj
.get("properties")
.and_then(|v| v.as_object())
- .ok_or_else(|| {
- CaptureError::RequestParsingError("Event missing 'properties' field".to_string())
- })?;
+ .ok_or(AiRejection::EventMissingProperties)?;
// Validate required AI properties
if !properties.contains_key("$ai_model") {
- return Err(CaptureError::RequestParsingError(
- "Event properties must contain '$ai_model'".to_string(),
- ));
+ return Err(AiRejection::AiModelMissing);
}
let ai_model = properties
.get("$ai_model")
.and_then(|v| v.as_str())
- .ok_or_else(|| {
- CaptureError::RequestParsingError("$ai_model must be a string".to_string())
- })?;
+ .ok_or(AiRejection::AiModelNotString)?;
if ai_model.is_empty() {
- return Err(CaptureError::RequestParsingError(
- "$ai_model cannot be empty".to_string(),
- ));
+ return Err(AiRejection::AiModelEmpty);
}
debug!(
diff --git a/rust/capture/src/ai_rejection.rs b/rust/capture/src/ai_rejection.rs
new file mode 100644
index 000000000000..2187375ecc6a
--- /dev/null
+++ b/rust/capture/src/ai_rejection.rs
@@ -0,0 +1,510 @@
+//! Typed rejection conditions for the AI events endpoint (`/i/v0/ai`).
+//!
+//! The handler used to return a bare
+//! [`CaptureError::RequestParsingError`](crate::api::CaptureError) for ~25
+//! unrelated conditions, all carrying a free-form message. That is fine for an
+//! HTTP response but useless for deciding which ingestion warning a customer
+//! should see: telling "sent a non-AI event name" apart from "sent an unknown
+//! multipart field" would mean matching on message strings.
+//!
+//! So the rejection reasons are an enum. [`AiRejection::message`] reproduces the
+//! exact wire message each condition produced before, and
+//! [`From<AiRejection>`](CaptureError) picks the same `CaptureError` variant, so
+//! status codes and bodies are unchanged. The warning mapping then matches
+//! variants, which the compiler checks.
+
+use std::fmt;
+
+use crate::api::CaptureError;
+
+/// Event names the endpoint accepts. Anything else is a client sending ordinary
+/// analytics to the AI path.
+pub const ALLOWED_AI_EVENTS: [&str; 6] = [
+ "$ai_generation",
+ "$ai_trace",
+ "$ai_span",
+ "$ai_embedding",
+ "$ai_metric",
+ "$ai_feedback",
+];
+
+/// Which `CaptureError` a rejection becomes, and so which HTTP status the client
+/// sees. Preserved per-condition from before the enum existed.
+enum ErrorKind {
+ /// 400, transport-level: the request framing itself is wrong.
+ Decoding,
+ /// 400, content-level: the framing parsed but the contents are unusable.
+ Parsing,
+ /// 413.
+ TooBig,
+}
+
+/// A request the AI endpoint refused because of something the customer sent.
+///
+/// Server-side failures (blob storage unconfigured, S3 upload, Kafka, event
+/// serialization) are deliberately absent: they stay `CaptureError`, since they
+/// are ours to fix and must never surface as customer warnings.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum AiRejection {
+ // Request framing
+ NotMultipart,
+ InvalidBoundary(String),
+ MultipartParseFailed(String),
+ FieldDataUnreadable(String),
+ MissingEventPart,
+ FirstPartNotEvent(String),
+ DuplicateEventPart,
+ UnknownField(String),
+
+ // Event part
+ EventPartNotUtf8,
+ EventPartNotJson,
+ EventNotObject,
+
+ // Properties
+ PropertiesPartNotUtf8,
+ PropertiesPartNotJson,
+ ConflictingProperties,
+ EventMissingProperties,
+
+ // Blob parts
+ BlobContentTypeMissing(String),
+ BlobContentTypeUnsupported { field: String, content_type: String },
+ BlobEmpty(String),
+ BlobPropertyNested(String),
+ BlobPropertyDuplicate(String),
+
+ // Size limits
+ EventPartTooBig { size: usize, max: usize },
+ EventAndPropertiesTooBig { size: usize, max: usize },
+ SumOfPartsTooBig { size: usize, max: usize },
+
+ // Event identity
+ EventMissingName,
+ EventNameRequired,
+ EventNameEmpty,
+ EventMissingDistinctId,
+ DistinctIdRequired,
+ DistinctIdEmpty,
+ EventUuidRequired,
+ EventUuidInvalid(String),
+
+ // AI-specific validation
+ EventNameNotAllowed(String),
+ AiModelMissing,
+ AiModelNotString,
+ AiModelEmpty,
+}
+
+impl AiRejection {
+ /// The message this condition puts on the wire. Unchanged from when each
+ /// site built its `CaptureError` inline, so clients see the same bodies.
+ pub fn message(&self) -> String {
+ match self {
+ Self::NotMultipart => "Content-Type must be multipart/form-data".to_string(),
+ Self::InvalidBoundary(e) => format!("Invalid boundary in Content-Type: {e}"),
+ Self::MultipartParseFailed(e) => format!("Multipart parsing failed: {e}"),
+ Self::FieldDataUnreadable(e) => format!("Failed to read field data: {e}"),
+ Self::MissingEventPart => {
+ "Missing required 'event' part in multipart data".to_string()
+ }
+ Self::FirstPartNotEvent(field_name) => {
+ format!("First part must be 'event', got '{field_name}'")
+ }
+ Self::DuplicateEventPart => "Duplicate 'event' part found".to_string(),
+ Self::UnknownField(field_name) => format!(
+ "Unknown multipart field: '{field_name}'. Expected 'event', 'event.properties', or 'event.properties.<property_name>'"
+ ),
+
+ Self::EventPartNotUtf8 => "Event part must be valid UTF-8".to_string(),
+ Self::EventPartNotJson => "Event part must be valid JSON".to_string(),
+ Self::EventNotObject => "Event must be a JSON object".to_string(),
+
+ Self::PropertiesPartNotUtf8 => "Properties part must be valid UTF-8".to_string(),
+ Self::PropertiesPartNotJson => "Properties part must be valid JSON".to_string(),
+ Self::ConflictingProperties => {
+ "Event cannot have both embedded properties and a separate 'event.properties' part"
+ .to_string()
+ }
+ Self::EventMissingProperties => "Event missing 'properties' field".to_string(),
+
+ Self::BlobContentTypeMissing(field_name) => format!(
+ "Missing required Content-Type header for blob part '{field_name}'"
+ ),
+ Self::BlobContentTypeUnsupported {
+ field,
+ content_type,
+ } => format!(
+ "Unsupported content type for blob part '{field}': '{content_type}'. Supported types: application/octet-stream, application/json, text/plain"
+ ),
+ Self::BlobEmpty(field_name) => {
+ format!("Blob part '{field_name}' cannot be empty (0 bytes)")
+ }
+ Self::BlobPropertyNested(field_name) => format!(
+ "Blob property '{field_name}' contains nested properties (dots). Only top-level properties are allowed."
+ ),
+ Self::BlobPropertyDuplicate(field_name) => {
+ format!("Duplicate blob property: {field_name}")
+ }
+
+ Self::EventPartTooBig { size, max } => format!(
+ "Event part size ({size} bytes) exceeds maximum allowed size ({max} bytes)"
+ ),
+ Self::EventAndPropertiesTooBig { size, max } => format!(
+ "Combined event and properties size ({size} bytes) exceeds maximum allowed size ({max} bytes)"
+ ),
+ Self::SumOfPartsTooBig { size, max } => format!(
+ "Sum of all parts ({size} bytes) exceeds maximum allowed size ({max} bytes)"
+ ),
+
+ Self::EventMissingName => "Event missing 'event' field".to_string(),
+ Self::EventNameRequired => "Event name is required".to_string(),
+ Self::EventNameEmpty => "Event name cannot be empty".to_string(),
+ Self::EventMissingDistinctId => "Event missing 'distinct_id' field".to_string(),
+ Self::DistinctIdRequired => "distinct_id is required".to_string(),
+ Self::DistinctIdEmpty => "distinct_id cannot be empty".to_string(),
+ Self::EventUuidRequired => "Event UUID is required".to_string(),
+ Self::EventUuidInvalid(e) => format!("Invalid UUID format: {e}"),
+
+ Self::EventNameNotAllowed(event_name) => format!(
+ "Event name must be one of: {}, got '{}'",
+ ALLOWED_AI_EVENTS.join(", "),
+ event_name
+ ),
+ Self::AiModelMissing => "Event properties must contain '$ai_model'".to_string(),
+ Self::AiModelNotString => "$ai_model must be a string".to_string(),
+ Self::AiModelEmpty => "$ai_model cannot be empty".to_string(),
+ }
+ }
+
+ fn kind(&self) -> ErrorKind {
+ match self {
+ // Framing problems the multipart layer itself reports.
+ Self::NotMultipart
+ | Self::InvalidBoundary(_)
+ | Self::MultipartParseFailed(_)
+ | Self::FieldDataUnreadable(_) => ErrorKind::Decoding,
+
+ Self::EventPartTooBig { .. }
+ | Self::EventAndPropertiesTooBig { .. }
+ | Self::SumOfPartsTooBig { .. } => ErrorKind::TooBig,
+
+ Self::MissingEventPart
+ | Self::FirstPartNotEvent(_)
+ | Self::DuplicateEventPart
+ | Self::UnknownField(_)
+ | Self::EventPartNotUtf8
+ | Self::EventPartNotJson
+ | Self::EventNotObject
+ | Self::PropertiesPartNotUtf8
+ | Self::PropertiesPartNotJson
+ | Self::ConflictingProperties
+ | Self::EventMissingProperties
+ | Self::BlobContentTypeMissing(_)
+ | Self::BlobContentTypeUnsupported { .. }
+ | Self::BlobEmpty(_)
+ | Self::BlobPropertyNested(_)
+ | Self::BlobPropertyDuplicate(_)
+ | Self::EventMissingName
+ | Self::EventNameRequired
+ | Self::EventNameEmpty
+ | Self::EventMissingDistinctId
+ | Self::DistinctIdRequired
+ | Self::DistinctIdEmpty
+ | Self::EventUuidRequired
+ | Self::EventUuidInvalid(_)
+ | Self::EventNameNotAllowed(_)
+ | Self::AiModelMissing
+ | Self::AiModelNotString
+ | Self::AiModelEmpty => ErrorKind::Parsing,
+ }
+ }
+}
+
+impl fmt::Display for AiRejection {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.write_str(&self.message())
+ }
+}
+
+/// Every variant with the exact message it puts on the wire.
+///
+/// The single list of all variants in the crate. Variants carry `String`s so it
+/// can't be a const like `WarningType::ALL`, and it lives here rather than in a
+/// test module because two of them need it: the parity check below and the
+/// warning mapping in `ingestion_warnings::ai`. Two hand-maintained copies would
+/// drift, leaving a new variant silently untested by both.
+#[cfg(test)]
+pub(crate) fn all_variants_with_messages() -> Vec<(AiRejection, &'static str)> {
+ vec![
+ (
+ AiRejection::NotMultipart,
+ "Content-Type must be multipart/form-data",
+ ),
+ (
+ AiRejection::InvalidBoundary("bad".to_string()),
+ "Invalid boundary in Content-Type: bad",
+ ),
+ (
+ AiRejection::MultipartParseFailed("boom".to_string()),
+ "Multipart parsing failed: boom",
+ ),
+ (
+ AiRejection::FieldDataUnreadable("io".to_string()),
+ "Failed to read field data: io",
+ ),
+ (
+ AiRejection::MissingEventPart,
+ "Missing required 'event' part in multipart data",
+ ),
+ (
+ AiRejection::FirstPartNotEvent("blob".to_string()),
+ "First part must be 'event', got 'blob'",
+ ),
+ (
+ AiRejection::DuplicateEventPart,
+ "Duplicate 'event' part found",
+ ),
+ (
+ AiRejection::UnknownField("nope".to_string()),
+ "Unknown multipart field: 'nope'. Expected 'event', 'event.properties', or 'event.properties.<property_name>'",
+ ),
+ (
+ AiRejection::EventPartNotUtf8,
+ "Event part must be valid UTF-8",
+ ),
+ (
+ AiRejection::EventPartNotJson,
+ "Event part must be valid JSON",
+ ),
+ (AiRejection::EventNotObject, "Event must be a JSON object"),
+ (
+ AiRejection::PropertiesPartNotUtf8,
+ "Properties part must be valid UTF-8",
+ ),
+ (
+ AiRejection::PropertiesPartNotJson,
+ "Properties part must be valid JSON",
+ ),
+ (
+ AiRejection::ConflictingProperties,
+ "Event cannot have both embedded properties and a separate 'event.properties' part",
+ ),
+ (
+ AiRejection::EventMissingProperties,
+ "Event missing 'properties' field",
+ ),
+ (
+ AiRejection::BlobContentTypeMissing("event.properties.x".to_string()),
+ "Missing required Content-Type header for blob part 'event.properties.x'",
+ ),
+ (
+ AiRejection::BlobContentTypeUnsupported {
+ field: "event.properties.x".to_string(),
+ content_type: "image/png".to_string(),
+ },
+ "Unsupported content type for blob part 'event.properties.x': 'image/png'. Supported types: application/octet-stream, application/json, text/plain",
+ ),
+ (
+ AiRejection::BlobEmpty("event.properties.x".to_string()),
+ "Blob part 'event.properties.x' cannot be empty (0 bytes)",
+ ),
+ (
+ AiRejection::BlobPropertyNested("event.properties.a.b".to_string()),
+ "Blob property 'event.properties.a.b' contains nested properties (dots). Only top-level properties are allowed.",
+ ),
+ (
+ AiRejection::BlobPropertyDuplicate("event.properties.x".to_string()),
+ "Duplicate blob property: event.properties.x",
+ ),
+ (
+ AiRejection::EventPartTooBig {
+ size: 40_000,
+ max: 32_768,
+ },
+ "Event part size (40000 bytes) exceeds maximum allowed size (32768 bytes)",
+ ),
+ (
+ AiRejection::EventAndPropertiesTooBig {
+ size: 1_000_000,
+ max: 983_040,
+ },
+ "Combined event and properties size (1000000 bytes) exceeds maximum allowed size (983040 bytes)",
+ ),
+ (
+ AiRejection::SumOfPartsTooBig {
+ size: 30_000_000,
+ max: 26_214_400,
+ },
+ "Sum of all parts (30000000 bytes) exceeds maximum allowed size (26214400 bytes)",
+ ),
+ (
+ AiRejection::EventMissingName,
+ "Event missing 'event' field",
+ ),
+ (AiRejection::EventNameRequired, "Event name is required"),
+ (AiRejection::EventNameEmpty, "Event name cannot be empty"),
+ (
+ AiRejection::EventMissingDistinctId,
+ "Event missing 'distinct_id' field",
+ ),
+ (AiRejection::DistinctIdRequired, "distinct_id is required"),
+ (AiRejection::DistinctIdEmpty, "distinct_id cannot be empty"),
+ (AiRejection::EventUuidRequired, "Event UUID is required"),
+ (
+ AiRejection::EventUuidInvalid("invalid length".to_string()),
+ "Invalid UUID format: invalid length",
+ ),
+ (
+ AiRejection::EventNameNotAllowed("$pageview".to_string()),
+ "Event name must be one of: $ai_generation, $ai_trace, $ai_span, $ai_embedding, $ai_metric, $ai_feedback, got '$pageview'",
+ ),
+ (
+ AiRejection::AiModelMissing,
+ "Event properties must contain '$ai_model'",
+ ),
+ (AiRejection::AiModelNotString, "$ai_model must be a string"),
+ (AiRejection::AiModelEmpty, "$ai_model cannot be empty"),
+ ]
+}
+
+/// [`all_variants_with_messages`] without the messages, for callers that only
+/// need to walk every variant.
+#[cfg(test)]
+pub(crate) fn all_variants() -> Vec<AiRejection> {
+ all_variants_with_messages()
+ .into_iter()
+ .map(|(rejection, _)| rejection)
+ .collect()
+}
+
+impl From<AiRejection> for CaptureError {
+ fn from(rejection: AiRejection) -> Self {
+ let message = rejection.message();
+ match rejection.kind() {
+ ErrorKind::Decoding => CaptureError::RequestDecodingError(message),
+ ErrorKind::Parsing => CaptureError::RequestParsingError(message),
+ ErrorKind::TooBig => CaptureError::EventTooBig(message),
+ }
+ }
+}
+
+/// Why an AI request failed: something the customer sent, or something on our
+/// side.
+///
+/// Splitting these is what lets the handler emit a warning for the first kind
+/// and stay silent for the second, while both still become a `CaptureError` for
+/// the response. `From` impls in both directions keep `?` working unchanged at
+/// every existing call site.
+#[derive(Debug)]
+pub enum AiFailure {
+ Rejected(AiRejection),
+ Other(CaptureError),
+}
+
+impl From<AiRejection> for AiFailure {
+ fn from(rejection: AiRejection) -> Self {
+ Self::Rejected(rejection)
+ }
+}
+
+impl From<CaptureError> for AiFailure {
+ fn from(err: CaptureError) -> Self {
+ Self::Other(err)
+ }
+}
+
+impl From<AiFailure> for CaptureError {
+ fn from(failure: AiFailure) -> Self {
+ match failure {
+ AiFailure::Rejected(rejection) => rejection.into(),
+ AiFailure::Other(err) => err,
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use axum::response::IntoResponse;
+ use rstest::rstest;
+
+ /// The regression guard for the refactor that introduced this enum: the ~30
+ /// conditions it replaced each has to keep putting the same thing on the
+ /// wire, and a reviewer can't verify that many inline `format!`s by eye.
+ ///
+ /// The pre-existing tests in `tests/integration_ai_endpoint.rs` are the
+ /// end-to-end half of the same proof; they pass unmodified.
+ #[test]
+ fn every_rejection_keeps_its_original_wire_message() {
+ for (rejection, expected) in all_variants_with_messages() {
+ assert_eq!(rejection.message(), expected, "message for {rejection:?}");
+ // Display and message must not drift apart; callers use both.
+ assert_eq!(rejection.to_string(), expected);
+ }
+ }
+
+ // `all_variants_with_messages` is hand-written, so it can fall behind the
+ // enum. Counting arms in the exhaustive `message` match is the cheapest way
+ // to notice: a new variant compiles there but is missing here.
+ #[test]
+ fn the_variant_list_covers_every_variant() {
+ let listed = all_variants();
+ let unique: std::collections::HashSet<_> =
+ listed.iter().map(std::mem::discriminant).collect();
+
+ assert_eq!(
+ unique.len(),
+ listed.len(),
+ "all_variants lists the same variant twice"
+ );
+ assert_eq!(
+ listed.len(),
+ 35,
+ "variant count changed — add the new variant to all_variants_with_messages \
+ and update this expected count"
+ );
+ }
+
+ // The response body is the message, so a CaptureError variant swap would
+ // silently change a 400 into a 413 or vice versa.
+ #[rstest]
+ #[case::not_multipart(AiRejection::NotMultipart, 400)]
+ #[case::boundary(AiRejection::InvalidBoundary("x".to_string()), 400)]
+ #[case::multipart_parse(AiRejection::MultipartParseFailed("x".to_string()), 400)]
+ #[case::field_read(AiRejection::FieldDataUnreadable("x".to_string()), 400)]
+ #[case::missing_event_part(AiRejection::MissingEventPart, 400)]
+ #[case::unknown_field(AiRejection::UnknownField("x".to_string()), 400)]
+ #[case::event_not_json(AiRejection::EventPartNotJson, 400)]
+ #[case::blob_empty(AiRejection::BlobEmpty("x".to_string()), 400)]
+ #[case::event_name_not_allowed(AiRejection::EventNameNotAllowed("$pageview".to_string()), 400)]
+ #[case::ai_model_missing(AiRejection::AiModelMissing, 400)]
+ #[case::event_part_too_big(AiRejection::EventPartTooBig { size: 1, max: 0 }, 413)]
+ #[case::combined_too_big(AiRejection::EventAndPropertiesTooBig { size: 1, max: 0 }, 413)]
+ #[case::sum_of_parts_too_big(AiRejection::SumOfPartsTooBig { size: 1, max: 0 }, 413)]
+ fn rejections_keep_their_status_code(#[case] rejection: AiRejection, #[case] expected: u16) {
+ let err: CaptureError = rejection.into();
+ let status = err.into_response().status().as_u16();
+ assert_eq!(status, expected);
+ }
+
+ #[test]
+ fn message_survives_the_round_trip_through_ai_failure() {
+ let rejection = AiRejection::EventNameNotAllowed("$pageview".to_string());
+ let expected = rejection.message();
+
+ let failure: AiFailure = rejection.into();
+ let err: CaptureError = failure.into();
+
+ assert!(matches!(err, CaptureError::RequestParsingError(ref m) if *m == expected));
+ }
+
+ #[test]
+ fn server_side_errors_pass_through_unchanged() {
+ let failure: AiFailure = CaptureError::NonRetryableSinkError.into();
+ assert!(matches!(failure, AiFailure::Other(_)));
+
+ let err: CaptureError = failure.into();
+ assert!(matches!(err, CaptureError::NonRetryableSinkError));
+ }
+}
diff --git a/rust/capture/src/events/analytics.rs b/rust/capture/src/events/analytics.rs
index 36b9af513819..5f8298fb5307 100644
--- a/rust/capture/src/events/analytics.rs
+++ b/rust/capture/src/events/analytics.rs
@@ -25,8 +25,10 @@ use crate::{
events::overflow_stamping::stamp_overflow_reason,
global_rate_limiter::{GlobalRateLimitKey, GlobalRateLimiter},
ingestion_warnings::{
- emit_distinct_id_truncated_warning, emit_processing_abort_warning, emit_rate_limit_warning,
- legacy_request_context,
+ emit_rate_limit_warning,
+ legacy::{
+ emit_distinct_id_truncated_warning, emit_processing_abort_warning, request_context,
+ },
},
prometheus::{report_clock_skew, report_dropped_events},
router, sinks,
@@ -532,7 +534,7 @@ async fn process_events_inner(
if warned_event_count > 0 {
emit_rate_limit_warning(
ingestion_warning_emitter.as_deref(),
- &legacy_request_context(context),
+ &request_context(context),
CAPTURE_LEGACY_RATE_LIMIT,
&warned_distinct_ids,
warned_event_count,
@@ -590,7 +592,7 @@ async fn process_events_inner(
if truncated_count > 0 {
emit_distinct_id_truncated_warning(
ingestion_warning_emitter.as_deref(),
- &legacy_request_context(context),
+ &request_context(context),
truncated_sample.filter(|_| truncated_count == 1),
truncated_count,
);
diff --git a/rust/capture/src/ingestion_warnings/ai.rs b/rust/capture/src/ingestion_warnings/ai.rs
new file mode 100644
index 000000000000..7eec6d92a742
--- /dev/null
+++ b/rust/capture/src/ingestion_warnings/ai.rs
@@ -0,0 +1,446 @@
+//! Ingestion warnings for the AI events endpoint (`/i/v0/ai`).
+//!
+//! The endpoint's context projection lives with the handler, which owns the
+//! event shape it reads `$lib` out of; see this directory's module doc.
+//!
+//! One request is one event here, so every warning carries `count = 1`.
+
+use common_ingestion_warnings::{
+ emit_request_warning, WarningEmitter, WarningRequestContext, WarningType, CAPTURE_AI_EVENTS,
+};
+use serde_json::{json, Map};
+
+use super::bounded_detail;
+use crate::ai_rejection::{AiFailure, AiRejection};
+use crate::api::CaptureError;
+
+/// Map a rejection to the warning the customer should see, or `None` when they
+/// can't act on it.
+///
+/// Attributable is not the same as actionable. Every rejection here happens
+/// after the token is read, so all of them *could* be attributed to a team; the
+/// bar for emitting is that the customer can change something to stop it.
+///
+/// Five of these reuse types the analytics paths already emit, because the
+/// condition is identical and a reader of the v2 table shouldn't have to learn a
+/// second vocabulary for the same mistake. The AI-specific types cover what has
+/// no analytics equivalent: this endpoint accepts only six event names and
+/// requires `$ai_model`, and its payload is multipart rather than a JSON batch.
+///
+/// Exhaustive with no catch-all, so a new rejection variant fails to compile
+/// until someone decides whether customers should see a warning for it.
+pub fn warning_for_ai_rejection(rejection: &AiRejection) -> Option<WarningType> {
+ match rejection {
+ // Sending ordinary analytics to the AI path, or omitting the one
+ // property every AI event needs.
+ AiRejection::EventNameNotAllowed(_)
+ | AiRejection::AiModelMissing
+ | AiRejection::AiModelNotString
+ | AiRejection::AiModelEmpty => Some(WarningType::InvalidAiEvent),
+
+ // Shared with the analytics paths: same mistake, same type.
+ AiRejection::EventMissingName
+ | AiRejection::EventNameRequired
+ | AiRejection::EventNameEmpty => Some(WarningType::MissingEventName),
+ AiRejection::EventMissingDistinctId
+ | AiRejection::DistinctIdRequired
+ | AiRejection::DistinctIdEmpty => Some(WarningType::MissingDistinctId),
+ AiRejection::EventUuidRequired => Some(WarningType::MissingEventUuid),
+ AiRejection::EventUuidInvalid(_) => Some(WarningType::InvalidEventUuid),
+ AiRejection::EventPartTooBig { .. }
+ | AiRejection::EventAndPropertiesTooBig { .. }
+ | AiRejection::SumOfPartsTooBig { .. } => Some(WarningType::MessageSizeTooLarge),
+
+ // The properties object specifically is missing or unreadable.
+ AiRejection::EventMissingProperties
+ | AiRejection::PropertiesPartNotUtf8
+ | AiRejection::PropertiesPartNotJson => Some(WarningType::MalformedEventProperties),
+
+ // Structural problems the customer built into the request.
+ AiRejection::NotMultipart
+ | AiRejection::InvalidBoundary(_)
+ | AiRejection::MissingEventPart
+ | AiRejection::FirstPartNotEvent(_)
+ | AiRejection::DuplicateEventPart
+ | AiRejection::UnknownField(_)
+ | AiRejection::EventPartNotUtf8
+ | AiRejection::EventPartNotJson
+ | AiRejection::EventNotObject
+ | AiRejection::ConflictingProperties
+ | AiRejection::BlobContentTypeMissing(_)
+ | AiRejection::BlobContentTypeUnsupported { .. }
+ | AiRejection::BlobEmpty(_)
+ | AiRejection::BlobPropertyNested(_)
+ | AiRejection::BlobPropertyDuplicate(_) => Some(WarningType::InvalidAiPayload),
+
+ // The body stream broke mid-read, so the request was truncated or
+ // aborted. We can't tell a client that hung up from a proxy or our own
+ // load balancer dropping the connection, and blaming the customer's
+ // payload for a drop we caused is worse than staying quiet. Same call
+ // the legacy path makes for `BodyReadTimeout`.
+ //
+ // Little is lost: a body that is genuinely malformed rather than
+ // truncated fails one of the specific arms above, which say more.
+ AiRejection::MultipartParseFailed(_) | AiRejection::FieldDataUnreadable(_) => None,
+ }
+}
+
+/// Emit the warning for a failed AI request, if the customer should see one.
+///
+/// The caller only reaches this once a token is known, so attribution is always
+/// available; pre-token failures never get here.
+pub fn emit_ai_failure_warning(
+ emitter: Option<&dyn WarningEmitter>,
+ request: &WarningRequestContext,
+ failure: &AiFailure,
+) {
+ let Some((warning, details)) = warning_for_ai_failure(failure) else {
+ return;
+ };
+ emit_request_warning(emitter, request, CAPTURE_AI_EVENTS, warning, details, 1);
+}
+
+/// The warning and details for a failure, or `None` when the customer can't act
+/// on it.
+fn warning_for_ai_failure(
+ failure: &AiFailure,
+) -> Option<(WarningType, Map<String, serde_json::Value>)> {
+ match failure {
+ AiFailure::Rejected(rejection) => {
+ Some((warning_for_ai_rejection(rejection)?, details_for(rejection)))
+ }
+
+ // Both of these come from the gzip decompressor, the only shared helper
+ // the handler calls after reading the token. Its size check raises
+ // `EventTooBig`; a corrupt stream raises `RequestDecodingError`. Bad
+ // compression is the customer's payload just as much as a wrong
+ // Content-Type is, so it gets the same treatment.
+ AiFailure::Other(CaptureError::EventTooBig(_)) => {
+ Some((WarningType::MessageSizeTooLarge, Map::new()))
+ }
+ AiFailure::Other(CaptureError::RequestDecodingError(_)) => {
+ Some((WarningType::InvalidAiPayload, Map::new()))
+ }
+
+ // Everything else reaching here is ours: quota is surfaced through
+ // billing, and blob storage, S3, Kafka, and serialization failures are
+ // not the customer's to fix.
+ AiFailure::Other(_) => None,
+ }
+}
+
+/// Per-rejection details.
+///
+/// Only values that are safe to show and useful to act on: the rejected event
+/// name, the offending part name, and sizes. The rejection's own message is
+/// deliberately excluded — several embed a library error string, and this lands
+/// in a customer-visible column.
+///
+/// Every value copied out of the request goes through
+/// [`bounded_detail`](super::bounded_detail): all three are client-controlled and
+/// nothing downstream length-limits details, so an oversized one would inflate
+/// the warning message and its stored row.
+fn details_for(rejection: &AiRejection) -> Map<String, serde_json::Value> {
+ let mut details = Map::new();
+ match rejection {
+ AiRejection::EventNameNotAllowed(event_name) => {
+ details.insert("eventName".to_string(), json!(bounded_detail(event_name)));
+ details.insert(
+ "allowed".to_string(),
+ json!(crate::ai_rejection::ALLOWED_AI_EVENTS),
+ );
+ }
+ AiRejection::FirstPartNotEvent(field)
+ | AiRejection::UnknownField(field)
+ | AiRejection::BlobContentTypeMissing(field)
+ | AiRejection::BlobEmpty(field)
+ | AiRejection::BlobPropertyNested(field)
+ | AiRejection::BlobPropertyDuplicate(field) => {
+ details.insert("part".to_string(), json!(bounded_detail(field)));
+ }
+ AiRejection::BlobContentTypeUnsupported {
+ field,
+ content_type,
+ } => {
+ details.insert("part".to_string(), json!(bounded_detail(field)));
+ details.insert(
+ "contentType".to_string(),
+ json!(bounded_detail(content_type)),
+ );
+ }
+ AiRejection::EventPartTooBig { size, max }
+ | AiRejection::EventAndPropertiesTooBig { size, max }
+ | AiRejection::SumOfPartsTooBig { size, max } => {
+ details.insert("size".to_string(), json!(size));
+ details.insert("limit".to_string(), json!(max));
+ }
+ _ => {}
+ }
+ details
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use common_ingestion_warnings::test_support::CollectingEmitter;
+ use rstest::rstest;
+
+ fn request() -> WarningRequestContext {
+ WarningRequestContext {
+ token: "tok".to_string(),
+ lib: "posthog-python".to_string(),
+ lib_version: "3.1.0".to_string(),
+ path: "/i/v0/ai".to_string(),
+ }
+ }
+
+ #[rstest]
+ #[case::wrong_event_name(
+ AiRejection::EventNameNotAllowed("$pageview".to_string()),
+ Some(WarningType::InvalidAiEvent)
+ )]
+ #[case::no_model(AiRejection::AiModelMissing, Some(WarningType::InvalidAiEvent))]
+ #[case::no_event_name(AiRejection::EventNameRequired, Some(WarningType::MissingEventName))]
+ #[case::no_distinct_id(AiRejection::DistinctIdEmpty, Some(WarningType::MissingDistinctId))]
+ #[case::no_uuid(AiRejection::EventUuidRequired, Some(WarningType::MissingEventUuid))]
+ #[case::bad_uuid(
+ AiRejection::EventUuidInvalid("nope".to_string()),
+ Some(WarningType::InvalidEventUuid)
+ )]
+ #[case::oversize(
+ AiRejection::SumOfPartsTooBig { size: 1, max: 0 },
+ Some(WarningType::MessageSizeTooLarge)
+ )]
+ #[case::bad_properties(
+ AiRejection::PropertiesPartNotJson,
+ Some(WarningType::MalformedEventProperties)
+ )]
+ #[case::bad_multipart(AiRejection::NotMultipart, Some(WarningType::InvalidAiPayload))]
+ // Truncated or aborted body: fault is ambiguous, so nothing is emitted.
+ #[case::truncated_stream(AiRejection::MultipartParseFailed("eof".to_string()), None)]
+ #[case::truncated_field(AiRejection::FieldDataUnreadable("eof".to_string()), None)]
+ #[case::bad_blob(
+ AiRejection::BlobEmpty("event.properties.x".to_string()),
+ Some(WarningType::InvalidAiPayload)
+ )]
+ fn rejections_map_to_their_warning(
+ #[case] rejection: AiRejection,
+ #[case] expected: Option<WarningType>,
+ ) {
+ assert_eq!(warning_for_ai_rejection(&rejection), expected);
+ }
+
+ // Same trust chain the other pipelines pin: an emitted type that is not
+ // capture-produced is demoted to a generic client warning at the consumer,
+ // and one on both routes breaks the common crate's one-route invariant.
+ // Both fail silently in production. Covers every variant, so a new one
+ // can't slip in mapped to an untrusted type.
+ #[test]
+ fn every_rejection_maps_to_a_trusted_single_routed_type() {
+ let mut silent = Vec::new();
+
+ for rejection in crate::ai_rejection::all_variants() {
+ let Some(warning) = warning_for_ai_rejection(&rejection) else {
+ silent.push(rejection);
+ continue;
+ };
+ assert!(
+ warning.capture_produced(),
+ "{rejection:?} maps to {warning:?}, which is not on the consumer trust allowlist"
+ );
+ let tag_routed = WarningType::from_tag(warning.as_str()) == Some(warning);
+ let direct = WarningType::DIRECT_EMIT.contains(&warning);
+ assert!(
+ tag_routed ^ direct,
+ "{warning:?} must be on exactly one emit route"
+ );
+ }
+
+ // Pinned rather than merely allowed: staying silent is a judgment call
+ // about fault, so a third variant joining this set should be a decision
+ // someone made here, not a mapping someone forgot. Compared by variant,
+ // since the payload values are placeholders.
+ let silent: Vec<_> = silent.iter().map(std::mem::discriminant).collect();
+ let expected = [
+ AiRejection::MultipartParseFailed(String::new()),
+ AiRejection::FieldDataUnreadable(String::new()),
+ ];
+ assert_eq!(
+ silent,
+ expected
+ .iter()
+ .map(std::mem::discriminant)
+ .collect::<Vec<_>>(),
+ "the set of rejections that emit nothing changed"
+ );
+ }
+
+ #[test]
+ fn wrong_event_name_reports_the_name_and_what_was_expected() {
+ let emitter = CollectingEmitter::default();
+ emit_ai_failure_warning(
+ Some(&emitter),
+ &request(),
+ &AiFailure::Rejected(AiRejection::EventNameNotAllowed("$pageview".to_string())),
+ );
+
+ let emitted = emitter.emitted();
+ assert_eq!(emitted.len(), 1);
+ let warning = &emitted[0];
+ assert_eq!(warning.warning, WarningType::InvalidAiEvent);
+ assert_eq!(warning.source, CAPTURE_AI_EVENTS);
+ // One request is one event.
+ assert_eq!(warning.count, 1);
+ assert_eq!(
+ warning.extra_details.get("eventName"),
+ Some(&json!("$pageview"))
+ );
+ assert_eq!(
+ warning.extra_details.get("lib"),
+ Some(&json!("posthog-python"))
+ );
+ assert_eq!(warning.extra_details.get("path"), Some(&json!("/i/v0/ai")));
+ }
+
+ #[test]
+ fn blob_rejection_names_the_part_but_not_the_error_message() {
+ let emitter = CollectingEmitter::default();
+ emit_ai_failure_warning(
+ Some(&emitter),
+ &request(),
+ &AiFailure::Rejected(AiRejection::BlobContentTypeUnsupported {
+ field: "event.properties.image".to_string(),
+ content_type: "image/png".to_string(),
+ }),
+ );
+
+ let emitted = emitter.emitted();
+ assert_eq!(emitted.len(), 1);
+ assert_eq!(
+ emitted[0].extra_details.get("part"),
+ Some(&json!("event.properties.image"))
+ );
+ assert_eq!(
+ emitted[0].extra_details.get("contentType"),
+ Some(&json!("image/png"))
+ );
+ assert!(!emitted[0].extra_details.contains_key("message"));
+ }
+
+ #[test]
+ fn oversize_rejection_reports_size_against_the_limit() {
+ let emitter = CollectingEmitter::default();
+ emit_ai_failure_warning(
+ Some(&emitter),
+ &request(),
+ &AiFailure::Rejected(AiRejection::SumOfPartsTooBig {
+ size: 30_000_000,
+ max: 26_214_400,
+ }),
+ );
+
+ let emitted = emitter.emitted();
+ assert_eq!(emitted[0].warning, WarningType::MessageSizeTooLarge);
+ assert_eq!(
+ emitted[0].extra_details.get("size"),
+ Some(&json!(30_000_000))
+ );
+ assert_eq!(
+ emitted[0].extra_details.get("limit"),
+ Some(&json!(26_214_400))
+ );
+ }
+
+ // The gzip decompressor is the one shared helper the handler calls after
+ // reading the token, so both its failures are attributable and actionable
+ // even though neither is an AiRejection.
+ #[rstest]
+ #[case::oversize(
+ CaptureError::EventTooBig("too big".to_string()),
+ WarningType::MessageSizeTooLarge
+ )]
+ #[case::corrupt_gzip(
+ CaptureError::RequestDecodingError("invalid GZIP data".to_string()),
+ WarningType::InvalidAiPayload
+ )]
+ fn gzip_failures_warn(#[case] err: CaptureError, #[case] expected: WarningType) {
+ let emitter = CollectingEmitter::default();
+ emit_ai_failure_warning(Some(&emitter), &request(), &AiFailure::Other(err));
+
+ let emitted = emitter.emitted();
+ assert_eq!(emitted.len(), 1);
+ assert_eq!(emitted[0].warning, expected);
+ }
+
+ #[rstest]
+ #[case::quota(CaptureError::BillingLimit)]
+ #[case::blob_storage(CaptureError::ServiceUnavailable("no s3".to_string()))]
+ #[case::s3_upload(CaptureError::NonRetryableSinkError)]
+ #[case::kafka(CaptureError::RetryableSinkError)]
+ #[case::internal(CaptureError::InternalError("boom".to_string()))]
+ fn our_failures_never_warn(#[case] err: CaptureError) {
+ let emitter = CollectingEmitter::default();
+ emit_ai_failure_warning(Some(&emitter), &request(), &AiFailure::Other(err));
+ assert!(emitter.emitted().is_empty());
+ }
+
+ // Details are client-controlled and nothing downstream length-limits them,
+ // so an oversized event name or part name must not inflate the warning
+ // message or its stored row. Truncation is marked and char-safe.
+ #[rstest]
+ #[case::event_name(
+ AiRejection::EventNameNotAllowed("$".to_string() + &"n".repeat(500)),
+ "eventName"
+ )]
+ #[case::part_name(
+ AiRejection::UnknownField("f".repeat(500)),
+ "part"
+ )]
+ fn oversized_client_values_are_bounded(#[case] rejection: AiRejection, #[case] key: &str) {
+ let emitter = CollectingEmitter::default();
+ emit_ai_failure_warning(Some(&emitter), &request(), &AiFailure::Rejected(rejection));
+
+ let emitted = emitter.emitted();
+ let value = emitted[0].extra_details[key]
+ .as_str()
+ .expect("string detail");
+ assert!(
+ value.chars().count() <= crate::ingestion_warnings::MAX_SDK_ATTRIBUTION_LEN + 1,
+ "{key} was not bounded: {} chars",
+ value.chars().count()
+ );
+ assert!(value.ends_with('\u{2026}'), "{key} should mark truncation");
+ }
+
+ // A multi-byte name must not be cut mid-character, which would produce
+ // invalid UTF-8 in the warning payload.
+ #[test]
+ fn bounding_respects_char_boundaries() {
+ let emitter = CollectingEmitter::default();
+ emit_ai_failure_warning(
+ Some(&emitter),
+ &request(),
+ &AiFailure::Rejected(AiRejection::UnknownField("\u{4f60}\u{597d}".repeat(200))),
+ );
+
+ let emitted = emitter.emitted();
+ let value = emitted[0].extra_details["part"]
+ .as_str()
+ .expect("string detail");
+ assert!(value.ends_with('\u{2026}'));
+ // Round-trips as valid UTF-8 with whole characters only.
+ assert!(value
+ .trim_end_matches('\u{2026}')
+ .chars()
+ .all(|c| c == '\u{4f60}' || c == '\u{597d}'));
+ }
+
+ #[test]
+ fn no_emitter_is_a_silent_no_op() {
+ emit_ai_failure_warning(
+ None,
+ &request(),
+ &AiFailure::Rejected(AiRejection::AiModelMissing),
+ );
+ }
+}
diff --git a/rust/capture/src/ingestion_warnings.rs b/rust/capture/src/ingestion_warnings/legacy.rs
similarity index 70%
rename from rust/capture/src/ingestion_warnings.rs
rename to rust/capture/src/ingestion_warnings/legacy.rs
index f7388629d6a3..2291d094f681 100644
--- a/rust/capture/src/ingestion_warnings.rs
+++ b/rust/capture/src/ingestion_warnings/legacy.rs
@@ -1,81 +1,31 @@
-//! Per-path SDK attribution for ingestion warnings.
+//! Ingestion warnings for the legacy analytics path.
//!
-//! Every capture pipeline learns the client SDK differently, and the differences
-//! are permanent, not transitional:
+//! Legacy's context projection lives here rather than with its pipeline (as
+//! v1's does) because legacy has no subtree of its own — it spans
+//! `v0_endpoint`, `v0_request`, `events/`, and `payload/`.
//!
-//! * v1 requires the `PostHog-Sdk-Info` header and materializes
-//! `$lib`/`$lib_version` from it, overriding whatever the body claims
-//! ([`crate::v1::context::RequestContext::sdk_lib_and_version`]).
-//! * The legacy path has no such header contract. Its only source is the events'
-//! `$lib`/`$lib_version` properties, which are gone by the time the pipeline
-//! holds serialized `CapturedEvent`s — so the batch handler snapshots them
-//! onto [`ProcessingContext`] while the events are still typed.
-//! * Replay and the AI endpoint each carry their own quirks and will need their
-//! own conversion here when they start emitting.
-//!
-//! Normalizing lives here rather than in `common_ingestion_warnings` so that
-//! crate never learns capture's event shapes: it takes concrete strings and
-//! stamps them.
-
-use std::collections::HashSet;
+//! Legacy has no `PostHog-Sdk-Info` header contract. Its only source of SDK
+//! identity is the events' `$lib`/`$lib_version` properties, which are gone by
+//! the time the pipeline holds serialized `CapturedEvent`s, so the batch handler
+//! snapshots them onto [`ProcessingContext`] while the events are still typed.
use common_ingestion_warnings::{
- emit_request_warning, WarningEmitter, WarningRequestContext, WarningSource, WarningType,
- CAPTURE_LEGACY_ANALYTICS, UNKNOWN_ATTRIBUTION,
+ emit_request_warning, WarningEmitter, WarningRequestContext, WarningType,
+ CAPTURE_LEGACY_ANALYTICS,
};
-use common_types::{EventWithLibraryInfo, RawEvent};
use serde_json::{json, Map};
use uuid::Uuid;
+use super::unknown_if_missing;
use crate::api::CaptureError;
use crate::v0_request::ProcessingContext;
-use crate::v1::context::RequestContext;
-
-/// Max accepted length of a client-supplied `$lib` or `$lib_version`, matching
-/// the bound v1 puts on the `PostHog-Sdk-Info` header (real values are ~20
-/// bytes). Oversized values are treated as absent rather than truncated: they
-/// would otherwise ride into every warning payload for the batch and into the
-/// `Debug` output of [`ProcessingContext`], which the legacy path logs several
-/// times per request when chatty debug is on.
-const MAX_SDK_ATTRIBUTION_LEN: usize = 200;
-
-/// SDK identity as reported by a batch, for attribution only.
-///
-/// Both fields are unvalidated client input. Nothing routes on them.
-#[derive(Debug, Clone, Default, PartialEq, Eq)]
-pub struct SdkAttribution {
- pub lib: Option<String>,
- pub lib_version: Option<String>,
-}
-
-impl SdkAttribution {
- /// Take attribution from the first event of a batch.
- ///
- /// One batch is one SDK in every real client: batching is a client-side
- /// buffer flush, so events in it share a `$lib`. Scanning further to
- /// reconcile disagreement would cost a pass over the batch on the hot path
- /// to improve a field that is only ever displayed.
- pub fn from_first_event(events: &[RawEvent]) -> Self {
- let Some(info) = events.first().and_then(|e| e.extract_library_info()) else {
- return Self::default();
- };
- Self {
- lib: within_bound(info.name),
- lib_version: info.version.and_then(within_bound),
- }
- }
-}
-
-fn within_bound(value: String) -> Option<String> {
- (value.len() <= MAX_SDK_ATTRIBUTION_LEN).then_some(value)
-}
/// Warning attribution for a legacy-path batch.
///
/// SDK fields come from the snapshot the handler took during batch construction;
/// a batch that reported no `$lib` (or a `$lib` with no version, which the JS
-/// SDK can do) stamps [`UNKNOWN_ATTRIBUTION`] rather than dropping the key.
-pub fn legacy_request_context(context: &ProcessingContext) -> WarningRequestContext {
+/// SDK can do) stamps `UNKNOWN_ATTRIBUTION` rather than dropping the key.
+pub fn request_context(context: &ProcessingContext) -> WarningRequestContext {
WarningRequestContext {
token: context.token.clone(),
lib: unknown_if_missing(context.sdk_attribution.lib.as_deref()),
@@ -84,57 +34,6 @@ pub fn legacy_request_context(context: &ProcessingContext) -> WarningRequestCont
}
}
-/// Warning attribution for a v1 request.
-///
-/// `sdk_lib_and_version` is all-or-nothing — the header is a single
-/// `name/version` string — so both fields fall back together.
-pub fn v1_request_context(context: &RequestContext) -> WarningRequestContext {
- let (lib, lib_version) = context
- .sdk_lib_and_version()
- .unwrap_or((UNKNOWN_ATTRIBUTION, UNKNOWN_ATTRIBUTION));
- WarningRequestContext {
- token: context.api_token.clone(),
- lib: lib.to_string(),
- lib_version: lib_version.to_string(),
- path: context.path.to_string(),
- }
-}
-
-/// Emit the `high_volume_distinct_id` warning for one batch's rate-limited
-/// events. Shared by the v1 and legacy rate limiter stages, which differ only in
-/// their [`WarningSource`] — the payload must not drift between them, since a
-/// reader of the v2 table can't tell which pipeline served a request.
-///
-/// `distinct_id` is included only when the batch had exactly one hot key; with
-/// several it would be an arbitrary pick, and `distinctIdCount` already says how
-/// many there were. The value needs no size bounding here: both pipelines drop
-/// oversized distinct_ids before the limiter runs.
-pub fn emit_rate_limit_warning(
- emitter: Option<&dyn WarningEmitter>,
- request: &WarningRequestContext,
- source: WarningSource,
- limited_distinct_ids: &HashSet<&str>,
- limited_event_count: u64,
-) {
- let mut details = Map::new();
- details.insert(
- "distinctIdCount".to_string(),
- json!(limited_distinct_ids.len()),
- );
- if let [distinct_id] = limited_distinct_ids.iter().copied().collect::<Vec<_>>()[..] {
- details.insert("distinctId".to_string(), json!(distinct_id));
- }
-
- emit_request_warning(
- emitter,
- request,
- source,
- WarningType::HighVolumeDistinctId,
- details,
- limited_event_count,
- );
-}
-
/// Emit the `distinct_id_truncated` warning for one legacy batch's events
/// whose distinct_id was cut down to the 200-char cap at extraction. The
/// events were ingested (modified, not dropped), so this is legacy-only: v1
@@ -168,13 +67,6 @@ pub fn emit_distinct_id_truncated_warning(
);
}
-fn unknown_if_missing(value: Option<&str>) -> String {
- match value {
- Some(v) if !v.trim().is_empty() => v.to_string(),
- _ => UNKNOWN_ATTRIBUTION.to_string(),
- }
-}
-
/// Map a legacy-path request abort to the ingestion warning customers should
/// see, or `None` for failures customers can't act on.
///
@@ -267,7 +159,7 @@ pub fn emit_processing_abort_warning(
};
emit_request_warning(
emitter,
- &legacy_request_context(context),
+ &request_context(context),
CAPTURE_LEGACY_ANALYTICS,
warning,
Map::new(),
@@ -278,21 +170,9 @@ pub fn emit_processing_abort_warning(
#[cfg(test)]
mod tests {
use super::*;
+ use crate::ingestion_warnings::{raw_event, SdkAttribution, MAX_SDK_ATTRIBUTION_LEN};
use common_ingestion_warnings::test_support::CollectingEmitter;
- use serde_json::json;
-
- fn raw_event(properties: serde_json::Value) -> RawEvent {
- RawEvent {
- event: "$pageview".to_string(),
- properties: properties
- .as_object()
- .expect("test properties must be an object")
- .iter()
- .map(|(k, v)| (k.clone(), v.clone()))
- .collect(),
- ..Default::default()
- }
- }
+ use common_ingestion_warnings::UNKNOWN_ATTRIBUTION;
fn legacy_context(attribution: SdkAttribution) -> ProcessingContext {
ProcessingContext {
@@ -311,21 +191,6 @@ mod tests {
}
}
- #[test]
- fn first_event_supplies_attribution_for_the_whole_batch() {
- let events = vec![
- raw_event(json!({"$lib": "web", "$lib_version": "1.2.3"})),
- raw_event(json!({"$lib": "posthog-python", "$lib_version": "9.9.9"})),
- ];
- assert_eq!(
- SdkAttribution::from_first_event(&events),
- SdkAttribution {
- lib: Some("web".to_string()),
- lib_version: Some("1.2.3".to_string()),
- }
- );
- }
-
// Each of these is a payload capture accepts today, so each must produce a
// stampable context rather than a missing key. Oversized values are dropped
// rather than truncated, so they land on the same fallback.
@@ -392,7 +257,7 @@ mod tests {
for (label, events, expected_lib, expected_lib_version) in cases {
let attribution = SdkAttribution::from_first_event(&events);
- let ctx = legacy_request_context(&legacy_context(attribution));
+ let ctx = request_context(&legacy_context(attribution));
assert_eq!(ctx.lib, expected_lib, "{label}: lib");
assert_eq!(ctx.lib_version, expected_lib_version, "{label}: libVersion");
}
@@ -511,10 +376,7 @@ mod tests {
assert_eq!(emitted.len(), 1, "{error:?} event_count={event_count}");
let warning = &emitted[0];
assert_eq!(warning.token, "tok");
- assert_eq!(
- warning.source,
- common_ingestion_warnings::CAPTURE_LEGACY_ANALYTICS
- );
+ assert_eq!(warning.source, CAPTURE_LEGACY_ANALYTICS);
assert_eq!(warning.warning, expected_warning);
assert_eq!(warning.count, expected_count, "{error:?}");
assert_eq!(warning.extra_details.get("lib"), Some(&json!("web")));
diff --git a/rust/capture/src/ingestion_warnings/mod.rs b/rust/capture/src/ingestion_warnings/mod.rs
new file mode 100644
index 000000000000..0ab78fb8ea2b
--- /dev/null
+++ b/rust/capture/src/ingestion_warnings/mod.rs
@@ -0,0 +1,179 @@
+//! Capture's ingestion-warning conversion layer.
+//!
+//! Normalizing lives here rather than in `common_ingestion_warnings` so that
+//! crate never learns capture's event shapes: it takes concrete strings and
+//! stamps them.
+//!
+//! The split inside this directory is between two different jobs:
+//!
+//! * **Context projections** turn one pipeline's own request type into a
+//! [`WarningRequestContext`]. Every capture pipeline learns the client SDK
+//! differently, and the differences are permanent, not transitional, so a
+//! projection is inseparable from the types it reads. Those live *with their
+//! pipeline*: v1's is [`crate::v1::context::RequestContext::warning_context`],
+//! built from the `PostHog-Sdk-Info` header it requires. Legacy's is the
+//! exception below, because legacy has no subtree of its own: it is spread
+//! across `v0_endpoint`, `v0_request`, `events/`, and `payload/`.
+//! * **Emit helpers and type mappers** decide which warning a failure becomes
+//! and which details ride along. Every pipeline's details land in one
+//! customer-facing table, and a reader of that table cannot tell which
+//! pipeline served a request, so the payloads must not drift apart. Keeping
+//! them in sibling files here is what makes drift visible in review.
+//!
+//! This module itself holds only what more than one pipeline genuinely shares.
+
+pub mod ai;
+pub mod legacy;
+pub mod otel;
+
+use std::collections::HashSet;
+
+use common_ingestion_warnings::{
+ emit_request_warning, WarningEmitter, WarningRequestContext, WarningSource, WarningType,
+ UNKNOWN_ATTRIBUTION,
+};
+use common_types::{EventWithLibraryInfo, RawEvent};
+use serde_json::{json, Map};
+
+/// Max accepted length of a client-supplied `$lib` or `$lib_version`, matching
+/// the bound v1 puts on the `PostHog-Sdk-Info` header (real values are ~20
+/// bytes). Oversized values are treated as absent rather than truncated: they
+/// would otherwise ride into every warning payload for the batch and into the
+/// `Debug` output of [`crate::v0_request::ProcessingContext`], which the legacy
+/// path logs several times per request when chatty debug is on.
+pub const MAX_SDK_ATTRIBUTION_LEN: usize = 200;
+
+/// SDK identity as reported by a batch, for attribution only.
+///
+/// Both fields are unvalidated client input. Nothing routes on them.
+#[derive(Debug, Clone, Default, PartialEq, Eq)]
+pub struct SdkAttribution {
+ pub lib: Option<String>,
+ pub lib_version: Option<String>,
+}
+
+impl SdkAttribution {
+ /// Take attribution from the first event of a batch.
+ ///
+ /// One batch is one SDK in every real client: batching is a client-side
+ /// buffer flush, so events in it share a `$lib`. Scanning further to
+ /// reconcile disagreement would cost a pass over the batch on the hot path
+ /// to improve a field that is only ever displayed.
+ pub fn from_first_event(events: &[RawEvent]) -> Self {
+ let Some(info) = events.first().and_then(|e| e.extract_library_info()) else {
+ return Self::default();
+ };
+ Self {
+ lib: within_bound(info.name),
+ lib_version: info.version.and_then(within_bound),
+ }
+ }
+}
+
+/// Drop an attribution value longer than [`MAX_SDK_ATTRIBUTION_LEN`] so it lands
+/// on the unknown fallback instead of riding into every warning for the request.
+pub(crate) fn within_bound(value: String) -> Option<String> {
+ (value.len() <= MAX_SDK_ATTRIBUTION_LEN).then_some(value)
+}
+
+/// Bound a client-supplied value being copied into a warning's details.
+///
+/// Same budget and same reason as [`MAX_SDK_ATTRIBUTION_LEN`]: details ride into
+/// every warning message and land in a customer-visible table, and nothing
+/// downstream length-limits them, so an oversized event name or part name would
+/// inflate Kafka messages and warning storage.
+///
+/// Unlike attribution, these values name the thing the customer has to fix, so
+/// an oversized one is truncated rather than dropped. Truncation is marked, and
+/// respects char boundaries so a multi-byte name can't be cut mid-character.
+pub(crate) fn bounded_detail(value: &str) -> String {
+ if value.len() <= MAX_SDK_ATTRIBUTION_LEN {
+ return value.to_string();
+ }
+ let end = (0..=MAX_SDK_ATTRIBUTION_LEN)
+ .rev()
+ .find(|&i| value.is_char_boundary(i))
+ .unwrap_or(0);
+ format!("{}…", &value[..end])
+}
+
+/// Stamp [`UNKNOWN_ATTRIBUTION`] rather than dropping the key, so every warning
+/// has the same shape whether or not the client identified itself.
+pub(crate) fn unknown_if_missing(value: Option<&str>) -> String {
+ match value {
+ Some(v) if !v.trim().is_empty() => v.to_string(),
+ _ => UNKNOWN_ATTRIBUTION.to_string(),
+ }
+}
+
+/// Emit the `high_volume_distinct_id` warning for one batch's rate-limited
+/// events. Shared by the v1 and legacy rate limiter stages, which differ only in
+/// their [`WarningSource`] — the payload must not drift between them, since a
+/// reader of the v2 table can't tell which pipeline served a request.
+///
+/// `distinct_id` is included only when the batch had exactly one hot key; with
+/// several it would be an arbitrary pick, and `distinctIdCount` already says how
+/// many there were. The value needs no size bounding here: both pipelines drop
+/// oversized distinct_ids before the limiter runs.
+pub fn emit_rate_limit_warning(
+ emitter: Option<&dyn WarningEmitter>,
+ request: &WarningRequestContext,
+ source: WarningSource,
+ limited_distinct_ids: &HashSet<&str>,
+ limited_event_count: u64,
+) {
+ let mut details = Map::new();
+ details.insert(
+ "distinctIdCount".to_string(),
+ json!(limited_distinct_ids.len()),
+ );
+ if let [distinct_id] = limited_distinct_ids.iter().copied().collect::<Vec<_>>()[..] {
+ details.insert("distinctId".to_string(), json!(distinct_id));
+ }
+
+ emit_request_warning(
+ emitter,
+ request,
+ source,
+ WarningType::HighVolumeDistinctId,
+ details,
+ limited_event_count,
+ );
+}
+
+/// A `RawEvent` carrying only `properties`, for the attribution tests in this
+/// module and its children.
+#[cfg(test)]
+pub(crate) fn raw_event(properties: serde_json::Value) -> RawEvent {
+ RawEvent {
+ event: "$pageview".to_string(),
+ properties: properties
+ .as_object()
+ .expect("test properties must be an object")
+ .iter()
+ .map(|(k, v)| (k.clone(), v.clone()))
+ .collect(),
+ ..Default::default()
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::json;
+
+ #[test]
+ fn first_event_supplies_attribution_for_the_whole_batch() {
+ let events = vec![
+ raw_event(json!({"$lib": "web", "$lib_version": "1.2.3"})),
+ raw_event(json!({"$lib": "posthog-python", "$lib_version": "9.9.9"})),
+ ];
+ assert_eq!(
+ SdkAttribution::from_first_event(&events),
+ SdkAttribution {
+ lib: Some("web".to_string()),
+ lib_version: Some("1.2.3".to_string()),
+ }
+ );
+ }
+}
diff --git a/rust/capture/src/ingestion_warnings/otel.rs b/rust/capture/src/ingestion_warnings/otel.rs
new file mode 100644
index 000000000000..c1df7d5d2556
--- /dev/null
+++ b/rust/capture/src/ingestion_warnings/otel.rs
@@ -0,0 +1,340 @@
+//! Ingestion warnings for the OTLP trace endpoint (`/i/v0/ai/otel`).
+//!
+//! The endpoint's context projection lives with the OTEL code
+//! (`crate::otel::attribution`) because it destructures OTLP types; see this
+//! directory's module doc for the split.
+//!
+//! Unlike the analytics paths, every failure here happens after the token is
+//! known, so it is attributable. What isn't emitted is therefore a policy
+//! choice, not a limitation: quota and event-restriction rejections are
+//! surfaced through billing and ops channels, and sink or serialization
+//! failures are ours to fix.
+
+use common_ingestion_warnings::{
+ emit_request_warning, WarningEmitter, WarningRequestContext, WarningType, CAPTURE_AI_OTEL,
+};
+use serde_json::{json, Map};
+
+use crate::api::CaptureError;
+
+/// Which span cap a request tripped.
+///
+/// The raw cap bounds attribute-scanning cost before conversion; the AI cap
+/// bounds what we'll ingest after non-AI spans are filtered out. A customer
+/// over the raw cap has to batch smaller, one over the AI cap is sending too
+/// many AI spans at once, so the two need telling apart.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum SpanCapStage {
+ Raw,
+ Ai,
+}
+
+impl SpanCapStage {
+ fn as_str(self) -> &'static str {
+ match self {
+ Self::Raw => "raw",
+ Self::Ai => "ai",
+ }
+ }
+}
+
+/// Map an OTLP decode failure to the warning customers should see.
+///
+/// `parse_request` only ever returns the three variants matched below, but the
+/// match is exhaustive over `CaptureError` and has no catch-all so that a new
+/// failure mode there can't silently pick up the wrong warning here.
+pub fn warning_for_otel_parse_error(err: &CaptureError) -> Option<WarningType> {
+ match err {
+ // The gzip decompressor raises this when the decompressed body would
+ // exceed the endpoint's limit.
+ CaptureError::EventTooBig(_) => Some(WarningType::MessageSizeTooLarge),
+ // An unsupported content-encoding or content-type, a body that isn't
+ // valid protobuf or JSON, or JSON that isn't an OTLP trace payload.
+ CaptureError::RequestDecodingError(_) | CaptureError::RequestParsingError(_) => {
+ Some(WarningType::InvalidAiPayload)
+ }
+
+ // Reachable only if `parse_request` grows a new failure mode: decide
+ // warn-or-not there rather than defaulting to silence here.
+ CaptureError::RequestHydrationError(_)
+ | CaptureError::EmptyBatch
+ | CaptureError::EmptyPayload
+ | CaptureError::EmptyPayloadFiltered
+ | CaptureError::NoTokenError
+ | CaptureError::MultipleTokensError
+ | CaptureError::TokenValidationError(_)
+ | CaptureError::MissingEventName
+ | CaptureError::MissingDistinctId
+ | CaptureError::InvalidCookielessMode
+ | CaptureError::InvalidTimestamp
+ | CaptureError::MissingSnapshotData
+ | CaptureError::MissingSessionId
+ | CaptureError::MissingWindowId
+ | CaptureError::InvalidSessionId
+ | CaptureError::BillingLimit
+ | CaptureError::RateLimited
+ | CaptureError::GlobalRateLimitExceeded()
+ | CaptureError::RetryableSinkError
+ | CaptureError::NonRetryableSinkError
+ | CaptureError::ServiceUnavailable(_)
+ | CaptureError::BodyReadTimeout
+ | CaptureError::InternalError(_) => None,
+ }
+}
+
+/// Emit the warning for a request whose OTLP body could not be read.
+///
+/// `count = 1`: the span count is unknowable when the payload didn't parse, and
+/// a zero would read as "nothing happened" in the v2 table.
+///
+/// `format` is what the handler resolved the content-type to, and it is the
+/// detail that makes the warning actionable: `unknown` says the content-type
+/// itself was wrong, while a named format says the body didn't match the type
+/// the client claimed. The decode error's own message is deliberately left out;
+/// it can embed arbitrary payload bytes, and this lands in a customer-visible
+/// column.
+pub fn emit_otel_parse_warning(
+ emitter: Option<&dyn WarningEmitter>,
+ request: &WarningRequestContext,
+ err: &CaptureError,
+ format: &str,
+) {
+ let Some(warning) = warning_for_otel_parse_error(err) else {
+ return;
+ };
+ let mut details = Map::new();
+ details.insert("format".to_string(), json!(format));
+
+ emit_request_warning(emitter, request, CAPTURE_AI_OTEL, warning, details, 1);
+}
+
+/// Emit the warning for a request rejected for carrying too many spans.
+///
+/// `count` charges every span in the request: the cap check runs before any
+/// span is sent, so the whole payload was rejected.
+pub fn emit_span_cap_warning(
+ emitter: Option<&dyn WarningEmitter>,
+ request: &WarningRequestContext,
+ stage: SpanCapStage,
+ span_count: usize,
+ limit: usize,
+) {
+ let mut details = Map::new();
+ details.insert("stage".to_string(), json!(stage.as_str()));
+ details.insert("spanCount".to_string(), json!(span_count));
+ details.insert("limit".to_string(), json!(limit));
+
+ emit_request_warning(
+ emitter,
+ request,
+ CAPTURE_AI_OTEL,
+ WarningType::InvalidAiPayload,
+ details,
+ span_count as u64,
+ );
+}
+
+/// Emit the warning for an export whose spans all filtered out as non-AI.
+///
+/// This is the one warning here that accompanies a 200. The OTLP contract gives
+/// us no way to say "accepted, ingested nothing", so without this the customer
+/// sees success and no events, with nothing to correlate. Mixed batches are
+/// expected and are not warned about; only a request that produced no AI events
+/// at all is.
+///
+/// `count` charges the spans that were sent, since none of them landed.
+pub fn emit_no_ai_spans_warning(
+ emitter: Option<&dyn WarningEmitter>,
+ request: &WarningRequestContext,
+ raw_span_count: usize,
+) {
+ let mut details = Map::new();
+ details.insert("rawSpanCount".to_string(), json!(raw_span_count));
+
+ emit_request_warning(
+ emitter,
+ request,
+ CAPTURE_AI_OTEL,
+ WarningType::NoAiSpansIngested,
+ details,
+ raw_span_count as u64,
+ );
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use common_ingestion_warnings::test_support::CollectingEmitter;
+ use common_ingestion_warnings::UNKNOWN_ATTRIBUTION;
+ use rstest::rstest;
+
+ fn request() -> WarningRequestContext {
+ WarningRequestContext {
+ token: "tok".to_string(),
+ lib: "opentelemetry-js".to_string(),
+ lib_version: "2.0.0".to_string(),
+ path: "/i/v0/ai/otel".to_string(),
+ }
+ }
+
+ #[rstest]
+ #[case::oversize(
+ CaptureError::EventTooBig("too big".to_string()),
+ Some(WarningType::MessageSizeTooLarge)
+ )]
+ #[case::bad_content_type(
+ CaptureError::RequestDecodingError("Content-Type must be".to_string()),
+ Some(WarningType::InvalidAiPayload)
+ )]
+ #[case::bad_protobuf(
+ CaptureError::RequestParsingError("Invalid protobuf".to_string()),
+ Some(WarningType::InvalidAiPayload)
+ )]
+ // Ours to fix, or unreachable from parse_request; see the mapper's None arms.
+ #[case::internal(CaptureError::InternalError("boom".to_string()), None)]
+ #[case::sink(CaptureError::RetryableSinkError, None)]
+ #[case::billing(CaptureError::BillingLimit, None)]
+ fn parse_errors_map_only_to_payload_problems(
+ #[case] err: CaptureError,
+ #[case] expected: Option<WarningType>,
+ ) {
+ assert_eq!(warning_for_otel_parse_error(&err), expected);
+ }
+
+ // Same trust chain the legacy mapper pins: a type that is not
+ // capture-produced gets demoted to a generic client warning by the nodejs
+ // consumer, and one reachable by both routes breaks the common crate's
+ // one-route invariant. Both fail silently in production.
+ #[test]
+ fn emitted_warnings_are_trusted_and_single_routed() {
+ let emitter = CollectingEmitter::default();
+ emit_otel_parse_warning(
+ Some(&emitter),
+ &request(),
+ &CaptureError::RequestParsingError("bad".to_string()),
+ "protobuf",
+ );
+ emit_span_cap_warning(Some(&emitter), &request(), SpanCapStage::Raw, 1001, 1000);
+ emit_no_ai_spans_warning(Some(&emitter), &request(), 4);
+
+ let emitted = emitter.emitted();
+ assert_eq!(emitted.len(), 3);
+ for warning in emitted {
+ assert_eq!(warning.source, CAPTURE_AI_OTEL);
+ assert!(
+ warning.warning.capture_produced(),
+ "{:?} is not on the consumer trust allowlist",
+ warning.warning
+ );
+ assert!(
+ WarningType::from_tag(warning.warning.as_str()).is_none(),
+ "{:?} must not also be tag-routed",
+ warning.warning
+ );
+ }
+ }
+
+ #[test]
+ fn parse_warning_reports_the_resolved_format_not_the_error_message() {
+ let emitter = CollectingEmitter::default();
+ emit_otel_parse_warning(
+ Some(&emitter),
+ &request(),
+ &CaptureError::RequestParsingError("Invalid protobuf: buffer underflow".to_string()),
+ "unknown",
+ );
+
+ let emitted = emitter.emitted();
+ assert_eq!(emitted.len(), 1);
+ let warning = &emitted[0];
+ assert_eq!(warning.warning, WarningType::InvalidAiPayload);
+ assert_eq!(warning.count, 1);
+ assert_eq!(warning.extra_details.get("format"), Some(&json!("unknown")));
+ // The decode message can embed payload bytes, so it must never ride along.
+ assert!(!warning.extra_details.contains_key("message"));
+ assert!(!warning.extra_details.contains_key("reason"));
+ assert_eq!(warning.token, "tok");
+ assert_eq!(
+ warning.extra_details.get("lib"),
+ Some(&json!("opentelemetry-js"))
+ );
+ }
+
+ #[rstest]
+ #[case::raw(SpanCapStage::Raw, 1001, 1000, "raw")]
+ #[case::ai(SpanCapStage::Ai, 101, 100, "ai")]
+ fn span_cap_warning_charges_every_span_and_names_the_stage(
+ #[case] stage: SpanCapStage,
+ #[case] span_count: usize,
+ #[case] limit: usize,
+ #[case] expected_stage: &str,
+ ) {
+ let emitter = CollectingEmitter::default();
+ emit_span_cap_warning(Some(&emitter), &request(), stage, span_count, limit);
+
+ let emitted = emitter.emitted();
+ assert_eq!(emitted.len(), 1);
+ let warning = &emitted[0];
+ assert_eq!(warning.warning, WarningType::InvalidAiPayload);
+ assert_eq!(warning.count, span_count as u64);
+ assert_eq!(
+ warning.extra_details.get("stage"),
+ Some(&json!(expected_stage))
+ );
+ assert_eq!(
+ warning.extra_details.get("spanCount"),
+ Some(&json!(span_count))
+ );
+ assert_eq!(warning.extra_details.get("limit"), Some(&json!(limit)));
+ }
+
+ #[test]
+ fn no_ai_spans_warning_charges_the_spans_that_were_sent() {
+ let emitter = CollectingEmitter::default();
+ emit_no_ai_spans_warning(Some(&emitter), &request(), 7);
+
+ let emitted = emitter.emitted();
+ assert_eq!(emitted.len(), 1);
+ let warning = &emitted[0];
+ assert_eq!(warning.warning, WarningType::NoAiSpansIngested);
+ assert_eq!(warning.count, 7);
+ assert_eq!(warning.extra_details.get("rawSpanCount"), Some(&json!(7)));
+ }
+
+ #[test]
+ fn unknown_attribution_still_emits() {
+ let emitter = CollectingEmitter::default();
+ let unattributed = WarningRequestContext {
+ token: "tok".to_string(),
+ lib: UNKNOWN_ATTRIBUTION.to_string(),
+ lib_version: UNKNOWN_ATTRIBUTION.to_string(),
+ path: "/i/v0/ai/otel".to_string(),
+ };
+
+ emit_otel_parse_warning(
+ Some(&emitter),
+ &unattributed,
+ &CaptureError::RequestDecodingError("nope".to_string()),
+ "unknown",
+ );
+
+ let emitted = emitter.emitted();
+ assert_eq!(emitted.len(), 1);
+ assert_eq!(
+ emitted[0].extra_details.get("lib"),
+ Some(&json!(UNKNOWN_ATTRIBUTION))
+ );
+ }
+
+ #[test]
+ fn no_emitter_is_a_silent_no_op() {
+ emit_otel_parse_warning(
+ None,
+ &request(),
+ &CaptureError::RequestParsingError("bad".to_string()),
+ "json",
+ );
+ emit_span_cap_warning(None, &request(), SpanCapStage::Ai, 101, 100);
+ emit_no_ai_spans_warning(None, &request(), 3);
+ }
+}
diff --git a/rust/capture/src/lib.rs b/rust/capture/src/lib.rs
index 2133f5957fe9..53102fd2deff 100644
--- a/rust/capture/src/lib.rs
+++ b/rust/capture/src/lib.rs
@@ -1,4 +1,5 @@
pub mod ai_endpoint;
+pub mod ai_rejection;
pub mod ai_s3;
pub mod api;
pub mod config;
diff --git a/rust/capture/src/otel/attribution.rs b/rust/capture/src/otel/attribution.rs
new file mode 100644
index 000000000000..79cb26a1adb3
--- /dev/null
+++ b/rust/capture/src/otel/attribution.rs
@@ -0,0 +1,194 @@
+//! SDK attribution for OTLP requests, for ingestion warnings.
+//!
+//! Lives here rather than in `ingestion_warnings` because it destructures OTLP
+//! types; see that module's doc for the projection-vs-emit-helper split.
+
+use common_ingestion_warnings::WarningRequestContext;
+use opentelemetry_proto::tonic::collector::trace::v1::ExportTraceServiceRequest;
+use opentelemetry_proto::tonic::common::v1::any_value;
+
+use crate::ingestion_warnings::{unknown_if_missing, within_bound};
+
+/// The OTLP analogue of `$lib`/`$lib_version`: semantic-convention resource
+/// attributes every OTEL SDK sets about itself.
+///
+/// `fan_out` strips the whole `telemetry.` prefix from event properties as
+/// auto-detected noise, which is right for properties and irrelevant here —
+/// these are read off the raw request, and only ever to say which exporter
+/// produced a bad payload.
+const SDK_NAME_ATTR: &str = "telemetry.sdk.name";
+const SDK_VERSION_ATTR: &str = "telemetry.sdk.version";
+
+/// Warning attribution for an OTLP request.
+///
+/// `request` is `None` when the body never parsed, which is exactly when a
+/// warning is most likely: attribution then falls back to unknown, since the
+/// SDK identity lives inside the payload we couldn't read.
+pub(super) fn otel_request_context(
+ token: &str,
+ path: &str,
+ request: Option<&ExportTraceServiceRequest>,
+) -> WarningRequestContext {
+ let (lib, lib_version) = request.map(sdk_attribution).unwrap_or_default();
+ WarningRequestContext {
+ token: token.to_string(),
+ lib: unknown_if_missing(lib.as_deref()),
+ lib_version: unknown_if_missing(lib_version.as_deref()),
+ path: path.to_string(),
+ }
+}
+
+/// Read the SDK name and version off the first resource that declares either.
+///
+/// A single export can carry several resources, but attribution only needs to
+/// name the exporter, and one process is one SDK. Non-string values are ignored
+/// rather than rendered: the semantic convention defines both as strings, so a
+/// number here is a broken exporter, not a value worth displaying.
+fn sdk_attribution(request: &ExportTraceServiceRequest) -> (Option<String>, Option<String>) {
+ for resource_spans in &request.resource_spans {
+ let Some(resource) = resource_spans.resource.as_ref() else {
+ continue;
+ };
+
+ let mut name = None;
+ let mut version = None;
+ for kv in &resource.attributes {
+ let Some(any_value::Value::StringValue(value)) =
+ kv.value.as_ref().and_then(|v| v.value.as_ref())
+ else {
+ continue;
+ };
+ match kv.key.as_str() {
+ SDK_NAME_ATTR => name = within_bound(value.clone()),
+ SDK_VERSION_ATTR => version = within_bound(value.clone()),
+ _ => {}
+ }
+ }
+
+ if name.is_some() || version.is_some() {
+ return (name, version);
+ }
+ }
+ (None, None)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use common_ingestion_warnings::UNKNOWN_ATTRIBUTION;
+ use opentelemetry_proto::tonic::common::v1::{AnyValue, KeyValue};
+ use opentelemetry_proto::tonic::resource::v1::Resource;
+ use opentelemetry_proto::tonic::trace::v1::ResourceSpans;
+
+ use crate::ingestion_warnings::MAX_SDK_ATTRIBUTION_LEN;
+
+ fn string_attr(key: &str, value: &str) -> KeyValue {
+ KeyValue {
+ key: key.to_string(),
+ value: Some(AnyValue {
+ value: Some(any_value::Value::StringValue(value.to_string())),
+ }),
+ }
+ }
+
+ fn int_attr(key: &str, value: i64) -> KeyValue {
+ KeyValue {
+ key: key.to_string(),
+ value: Some(AnyValue {
+ value: Some(any_value::Value::IntValue(value)),
+ }),
+ }
+ }
+
+ fn request_with(resources: Vec<Option<Vec<KeyValue>>>) -> ExportTraceServiceRequest {
+ ExportTraceServiceRequest {
+ resource_spans: resources
+ .into_iter()
+ .map(|attributes| ResourceSpans {
+ resource: attributes.map(|attributes| Resource {
+ attributes,
+ ..Default::default()
+ }),
+ ..Default::default()
+ })
+ .collect(),
+ }
+ }
+
+ // Every case here is a payload an exporter can actually send, so each must
+ // produce a stampable context rather than a missing key.
+ #[test]
+ fn sdk_attribution_falls_back_to_unknown_when_unusable() {
+ let over_bound = "w".repeat(MAX_SDK_ATTRIBUTION_LEN + 1);
+ let cases = [
+ (
+ "unparsed body",
+ None,
+ UNKNOWN_ATTRIBUTION,
+ UNKNOWN_ATTRIBUTION,
+ ),
+ (
+ "no resource",
+ Some(request_with(vec![None])),
+ UNKNOWN_ATTRIBUTION,
+ UNKNOWN_ATTRIBUTION,
+ ),
+ (
+ "no telemetry attrs",
+ Some(request_with(vec![Some(vec![string_attr(
+ "service.name",
+ "checkout",
+ )])])),
+ UNKNOWN_ATTRIBUTION,
+ UNKNOWN_ATTRIBUTION,
+ ),
+ (
+ "name without version",
+ Some(request_with(vec![Some(vec![string_attr(
+ SDK_NAME_ATTR,
+ "opentelemetry",
+ )])])),
+ "opentelemetry",
+ UNKNOWN_ATTRIBUTION,
+ ),
+ (
+ "non-string name",
+ Some(request_with(vec![Some(vec![
+ int_attr(SDK_NAME_ATTR, 42),
+ string_attr(SDK_VERSION_ATTR, "1.2.3"),
+ ])])),
+ UNKNOWN_ATTRIBUTION,
+ "1.2.3",
+ ),
+ (
+ "oversized name",
+ Some(request_with(vec![Some(vec![
+ string_attr(SDK_NAME_ATTR, &over_bound),
+ string_attr(SDK_VERSION_ATTR, "1.2.3"),
+ ])])),
+ UNKNOWN_ATTRIBUTION,
+ "1.2.3",
+ ),
+ (
+ "first resource without attrs is skipped",
+ Some(request_with(vec![
+ Some(vec![string_attr("service.name", "checkout")]),
+ Some(vec![
+ string_attr(SDK_NAME_ATTR, "opentelemetry-js"),
+ string_attr(SDK_VERSION_ATTR, "2.0.0"),
+ ]),
+ ])),
+ "opentelemetry-js",
+ "2.0.0",
+ ),
+ ];
+
+ for (label, request, expected_lib, expected_version) in cases {
+ let ctx = otel_request_context("tok", "/i/v0/ai/otel", request.as_ref());
+ assert_eq!(ctx.token, "tok", "{label}: token");
+ assert_eq!(ctx.path, "/i/v0/ai/otel", "{label}: path");
+ assert_eq!(ctx.lib, expected_lib, "{label}: lib");
+ assert_eq!(ctx.lib_version, expected_version, "{label}: libVersion");
+ }
+ }
+}
diff --git a/rust/capture/src/otel/mod.rs b/rust/capture/src/otel/mod.rs
index daa2b9066537..52a5b31ee269 100644
--- a/rust/capture/src/otel/mod.rs
+++ b/rust/capture/src/otel/mod.rs
@@ -1,3 +1,4 @@
+mod attribution;
mod error_status;
mod fan_out;
mod filtering;
@@ -19,12 +20,21 @@ use tracing::{debug, instrument, warn, Span};
use crate::api::{CaptureError, CaptureResponse, CaptureResponseCode};
use crate::events::overflow_stamping::stamp_overflow_reason;
use crate::extractors::extract_body_with_timeout;
+use crate::ingestion_warnings::otel::{
+ emit_no_ai_spans_warning, emit_otel_parse_warning, emit_span_cap_warning, SpanCapStage,
+};
use crate::prometheus::{report_dropped_events, report_internal_error_metrics};
use crate::router::State as AppState;
use crate::token::validate_token;
+use self::attribution::otel_request_context;
+
pub const OTEL_BODY_SIZE: usize = 4 * 1024 * 1024; // 4MB
+/// Route this handler serves. Stamped onto warnings so a reader of the v2 table
+/// can tell which endpoint produced them.
+const OTEL_PATH: &str = "/i/v0/ai/otel";
+
/// Maximum AI spans accepted after filtering. SDKs receive a 400 (non-retryable)
/// if this is exceeded, so callers must batch sensibly.
const MAX_SPANS_PER_REQUEST: usize = 100;
@@ -65,7 +75,7 @@ pub async fn otel_handler(
OTEL_BODY_SIZE,
state.body_chunk_read_timeout,
state.body_read_chunk_size_kb,
- "/i/v0/ai/otel",
+ OTEL_PATH,
)
.await
.map_err(|e| {
@@ -121,6 +131,14 @@ pub async fn otel_handler(
let request = ingestion::parse_request(&body, &headers, OTEL_BODY_SIZE).map_err(|e| {
report_internal_error_metrics(e.to_metric_tag(), "otel_parsing");
+ // No parsed request to attribute from: the SDK identity lives inside the
+ // body we couldn't read.
+ emit_otel_parse_warning(
+ state.ingestion_warning_emitter.as_deref(),
+ &otel_request_context(token, OTEL_PATH, None),
+ &e,
+ format,
+ );
e.into_response()
})?;
@@ -139,6 +157,13 @@ pub async fn otel_handler(
"Too many spans: {raw_span_count} exceeds limit of {MAX_RAW_SPANS_PER_REQUEST}"
));
report_internal_error_metrics(err.to_metric_tag(), "otel_validation");
+ emit_span_cap_warning(
+ state.ingestion_warning_emitter.as_deref(),
+ &otel_request_context(token, OTEL_PATH, Some(&request)),
+ SpanCapStage::Raw,
+ raw_span_count,
+ MAX_RAW_SPANS_PER_REQUEST,
+ );
return Err(err.into_response());
}
@@ -155,6 +180,15 @@ pub async fn otel_handler(
}
if span_count == 0 {
+ // Reached only with raw_span_count > 0 (the zero-span export returned
+ // above), so the customer sent spans and none of them landed. The OTLP
+ // contract has no way to say that in the response, which is why this
+ // 200 gets a warning and the mixed-batch case above does not.
+ emit_no_ai_spans_warning(
+ state.ingestion_warning_emitter.as_deref(),
+ &otel_request_context(token, OTEL_PATH, Some(&request)),
+ raw_span_count,
+ );
counter!("capture_ai_otel_requests_success").increment(1);
return Ok(Json(json!({})));
}
@@ -163,6 +197,13 @@ pub async fn otel_handler(
"Too many AI spans: {span_count} exceeds limit of {MAX_SPANS_PER_REQUEST}"
));
report_internal_error_metrics(err.to_metric_tag(), "otel_validation");
+ emit_span_cap_warning(
+ state.ingestion_warning_emitter.as_deref(),
+ &otel_request_context(token, OTEL_PATH, Some(&request)),
+ SpanCapStage::Ai,
+ span_count,
+ MAX_SPANS_PER_REQUEST,
+ );
return Err(err.into_response());
}
diff --git a/rust/capture/src/v1/analytics/process.rs b/rust/capture/src/v1/analytics/process.rs
index 9a314c72cd0e..e76da6fd16c6 100644
--- a/rust/capture/src/v1/analytics/process.rs
+++ b/rust/capture/src/v1/analytics/process.rs
@@ -24,7 +24,7 @@ use limiters::overflow::{OverflowLimiter, OverflowLimiterResult};
use tracing::Level;
use super::context::Context;
-use crate::ingestion_warnings::{emit_rate_limit_warning, v1_request_context};
+use crate::ingestion_warnings::emit_rate_limit_warning;
use crate::router;
use crate::v1::context::RequestContext;
use crate::v1::sinks::event::Event as SinkEvent;
@@ -348,7 +348,7 @@ fn emit_batch_abort_warning(
// one occurrence, so never charge a count of zero.
emit_request_warning(
state.ingestion_warning_emitter.as_deref(),
- &v1_request_context(context),
+ &context.warning_context(),
CAPTURE_V1_ANALYTICS,
warning,
serde_json::Map::new(),
@@ -392,7 +392,7 @@ fn emit_validation_drop_warnings(
}
}
- let request = v1_request_context(context);
+ let request = context.warning_context();
for (warning, (count, single_event)) in grouped {
let mut details = serde_json::Map::new();
if let Some((distinct_id, uuid)) = single_event {
@@ -920,7 +920,7 @@ async fn apply_token_distinct_id_limits(
emit_rate_limit_warning(
emitter,
- &v1_request_context(context),
+ &context.warning_context(),
CAPTURE_V1_RATE_LIMIT,
&limited_distinct_ids,
limited_event_count,
diff --git a/rust/capture/src/v1/context.rs b/rust/capture/src/v1/context.rs
index 9777885cb2e1..3644c4c9baec 100644
--- a/rust/capture/src/v1/context.rs
+++ b/rust/capture/src/v1/context.rs
@@ -3,6 +3,7 @@ use std::net::IpAddr;
use axum::http::{header, HeaderMap, Method};
use axum_client_ip::InsecureClientIp;
use chrono::{DateTime, Utc};
+use common_ingestion_warnings::{WarningRequestContext, UNKNOWN_ATTRIBUTION};
use uuid::Uuid;
use crate::token::validate_token;
@@ -67,6 +68,24 @@ impl RequestContext {
Some((lib, version))
}
+ /// Attribution stamped onto every ingestion warning this request produces.
+ ///
+ /// [`Self::sdk_lib_and_version`] is all-or-nothing — the header is a single
+ /// `name/version` string — so both fields fall back together. Unlike the
+ /// injection callers, a warning always needs both keys present, so this
+ /// stamps the unknown placeholder rather than skipping them.
+ pub fn warning_context(&self) -> WarningRequestContext {
+ let (lib, lib_version) = self
+ .sdk_lib_and_version()
+ .unwrap_or((UNKNOWN_ATTRIBUTION, UNKNOWN_ATTRIBUTION));
+ WarningRequestContext {
+ token: self.api_token.clone(),
+ lib: lib.to_string(),
+ lib_version: lib_version.to_string(),
+ path: self.path.to_string(),
+ }
+ }
+
pub fn new(
headers: &HeaderMap,
ip: &InsecureClientIp,
diff --git a/rust/capture/tests/integration_ai_endpoint.rs b/rust/capture/tests/integration_ai_endpoint.rs
index 4fe2196299e0..5858b70d550c 100644
--- a/rust/capture/tests/integration_ai_endpoint.rs
+++ b/rust/capture/tests/integration_ai_endpoint.rs
@@ -14,6 +14,8 @@ use capture::sinks::Event;
use capture::time::TimeSource;
use capture::v0_request::{OverflowReason, ProcessedEvent};
use chrono::{DateTime, TimeZone, Utc};
+use common_ingestion_warnings::test_support::CollectingEmitter;
+use common_ingestion_warnings::{WarningEmitter, WarningType, CAPTURE_AI_EVENTS};
use common_redis::MockRedisClient;
use futures::StreamExt;
use integration_utils::{test_lifecycle_handlers, DEFAULT_CONFIG, DEFAULT_TEST_TIME};
@@ -203,6 +205,65 @@ fn setup_ai_test_router() -> Router {
)
}
+/// A router whose emit sites are live, plus the emitter to assert against.
+/// Mirrors `setup_ai_test_router` and differs only in the last argument.
+fn setup_ai_router_collecting_warnings() -> (Router, Arc<CollectingEmitter>) {
+ let (readiness, liveness, _monitor) = test_lifecycle_handlers();
+
+ let timesource = FixedTime {
+ time: DateTime::parse_from_rfc3339(DEFAULT_TEST_TIME)
+ .expect("Invalid fixed time format")
+ .with_timezone(&Utc),
+ };
+ let redis = Arc::new(MockRedisClient::new());
+
+ let mut cfg = DEFAULT_CONFIG.clone();
+ cfg.capture_mode = CaptureMode::Events;
+
+ let quota_limiter =
+ CaptureQuotaLimiter::new(&cfg, redis.clone(), Duration::from_secs(60 * 60 * 24 * 7));
+
+ let emitter = Arc::new(CollectingEmitter::default());
+ let warning_emitter: Option<Arc<dyn WarningEmitter>> = Some(emitter.clone());
+
+ let app = router(
+ timesource,
+ readiness,
+ liveness,
+ Arc::new(TestSink),
+ redis,
+ None,
+ quota_limiter,
+ TokenDropper::default(),
+ None, // event_restriction_service
+ None, // recorder_handle
+ CaptureMode::Events,
+ None,
+ 25 * 1024 * 1024,
+ false,
+ 1_i64,
+ false,
+ 0.0_f32,
+ 26_214_400,
+ Some(create_mock_blob_storage()),
+ None,
+ 256,
+ 10 * 1024 * 1024,
+ 50 * 1024 * 1024,
+ None,
+ None,
+ None,
+ None,
+ 8,
+ None,
+ AiRouting::Primary,
+ false,
+ warning_emitter,
+ );
+
+ (app, emitter)
+}
+
// ============================================================================
// PHASE 1: HTTP ENDPOINT
// ============================================================================
@@ -3277,3 +3338,131 @@ async fn test_ai_endpoint_verified_gateway_event_still_subject_to_global_quota()
"verified gateway event must still obey the global Events quota"
);
}
+
+// ============================================================================
+// PHASE 11: INGESTION WARNINGS
+// ============================================================================
+//
+// The mapping, details, and count are pinned at the helper level in
+// `ingestion_warnings::ai`. These cover what a unit test can't: that the emit
+// seam is wired into the handler at all, that attribution reaches it from the
+// event part, and that a rejection still produces its original HTTP response.
+
+#[tokio::test]
+async fn non_ai_event_name_warns_and_still_returns_400() {
+ let (app, emitter) = setup_ai_router_collecting_warnings();
+ let client = TestClient::new(app);
+
+ // Analytics sent to the AI path: the mistake invalid_ai_event exists for.
+ let form = Form::new().part(
+ "event",
+ Part::bytes(
+ serde_json::to_vec(&json!({
+ "uuid": uuid::Uuid::now_v7().to_string(),
+ "event": "$pageview",
+ "distinct_id": "user-1",
+ "properties": {"$ai_model": "gpt-4", "$lib": "posthog-python", "$lib_version": "3.1.0"}
+ }))
+ .unwrap(),
+ )
+ .mime_str("application/json")
+ .unwrap(),
+ );
+
+ let resp = send_multipart_request(&client, form, Some("test_token")).await;
+ assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
+
+ let emitted = emitter.emitted();
+ assert_eq!(emitted.len(), 1);
+ assert_eq!(emitted[0].warning, WarningType::InvalidAiEvent);
+ assert_eq!(emitted[0].source, CAPTURE_AI_EVENTS);
+ assert_eq!(emitted[0].token, "test_token");
+ assert_eq!(emitted[0].count, 1);
+ assert_eq!(
+ emitted[0].extra_details.get("eventName"),
+ Some(&json!("$pageview"))
+ );
+ // Attribution came off the event part's own properties.
+ assert_eq!(
+ emitted[0].extra_details.get("lib"),
+ Some(&json!("posthog-python"))
+ );
+ assert_eq!(
+ emitted[0].extra_details.get("libVersion"),
+ Some(&json!("3.1.0"))
+ );
+ assert_eq!(
+ emitted[0].extra_details.get("path"),
+ Some(&json!("/i/v0/ai"))
+ );
+}
+
+#[tokio::test]
+async fn missing_ai_model_warns_as_invalid_ai_event() {
+ let (app, emitter) = setup_ai_router_collecting_warnings();
+ let client = TestClient::new(app);
+
+ let form = create_ai_event_form("$ai_generation", "user-2", json!({"foo": "bar"}));
+ let resp = send_multipart_request(&client, form, Some("test_token")).await;
+ assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
+
+ let emitted = emitter.emitted();
+ assert_eq!(emitted.len(), 1);
+ assert_eq!(emitted[0].warning, WarningType::InvalidAiEvent);
+ // No $lib in the properties, so attribution falls back rather than dropping keys.
+ assert_eq!(emitted[0].extra_details.get("lib"), Some(&json!("unknown")));
+}
+
+// Structural failures happen before the event part parses, so this also covers
+// the pre-event-part attribution fallback on the seam.
+#[tokio::test]
+async fn unknown_multipart_field_warns_as_invalid_ai_payload() {
+ let (app, emitter) = setup_ai_router_collecting_warnings();
+ let client = TestClient::new(app);
+
+ let form = create_ai_event_form("$ai_generation", "user-3", json!({"$ai_model": "gpt-4"}))
+ .part(
+ "surprise",
+ Part::bytes(b"data".to_vec())
+ .mime_str("application/json")
+ .unwrap(),
+ );
+
+ let resp = send_multipart_request(&client, form, Some("test_token")).await;
+ assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
+
+ let emitted = emitter.emitted();
+ assert_eq!(emitted.len(), 1);
+ assert_eq!(emitted[0].warning, WarningType::InvalidAiPayload);
+ assert_eq!(
+ emitted[0].extra_details.get("part"),
+ Some(&json!("surprise"))
+ );
+}
+
+// A missing Bearer header is pre-token, so there is no team to attribute to and
+// the seam must stay silent. This is the property that keeps unattributable
+// failures out of the warnings table.
+#[tokio::test]
+async fn unauthenticated_request_never_warns() {
+ let (app, emitter) = setup_ai_router_collecting_warnings();
+ let client = TestClient::new(app);
+
+ let form = create_ai_event_form("$ai_generation", "user-4", json!({"$ai_model": "gpt-4"}));
+ let resp = send_multipart_request(&client, form, None).await;
+
+ assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
+ assert!(emitter.emitted().is_empty());
+}
+
+#[tokio::test]
+async fn valid_ai_event_never_warns() {
+ let (app, emitter) = setup_ai_router_collecting_warnings();
+ let client = TestClient::new(app);
+
+ let form = create_ai_event_form("$ai_generation", "user-5", json!({"$ai_model": "gpt-4"}));
+ let resp = send_multipart_request(&client, form, Some("test_token")).await;
+
+ assert_eq!(resp.status(), StatusCode::OK);
+ assert!(emitter.emitted().is_empty());
+}
diff --git a/rust/capture/tests/integration_otel_endpoint.rs b/rust/capture/tests/integration_otel_endpoint.rs
index c70f0c9f2428..8e7c03d03597 100644
--- a/rust/capture/tests/integration_otel_endpoint.rs
+++ b/rust/capture/tests/integration_otel_endpoint.rs
@@ -16,6 +16,8 @@ use capture::sinks::Event;
use capture::time::TimeSource;
use capture::v0_request::{DataType, OverflowReason, ProcessedEvent};
use chrono::{DateTime, Utc};
+use common_ingestion_warnings::test_support::CollectingEmitter;
+use common_ingestion_warnings::{WarningEmitter, WarningType, CAPTURE_AI_OTEL};
use common_redis::MockRedisClient;
use integration_utils::{test_lifecycle_handlers, DEFAULT_TEST_TIME};
use limiters::overflow::OverflowLimiter;
@@ -128,6 +130,10 @@ struct TestClientOptions {
// configs without `OVERFLOW_ENABLED=true` and exercises the no-op branch
// of `stamp_overflow_reason`.
overflow_limiter: Option<Arc<OverflowLimiter>>,
+ // Opt-in warnings emitter. `None` (default) matches deploys without
+ // `CAPTURE_INGESTION_WARNINGS_ENABLED` and exercises the no-op branch of
+ // every emit site.
+ ingestion_warning_emitter: Option<Arc<dyn WarningEmitter>>,
}
fn make_test_client(sink: &CapturingSink) -> TestClient {
@@ -189,12 +195,27 @@ fn make_test_client_with_options(sink: &CapturingSink, options: TestClientOption
None, // ai_gateway_signing_secret
AiRouting::Primary, // ai_routing
false, // ai_events_overflow_enabled
- None, // ingestion_warning_emitter
+ options.ingestion_warning_emitter, // ingestion_warning_emitter
);
TestClient::new(app)
}
+/// A client whose emit sites are live, plus the emitter to assert against.
+fn make_test_client_collecting_warnings(
+ sink: &CapturingSink,
+) -> (TestClient, Arc<CollectingEmitter>) {
+ let emitter = Arc::new(CollectingEmitter::default());
+ let client = make_test_client_with_options(
+ sink,
+ TestClientOptions {
+ ingestion_warning_emitter: Some(emitter.clone()),
+ ..Default::default()
+ },
+ );
+ (client, emitter)
+}
+
const ENDPOINT: &str = "/i/v0/ai/otel";
async fn send_request(sink: &CapturingSink, request: &ExportTraceServiceRequest) -> u16 {
@@ -612,6 +633,182 @@ async fn test_mixed_requests_only_emit_relevant_ai_spans() {
assert_eq!(events[0].event.event, "$ai_generation");
}
+// The warning is the only feedback channel for this outcome: the OTLP contract
+// has no way to say "accepted, ingested nothing", so the exporter sees a 200.
+// Also proves the emit site is wired and that SDK attribution survives the trip
+// from resource attributes into the warning, neither of which a unit test on the
+// helper can catch.
+#[tokio::test]
+async fn all_spans_filtered_warns_and_still_returns_200() {
+ let sink = CapturingSink::new();
+ let (client, emitter) = make_test_client_collecting_warnings(&sink);
+ let request = ExportTraceServiceRequest {
+ resource_spans: vec![ResourceSpans {
+ resource: Some(Resource {
+ attributes: vec![
+ make_kv(
+ "telemetry.sdk.name",
+ any_value::Value::StringValue("opentelemetry-js".to_string()),
+ ),
+ make_kv(
+ "telemetry.sdk.version",
+ any_value::Value::StringValue("2.0.0".to_string()),
+ ),
+ ],
+ dropped_attributes_count: 0,
+ }),
+ scope_spans: vec![ScopeSpans {
+ scope: None,
+ spans: vec![
+ make_irrelevant_http_span(vec![9; 16], vec![8; 8]),
+ make_irrelevant_http_span(vec![9; 16], vec![7; 8]),
+ ],
+ schema_url: String::new(),
+ }],
+ schema_url: String::new(),
+ }],
+ };
+
+ let status = send_request_with_client(&client, &request).await;
+ assert_eq!(status, 200);
+ assert!(sink.get_events().await.is_empty());
+
+ let emitted = emitter.emitted();
+ assert_eq!(emitted.len(), 1);
+ assert_eq!(emitted[0].warning, WarningType::NoAiSpansIngested);
+ assert_eq!(emitted[0].source, CAPTURE_AI_OTEL);
+ assert_eq!(emitted[0].token, TOKEN);
+ assert_eq!(emitted[0].count, 2);
+ assert_eq!(
+ emitted[0].extra_details.get("rawSpanCount"),
+ Some(&json!(2))
+ );
+ assert_eq!(
+ emitted[0].extra_details.get("lib"),
+ Some(&json!("opentelemetry-js"))
+ );
+ assert_eq!(
+ emitted[0].extra_details.get("libVersion"),
+ Some(&json!("2.0.0"))
+ );
+ assert_eq!(
+ emitted[0].extra_details.get("path"),
+ Some(&json!("/i/v0/ai/otel"))
+ );
+}
+
+// Mixed batches are documented-expected (a framework exporting HTTP and AI spans
+// together), so warning on them would fire on correct usage. Pins that choice
+// against a future refactor that starts warning whenever anything is filtered.
+#[tokio::test]
+async fn mixed_batch_ingests_ai_spans_without_warning() {
+ let sink = CapturingSink::new();
+ let (client, emitter) = make_test_client_collecting_warnings(&sink);
+ let request = ExportTraceServiceRequest {
+ resource_spans: vec![ResourceSpans {
+ resource: None,
+ scope_spans: vec![ScopeSpans {
+ scope: None,
+ spans: vec![
+ make_irrelevant_http_span(vec![3; 16], vec![1; 8]),
+ make_span(
+ vec![3; 16],
+ vec![2; 8],
+ vec![],
+ 1_704_067_200_000_000_000,
+ vec![make_kv(
+ "gen_ai.operation.name",
+ any_value::Value::StringValue("chat".to_string()),
+ )],
+ ),
+ ],
+ schema_url: String::new(),
+ }],
+ schema_url: String::new(),
+ }],
+ };
+
+ let status = send_request_with_client(&client, &request).await;
+ assert_eq!(status, 200);
+ assert_eq!(sink.get_events().await.len(), 1);
+ assert!(emitter.emitted().is_empty());
+}
+
+#[tokio::test]
+async fn too_many_ai_spans_warns_with_the_ai_stage() {
+ let sink = CapturingSink::new();
+ let (client, emitter) = make_test_client_collecting_warnings(&sink);
+ let over_cap = 101;
+ let spans = (0..over_cap)
+ .map(|i| {
+ make_span(
+ vec![4; 16],
+ vec![i as u8; 8],
+ vec![],
+ 1_704_067_200_000_000_000,
+ vec![make_kv(
+ "gen_ai.operation.name",
+ any_value::Value::StringValue("chat".to_string()),
+ )],
+ )
+ })
+ .collect();
+ let request = ExportTraceServiceRequest {
+ resource_spans: vec![ResourceSpans {
+ resource: None,
+ scope_spans: vec![ScopeSpans {
+ scope: None,
+ spans,
+ schema_url: String::new(),
+ }],
+ schema_url: String::new(),
+ }],
+ };
+
+ let status = send_request_with_client(&client, &request).await;
+ assert_eq!(status, 400);
+ assert!(sink.get_events().await.is_empty());
+
+ let emitted = emitter.emitted();
+ assert_eq!(emitted.len(), 1);
+ assert_eq!(emitted[0].warning, WarningType::InvalidAiPayload);
+ assert_eq!(emitted[0].count, over_cap as u64);
+ assert_eq!(emitted[0].extra_details.get("stage"), Some(&json!("ai")));
+ assert_eq!(
+ emitted[0].extra_details.get("spanCount"),
+ Some(&json!(over_cap))
+ );
+ assert_eq!(emitted[0].extra_details.get("limit"), Some(&json!(100)));
+}
+
+// Attribution has to fall back to unknown here: the SDK identity lives inside
+// the body that failed to parse.
+#[tokio::test]
+async fn unparseable_body_warns_with_unknown_attribution() {
+ let sink = CapturingSink::new();
+ let (client, emitter) = make_test_client_collecting_warnings(&sink);
+
+ let resp = client
+ .post(ENDPOINT)
+ .header("Content-Type", "application/x-protobuf")
+ .header("Authorization", format!("Bearer {}", TOKEN))
+ .body(vec![0xff, 0xff, 0xff, 0xff])
+ .send()
+ .await;
+
+ assert_eq!(resp.status().as_u16(), 400);
+
+ let emitted = emitter.emitted();
+ assert_eq!(emitted.len(), 1);
+ assert_eq!(emitted[0].warning, WarningType::InvalidAiPayload);
+ assert_eq!(emitted[0].count, 1);
+ assert_eq!(
+ emitted[0].extra_details.get("format"),
+ Some(&json!("protobuf"))
+ );
+ assert_eq!(emitted[0].extra_details.get("lib"), Some(&json!("unknown")));
+}
+
#[tokio::test]
async fn test_empty_body_returns_400() {
let sink = CapturingSink::new();
diff --git a/rust/common/ingestion_warnings/src/lib.rs b/rust/common/ingestion_warnings/src/lib.rs
index f75e3852987d..3d6642390514 100644
--- a/rust/common/ingestion_warnings/src/lib.rs
+++ b/rust/common/ingestion_warnings/src/lib.rs
@@ -165,6 +165,25 @@ pub const CAPTURE_LEGACY_ANALYTICS: WarningSource = WarningSource {
pipeline_step: "capture_validation",
};
+/// Capture's AI events endpoint (`rust/capture/src/ai_endpoint.rs`, `/i/v0/ai`).
+/// One multipart event per request, so warnings from this source always carry
+/// `count = 1`.
+pub const CAPTURE_AI_EVENTS: WarningSource = WarningSource {
+ service: serializer::SOURCE_CAPTURE,
+ path: "ai_events",
+ pipeline_step: "capture_validation",
+};
+
+/// Capture's OTLP trace endpoint (`rust/capture/src/otel`, `/i/v0/ai/otel`).
+/// Split from `CAPTURE_AI_EVENTS` by `path` because the two AI endpoints take
+/// unrelated payload formats and fail for unrelated reasons, so a spike in one
+/// says nothing about the other.
+pub const CAPTURE_AI_OTEL: WarningSource = WarningSource {
+ service: serializer::SOURCE_CAPTURE,
+ path: "ai_otel",
+ pipeline_step: "capture_validation",
+};
+
/// Sink-agnostic emitter seam. The Kafka implementation is
/// [`KafkaWarningEmitter`]; tests use
/// [`test_support::CollectingEmitter`].
diff --git a/rust/common/ingestion_warnings/src/registry.rs b/rust/common/ingestion_warnings/src/registry.rs
index e9a52bfc15cc..6afd5e060779 100644
--- a/rust/common/ingestion_warnings/src/registry.rs
+++ b/rust/common/ingestion_warnings/src/registry.rs
@@ -28,15 +28,27 @@ impl WarningType {
/// Types capture emits directly, with no error tag behind them.
///
/// The tag route only reaches conditions capture already models as an
- /// `Error` or a per-event drop detail. Some warnings aren't failures at all:
- /// a rate-limited event is ingested (degraded, not dropped), so there is no
- /// tag to map and inventing one would mean inventing an error that never
- /// gets returned. Emit sites for these name the variant directly.
+ /// `Error` or a per-event drop detail. Two kinds of warning sit outside it:
+ ///
+ /// * Ones that aren't failures at all. A rate-limited event is ingested
+ /// (degraded, not dropped), so there is no tag to map and inventing one
+ /// 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.
+ ///
+ /// Emit sites for these name the variant directly.
///
/// 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; 2] = [Self::HighVolumeDistinctId, Self::DistinctIdTruncated];
+ pub const DIRECT_EMIT: [Self; 5] = [
+ Self::HighVolumeDistinctId,
+ Self::DistinctIdTruncated,
+ Self::InvalidAiEvent,
+ Self::InvalidAiPayload,
+ Self::NoAiSpansIngested,
+ ];
/// Map a capture error tag (`v1::Error::tag()` / per-event drop detail) to a
/// registered warning type. Returns `None` for anything not on the allowlist —
diff --git a/rust/common/ingestion_warnings/warning_types.generated.json b/rust/common/ingestion_warnings/warning_types.generated.json
index a464e5a2bf78..9c9497f18627 100644
--- a/rust/common/ingestion_warnings/warning_types.generated.json
+++ b/rust/common/ingestion_warnings/warning_types.generated.json
@@ -121,6 +121,18 @@
"severity": "warning",
"captureProduced": false
},
+ {
+ "type": "invalid_ai_event",
+ "category": "event",
+ "severity": "error",
+ "captureProduced": true
+ },
+ {
+ "type": "invalid_ai_payload",
+ "category": "event",
+ "severity": "error",
+ "captureProduced": true
+ },
{
"type": "invalid_ai_token_property",
"category": "event",
@@ -223,6 +235,12 @@
"severity": "error",
"captureProduced": true
},
+ {
+ "type": "no_ai_spans_ingested",
+ "category": "event",
+ "severity": "warning",
+ "captureProduced": true
+ },
{
"type": "person_properties_size_violation",
"category": "size",