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.

chore(aio): drop the multipart blob code from the ai capture endpoint (#78855)

Carlos Marchal461822d9bc2b
diff --git a/bin/start-rust-service b/bin/start-rust-service
index 06807ff1e21d..72e38c96c5e9 100755
--- a/bin/start-rust-service
+++ b/bin/start-rust-service
@@ -99,13 +99,6 @@ case "$RS_SVC" in
export CAPTURE_MODE=events
export LOG_LEVEL=debug
export DEBUG=1
- # AI endpoint S3 blob storage (MinIO)
- export AI_S3_BUCKET=ai-blobs
- export AI_S3_PREFIX=llma/
- export AI_S3_ENDPOINT=${AI_S3_ENDPOINT:-http://objectstorage:19000}
- export AI_S3_REGION=us-east-1
- export AI_S3_ACCESS_KEY_ID=object_storage_root_user
- export AI_S3_SECRET_ACCESS_KEY=object_storage_root_password
export DEV_RUST_SVC_OVERRIDE=capture # we want to run the same "capture" binary in a separate mode
;;
diff --git a/common/ingestion/acceptance_tests/test_ai_observability.py b/common/ingestion/acceptance_tests/test_ai_observability.py
index a5d24f30afcd..adde18bb7e7a 100644
--- a/common/ingestion/acceptance_tests/test_ai_observability.py
+++ b/common/ingestion/acceptance_tests/test_ai_observability.py
@@ -1,7 +1,5 @@
-"""AI observability capture tests - tests multipart blob upload and S3 storage."""
+"""AI observability capture tests - tests the multipart event transport on /i/v0/ai."""
-import os
-import re
import gzip
import json
import uuid
@@ -9,274 +7,36 @@ import logging
import pytest
-import boto3
import requests
-from botocore.config import Config as BotoConfig
-from multipart import multipart
from requests_toolbelt import MultipartEncoder
logger = logging.getLogger(__name__)
-def parse_s3_url(s3_url: str) -> tuple[str, str, int, int]:
- """Parse an S3 URL with range parameter.
-
- Args:
- s3_url: URL in format s3://bucket/key?range=start-end
-
- Returns:
- Tuple of (bucket, key, range_start, range_end)
- """
- # Parse s3://bucket/key?range=start-end
- match = re.match(r"s3://([^/]+)/(.+)\?range=(\d+)-(\d+)", s3_url)
- if not match:
- raise ValueError(f"Invalid S3 URL format: {s3_url}")
-
- bucket = match.group(1)
- key = match.group(2)
- range_start = int(match.group(3))
- range_end = int(match.group(4))
-
- return bucket, key, range_start, range_end
-
-
-def get_s3_client():
- """Create an S3 client using environment variables.
-
- Required environment variables:
- AI_S3_ENDPOINT: S3 endpoint URL (e.g., http://localhost:19000)
- AI_S3_ACCESS_KEY_ID: S3 access key
- AI_S3_SECRET_ACCESS_KEY: S3 secret key
- AI_S3_REGION: S3 region (optional, defaults to us-east-1)
-
- Raises:
- ValueError: If required environment variables are not set.
- """
- endpoint_url = os.environ.get("AI_S3_ENDPOINT")
- access_key = os.environ.get("AI_S3_ACCESS_KEY_ID")
- secret_key = os.environ.get("AI_S3_SECRET_ACCESS_KEY")
- region = os.environ.get("AI_S3_REGION", "us-east-1")
-
- missing = []
- if not endpoint_url:
- missing.append("AI_S3_ENDPOINT")
- if not access_key:
- missing.append("AI_S3_ACCESS_KEY_ID")
- if not secret_key:
- missing.append("AI_S3_SECRET_ACCESS_KEY")
-
- if missing:
- raise ValueError(f"Missing required S3 environment variables: {', '.join(missing)}")
-
- return boto3.client(
- "s3",
- endpoint_url=endpoint_url,
- aws_access_key_id=access_key,
- aws_secret_access_key=secret_key,
- region_name=region,
- config=BotoConfig(signature_version="s3v4"),
- )
-
-
-def fetch_blob_from_s3(s3_url: str) -> bytes:
- """Fetch blob data from S3 using the URL with range parameter.
-
- Args:
- s3_url: URL in format s3://bucket/key?range=start-end
-
- Returns:
- The blob data as bytes
-
- Raises:
- ValueError: If S3 credentials are not configured.
- """
- bucket, key, range_start, range_end = parse_s3_url(s3_url)
-
- s3_client = get_s3_client()
-
- # Fetch the object with byte range
- response = s3_client.get_object(Bucket=bucket, Key=key, Range=f"bytes={range_start}-{range_end}")
-
- return response["Body"].read()
-
-
-def fetch_full_s3_object(s3_url: str) -> tuple[bytes, str]:
- """Fetch the full S3 object (not just a range).
-
- Args:
- s3_url: URL in format s3://bucket/key?range=start-end
-
- Returns:
- Tuple of (object bytes, content-type header)
- """
- bucket, key, _, _ = parse_s3_url(s3_url)
- s3_client = get_s3_client()
- response = s3_client.get_object(Bucket=bucket, Key=key)
- return response["Body"].read(), response.get("ContentType", "")
-
-
-def parse_multipart_data(data: bytes, boundary: str) -> list[dict]:
- """Parse multipart data and return list of parts with headers and body.
-
- Args:
- data: Raw multipart bytes
- boundary: The boundary string (without -- prefix)
-
- Returns:
- List of dicts with keys: name, content_type, content_encoding, body
- """
- parts: list[dict] = []
-
- # python-multipart uses callbacks
- current_part: dict = {}
-
- def on_part_begin() -> None:
- nonlocal current_part
- current_part = {"headers": {}, "body": b""}
-
- def on_part_data(data: bytes, start: int, end: int) -> None:
- current_part["body"] += data[start:end]
-
- def on_part_end() -> None:
- # Extract name from Content-Disposition
- content_disposition = current_part["headers"].get("Content-Disposition", "")
- name_match = re.search(r'name="([^"]+)"', content_disposition)
- name = name_match.group(1) if name_match else ""
-
- parts.append(
- {
- "name": name,
- "content_type": current_part["headers"].get("Content-Type", "application/octet-stream"),
- "content_encoding": current_part["headers"].get("Content-Encoding"),
- "body": current_part["body"],
- }
- )
-
- def on_header_field(data: bytes, start: int, end: int) -> None:
- current_part["_header_field"] = data[start:end].decode("utf-8")
-
- def on_header_value(data: bytes, start: int, end: int) -> None:
- field = current_part.get("_header_field", "")
- current_part["headers"][field] = data[start:end].decode("utf-8")
-
- callbacks = {
- "on_part_begin": on_part_begin,
- "on_part_data": on_part_data,
- "on_part_end": on_part_end,
- "on_header_field": on_header_field,
- "on_header_value": on_header_value,
- }
-
- parser = multipart.MultipartParser(boundary.encode("utf-8"), callbacks)
- parser.write(data)
- parser.finalize()
-
- return parts
-
-
-def parse_mime_part(data: bytes) -> tuple[dict[str, str], bytes]:
- """Parse a MIME part (headers + body) using the standard email parser.
-
- The byte range format is a standard MIME part:
- Content-Disposition: form-data; name="property_name"\r\n
- Content-Type: application/json\r\n
- [Content-Encoding: gzip\r\n]
- \r\n
- <body bytes>
-
- Args:
- data: Raw bytes containing headers and body separated by \r\n\r\n
-
- Returns:
- Tuple of (headers dict with lowercase keys, body bytes)
- """
- from email import policy
- from email.parser import BytesParser
-
- # Parse as a MIME message
- parser = BytesParser(policy=policy.HTTP)
- msg = parser.parsebytes(data)
-
- # Extract headers (lowercase keys for consistency)
- headers: dict[str, str] = {k.lower(): str(v) for k, v in msg.items()}
-
- # Get raw body bytes
- payload = msg.get_payload(decode=True)
- body: bytes
- if payload is None:
- raw_payload = msg.get_payload()
- if isinstance(raw_payload, str):
- body = raw_payload.encode("utf-8")
- else:
- body = b""
- elif isinstance(payload, bytes):
- body = payload
- else:
- body = b""
-
- return headers, body
-
-
-def assert_part_details(part, expected_name, expected_length, expected_content_type, expected_content_encoding=None):
- """Assert comprehensive details about a multipart part."""
- assert part["name"] == expected_name, f"Expected part name '{expected_name}', got '{part['name']}'"
- assert part["length"] == expected_length, f"Expected part length {expected_length}, got {part['length']}"
- assert part["content-type"] == expected_content_type, (
- f"Expected content-type '{expected_content_type}', got '{part['content-type']}'"
+def post_multipart(base_url: str, api_key: str, fields: dict) -> requests.Response:
+ multipart_data = MultipartEncoder(fields=fields)
+ return requests.post(
+ f"{base_url}/i/v0/ai",
+ data=multipart_data,
+ headers={"Content-Type": multipart_data.content_type, "Authorization": f"Bearer {api_key}"},
)
- assert part["content-encoding"] == expected_content_encoding, (
- f"Expected content-encoding '{expected_content_encoding}', got '{part['content-encoding']}'"
- )
-
-
-def assert_parts_order_and_details(response_data, expected_parts):
- """Assert that parts are in the correct order and have correct details."""
- assert "accepted_parts" in response_data, "Response should contain accepted_parts"
- assert isinstance(response_data["accepted_parts"], list), "accepted_parts should be a list"
-
- actual_parts = response_data["accepted_parts"]
- assert len(actual_parts) == len(expected_parts), f"Expected {len(expected_parts)} parts, got {len(actual_parts)}"
-
- for i, (actual_part, expected_part) in enumerate(zip(actual_parts, expected_parts)):
- expected_name, expected_length, expected_content_type, expected_content_encoding = expected_part
- assert_part_details(
- actual_part, expected_name, expected_length, expected_content_type, expected_content_encoding
- )
- logger.debug(f"Part {i}: {actual_part['name']} - {actual_part['length']} bytes - {actual_part['content-type']}")
@pytest.mark.usefixtures("shared_org_project")
class TestAIObservability:
- """Test AI observability capture flow with multipart requests and S3 storage."""
-
- # ============================================================================
- # PHASE 1: HTTP ENDPOINT
- # ============================================================================
-
- # ----------------------------------------------------------------------------
- # Scenario 1.1: Event Processing Verification
- # ----------------------------------------------------------------------------
-
def test_basic_ai_generation_event(self, shared_org_project):
- """Test that we can capture an $ai_generation event with blob data via multipart request."""
- logger.info("\n" + "=" * 60)
- logger.info("STARTING TEST: Basic $ai_generation Event Capture")
- logger.info("=" * 60)
-
client = shared_org_project["client"]
project_id = shared_org_project["project_id"]
project_api_key = shared_org_project["api_key"]
- # Step 1: Using shared organization and project
- logger.info("Step 1: Using shared organization and project")
-
- # Step 2: Prepare test event data
- logger.info("Step 2: Preparing $ai_generation event")
distinct_id = f"test_user_{uuid.uuid4().hex[:8]}"
- event_uuid = str(uuid.uuid4())
+ ai_input = [
+ {"role": "system", "content": "You are a helpful assistant."},
+ {"role": "user", "content": "What is the capital of France?"},
+ ]
event_data = {
- "uuid": event_uuid,
+ "uuid": str(uuid.uuid4()),
"event": "$ai_generation",
"distinct_id": distinct_id,
"timestamp": "2024-01-15T10:30:00Z",
@@ -285,305 +45,115 @@ class TestAIObservability:
"$ai_provider": "openai",
"$ai_output_tokens": 150,
"$ai_input_tokens": 50,
+ "$ai_input": ai_input,
"custom_property": "test_value",
},
}
- # Prepare blob data
- input_blob = {
- "messages": [
- {"role": "system", "content": "You are a helpful assistant."},
- {"role": "user", "content": "What is the capital of France?"},
- ],
- "temperature": 0.7,
- "max_tokens": 200,
- }
-
- output_blob = {
- "choices": [
- {
- "message": {"role": "assistant", "content": "The capital of France is Paris."},
- "finish_reason": "stop",
- "index": 0,
- }
- ],
- "model": "gpt-4",
- "usage": {"prompt_tokens": 50, "completion_tokens": 150, "total_tokens": 200},
- }
-
- # Step 3: Create multipart request
- logger.info("Step 3: Creating multipart request")
-
- # Create multipart encoder with proper boundary
- boundary = f"----WebKitFormBoundary{uuid.uuid4().hex[:16]}"
-
- fields = {
- "event": ("event", json.dumps(event_data), "application/json"),
- "event.properties.$ai_input": (
- f"blob_{uuid.uuid4().hex[:8]}",
- json.dumps(input_blob),
- "application/json",
- ),
- "event.properties.$ai_output_choices": (
- f"blob_{uuid.uuid4().hex[:8]}",
- json.dumps(output_blob),
- "application/json",
- ),
- }
-
- multipart_data = MultipartEncoder(fields=fields, boundary=boundary)
-
- # Step 4: Send multipart request to /i/v0/ai endpoint
- logger.info("Step 4: Sending multipart request to /i/v0/ai endpoint")
-
- capture_url = f"{client.base_url}/i/v0/ai"
- headers = {"Content-Type": multipart_data.content_type, "Authorization": f"Bearer {project_api_key}"}
-
- logger.debug("POST %s", capture_url)
- logger.debug("Content-Type: %s", headers["Content-Type"])
-
- response = requests.post(capture_url, data=multipart_data, headers=headers)
-
- logger.debug("Response status: %s", response.status_code)
- logger.debug("Response body: %s", response.text)
-
- # Check if request was successful
+ response = post_multipart(
+ client.base_url,
+ project_api_key,
+ {"event": ("event", json.dumps(event_data), "application/json")},
+ )
response.raise_for_status()
- logger.info("Multipart request sent successfully")
- # Verify response contains accepted parts
response_data = response.json()
- assert "accepted_parts" in response_data
accepted_parts = response_data["accepted_parts"]
- assert len(accepted_parts) == 3, f"Expected 3 parts, got {len(accepted_parts)}"
-
- # Verify each part has correct details
- event_json = json.dumps(event_data)
- input_json = json.dumps(input_blob)
- output_json = json.dumps(output_blob)
-
+ assert len(accepted_parts) == 1, f"Expected 1 part, got {len(accepted_parts)}"
assert accepted_parts[0]["name"] == "event"
- assert accepted_parts[0]["length"] == len(event_json)
+ assert accepted_parts[0]["length"] == len(json.dumps(event_data))
assert accepted_parts[0]["content-type"] == "application/json"
- assert accepted_parts[1]["name"] == "event.properties.$ai_input"
- assert accepted_parts[1]["length"] == len(input_json)
- assert accepted_parts[1]["content-type"] == "application/json"
-
- assert accepted_parts[2]["name"] == "event.properties.$ai_output_choices"
- assert accepted_parts[2]["length"] == len(output_json)
- assert accepted_parts[2]["content-type"] == "application/json"
-
- logger.info("Response validation successful: all parts accepted with correct lengths")
-
- # Step 5: Wait for event to appear in query API
- logger.info("Step 5: Waiting for event to be processed")
event = client.wait_for_event(
project_id=project_id, event_name="$ai_generation", distinct_id=distinct_id, timeout=30
)
-
- # Verify event was found
assert event is not None, "$ai_generation event not found after 30 seconds"
- logger.info("Event found in query API")
- logger.debug("Retrieved event: %s", event)
-
- # Step 6: Verify event properties
- logger.info("Step 6: Verifying event properties")
assert event.get("event") == "$ai_generation"
assert event.get("distinct_id") == distinct_id
event_properties = event.get("properties", {})
-
- # Verify standard properties
assert event_properties.get("$ai_model") == "gpt-4"
assert event_properties.get("$ai_provider") == "openai"
assert event_properties.get("$ai_output_tokens") == 150
assert event_properties.get("$ai_input_tokens") == 50
assert event_properties.get("custom_property") == "test_value"
-
- # Verify blob properties were replaced with S3 URLs
- assert "$ai_input" in event_properties, "$ai_input property not found"
- assert "$ai_output_choices" in event_properties, "$ai_output_choices property not found"
-
- ai_input_url = event_properties["$ai_input"]
- ai_output_url = event_properties["$ai_output_choices"]
-
- logger.debug("$ai_input URL: %s", ai_input_url)
- logger.debug("$ai_output_choices URL: %s", ai_output_url)
-
- # Verify URLs are S3 URLs with range parameters
- assert ai_input_url.startswith("s3://"), "$ai_input should be an S3 URL"
- assert ai_output_url.startswith("s3://"), "$ai_output_choices should be an S3 URL"
- assert "range=" in ai_input_url, "$ai_input URL should contain range parameter"
- assert "range=" in ai_output_url, "$ai_output_choices URL should contain range parameter"
-
- # Verify URLs point to same multipart file but different ranges
- input_base = ai_input_url.split("?")[0]
- output_base = ai_output_url.split("?")[0]
- assert input_base == output_base, "Both URLs should point to same multipart file"
-
- logger.info("All event properties verified successfully")
- logger.info("S3 URLs generated correctly with byte ranges")
- logger.info("Test completed successfully")
- logger.info("=" * 60)
+ assert event_properties.get("$ai_input") == ai_input
def test_ai_generation_event_with_separate_properties(self, shared_org_project):
- """Test $ai_generation event with properties in a separate multipart part."""
- logger.info("\n" + "=" * 60)
- logger.info("STARTING TEST: $ai_generation Event with Separate Properties")
- logger.info("=" * 60)
-
client = shared_org_project["client"]
project_id = shared_org_project["project_id"]
project_api_key = shared_org_project["api_key"]
- logger.info("Step 1: Using shared organization and project")
-
- logger.info("Step 2: Preparing $ai_generation event with separate properties")
distinct_id = f"test_user_{uuid.uuid4().hex[:8]}"
- event_uuid = str(uuid.uuid4())
-
event_data = {
- "uuid": event_uuid,
+ "uuid": str(uuid.uuid4()),
"event": "$ai_generation",
"distinct_id": distinct_id,
- "timestamp": "2024-01-15T10:30:00Z",
}
-
properties_data = {
- "$ai_model": "gpt-3.5-turbo",
+ "$ai_model": "gpt-4",
"$ai_provider": "openai",
- "$ai_output_tokens": 100,
- "$ai_input_tokens": 25,
- "custom_property": "separate_test",
- }
-
- input_blob = {
- "messages": [
- {"role": "user", "content": "Tell me a joke."},
- ],
- "temperature": 0.9,
+ "$ai_input": [{"role": "user", "content": "Hello"}],
}
- output_blob = {
- "choices": [
- {
- "message": {
- "role": "assistant",
- "content": "Why did the chicken cross the road? To get to the other side!",
- },
- "finish_reason": "stop",
- }
- ],
- }
-
- logger.info("Step 3: Creating multipart request with separate properties part")
- boundary = f"----WebKitFormBoundary{uuid.uuid4().hex[:16]}"
-
- fields = {
- "event": ("event", json.dumps(event_data), "application/json"),
- "event.properties": ("event.properties", json.dumps(properties_data), "application/json"),
- "event.properties.$ai_input": (
- f"blob_{uuid.uuid4().hex[:8]}",
- json.dumps(input_blob),
- "application/json",
- ),
- "event.properties.$ai_output_choices": (
- f"blob_{uuid.uuid4().hex[:8]}",
- json.dumps(output_blob),
- "application/json",
- ),
- }
-
- multipart_data = MultipartEncoder(fields=fields, boundary=boundary)
-
- logger.info("Step 4: Sending multipart request to /i/v0/ai endpoint")
- capture_url = f"{client.base_url}/i/v0/ai"
- headers = {"Content-Type": multipart_data.content_type, "Authorization": f"Bearer {project_api_key}"}
-
- response = requests.post(capture_url, data=multipart_data, headers=headers)
+ response = post_multipart(
+ client.base_url,
+ project_api_key,
+ {
+ "event": ("event", json.dumps(event_data), "application/json"),
+ "event.properties": ("event.properties", json.dumps(properties_data), "application/json"),
+ },
+ )
response.raise_for_status()
- logger.info("Multipart request sent successfully")
-
- # Verify response contains accepted parts
- response_data = response.json()
- assert "accepted_parts" in response_data
- accepted_parts = response_data["accepted_parts"]
- assert len(accepted_parts) == 4, f"Expected 4 parts, got {len(accepted_parts)}"
-
- # Verify each part has correct details
- event_json = json.dumps(event_data)
- properties_json = json.dumps(properties_data)
- input_json = json.dumps(input_blob)
- output_json = json.dumps(output_blob)
+ accepted_parts = response.json()["accepted_parts"]
+ assert len(accepted_parts) == 2, f"Expected 2 parts, got {len(accepted_parts)}"
assert accepted_parts[0]["name"] == "event"
- assert accepted_parts[0]["length"] == len(event_json)
- assert accepted_parts[0]["content-type"] == "application/json"
-
assert accepted_parts[1]["name"] == "event.properties"
- assert accepted_parts[1]["length"] == len(properties_json)
- assert accepted_parts[1]["content-type"] == "application/json"
+ assert accepted_parts[1]["length"] == len(json.dumps(properties_data))
- assert accepted_parts[2]["name"] == "event.properties.$ai_input"
- assert accepted_parts[2]["length"] == len(input_json)
- assert accepted_parts[2]["content-type"] == "application/json"
-
- assert accepted_parts[3]["name"] == "event.properties.$ai_output_choices"
- assert accepted_parts[3]["length"] == len(output_json)
- assert accepted_parts[3]["content-type"] == "application/json"
-
- logger.info("Response validation successful: all parts accepted with correct lengths")
-
- logger.info("Step 5: Waiting for event to be processed")
event = client.wait_for_event(
project_id=project_id, event_name="$ai_generation", distinct_id=distinct_id, timeout=30
)
-
assert event is not None, "$ai_generation event not found after 30 seconds"
- logger.info("Event found in query API")
-
- logger.info("Step 6: Verifying event properties")
- assert event.get("event") == "$ai_generation"
- assert event.get("distinct_id") == distinct_id
-
event_properties = event.get("properties", {})
+ assert event_properties.get("$ai_model") == "gpt-4"
+ assert event_properties.get("$ai_input") == [{"role": "user", "content": "Hello"}]
- assert event_properties.get("$ai_model") == "gpt-3.5-turbo"
- assert event_properties.get("$ai_provider") == "openai"
- assert event_properties.get("$ai_output_tokens") == 100
- assert event_properties.get("$ai_input_tokens") == 25
- assert event_properties.get("custom_property") == "separate_test"
-
- assert "$ai_input" in event_properties
- assert "$ai_output_choices" in event_properties
-
- ai_input_url = event_properties["$ai_input"]
- ai_output_url = event_properties["$ai_output_choices"]
+ def test_blob_parts_are_rejected(self, shared_org_project):
+ client = shared_org_project["client"]
+ project_api_key = shared_org_project["api_key"]
- assert ai_input_url.startswith("s3://")
- assert ai_output_url.startswith("s3://")
- assert "range=" in ai_input_url
- assert "range=" in ai_output_url
+ event_data = {
+ "uuid": str(uuid.uuid4()),
+ "event": "$ai_generation",
+ "distinct_id": f"test_user_{uuid.uuid4().hex[:8]}",
+ "properties": {"$ai_model": "gpt-4"},
+ }
- input_base = ai_input_url.split("?")[0]
- output_base = ai_output_url.split("?")[0]
- assert input_base == output_base
+ response = post_multipart(
+ client.base_url,
+ project_api_key,
+ {
+ "event": ("event", json.dumps(event_data), "application/json"),
+ "event.properties.$ai_input": (
+ f"blob_{uuid.uuid4().hex[:8]}",
+ json.dumps({"messages": []}),
+ "application/json",
+ ),
+ },
+ )
- logger.info("All event properties verified successfully")
- logger.info("Separate properties part handled correctly")
- logger.info("Test completed successfully")
- logger.info("=" * 60)
+ assert response.status_code == 400, f"Expected 400, got {response.status_code}: {response.text}"
+ assert "Unknown multipart field" in response.text
def test_all_accepted_ai_event_types(self, shared_org_project):
- """Test that all six accepted AI event types are successfully captured and stored."""
client = shared_org_project["client"]
project_id = shared_org_project["project_id"]
api_key = shared_org_project["api_key"]
base_distinct_id = f"user_{uuid.uuid4()}"
- # Define all event types with their specific properties
events_to_test = [
{
"event_type": "$ai_generation",
@@ -645,7 +215,6 @@ class TestAIObservability:
},
]
- # Send all events
for event_spec in events_to_test:
event_type = event_spec["event_type"]
distinct_id = event_spec["distinct_id"]
@@ -658,28 +227,21 @@ class TestAIObservability:
"$set": {"test_user": True, "event_type_test": event_type},
}
- fields = {
- "event": ("event", json.dumps(event_data), "application/json"),
- "event.properties": ("event.properties", json.dumps(event_spec["properties"]), "application/json"),
- }
-
- multipart_data = MultipartEncoder(fields=fields)
- response = requests.post(
- f"{client.base_url}/i/v0/ai",
- data=multipart_data,
- headers={"Content-Type": multipart_data.content_type, "Authorization": f"Bearer {api_key}"},
+ response = post_multipart(
+ client.base_url,
+ api_key,
+ {
+ "event": ("event", json.dumps(event_data), "application/json"),
+ "event.properties": ("event.properties", json.dumps(event_spec["properties"]), "application/json"),
+ },
)
assert response.status_code == 200, (
f"Expected 200 for {event_type}, got {response.status_code}: {response.text}"
)
- response_data = response.json()
- assert len(response_data["accepted_parts"]) == 2
+ assert len(response.json()["accepted_parts"]) == 2
logger.info(f"{event_type} event sent successfully")
- logger.info("All event types sent successfully, now querying to verify storage")
-
- # Query and verify all events
for event_spec in events_to_test:
event_type = event_spec["event_type"]
distinct_id = event_spec["distinct_id"]
@@ -693,356 +255,7 @@ class TestAIObservability:
assert event["properties"]["$ai_provider"] == "test-provider"
logger.info(f"{event_type} event verified successfully")
- logger.info("All six AI event types verified successfully")
-
- # ============================================================================
- # PHASE 4: MULTIPART FILE PROCESSING
- # ============================================================================
-
- # ----------------------------------------------------------------------------
- # Scenario 4.3: Content Type Handling
- # ----------------------------------------------------------------------------
-
- def test_ai_generation_event_with_different_content_types(self, shared_org_project):
- """Test sending events with blobs using different supported content types."""
- client = shared_org_project["client"]
- project_id = shared_org_project["project_id"]
- api_key = shared_org_project["api_key"]
-
- base_distinct_id = f"user_{uuid.uuid4()}"
-
- # Send Event 1: application/json blob
- logger.info("Sending event with application/json blob")
- distinct_id_json = f"{base_distinct_id}_json"
- event_data_json = {
- "uuid": str(uuid.uuid4()),
- "event": "$ai_generation",
- "distinct_id": distinct_id_json,
- "$set": {"test_user": True, "content_type_test": "json"},
- }
- properties_data_json = {
- "$ai_model": "gpt-4",
- "$ai_model_parameters": {"temperature": 0.7},
- }
- json_blob_data = {"context": "This is JSON formatted LLM input", "tokens": 150}
-
- fields_json = {
- "event": ("event", json.dumps(event_data_json), "application/json"),
- "event.properties": ("event.properties", json.dumps(properties_data_json), "application/json"),
- "event.properties.$ai_input": ("blob_json", json.dumps(json_blob_data), "application/json"),
- }
-
- multipart_data_json = MultipartEncoder(fields=fields_json)
- response_json = requests.post(
- f"{client.base_url}/i/v0/ai",
- data=multipart_data_json,
- headers={"Content-Type": multipart_data_json.content_type, "Authorization": f"Bearer {api_key}"},
- )
- assert response_json.status_code == 200, f"Expected 200, got {response_json.status_code}: {response_json.text}"
- response_data_json = response_json.json()
- assert len(response_data_json["accepted_parts"]) == 3
- parts_by_name_json = {part["name"]: part for part in response_data_json["accepted_parts"]}
- assert parts_by_name_json["event.properties.$ai_input"]["content-type"] == "application/json"
-
- # Send Event 2: text/plain blob
- logger.info("Sending event with text/plain blob")
- distinct_id_text = f"{base_distinct_id}_text"
- event_data_text = {
- "uuid": str(uuid.uuid4()),
- "event": "$ai_generation",
- "distinct_id": distinct_id_text,
- "$set": {"test_user": True, "content_type_test": "text"},
- }
- properties_data_text = {
- "$ai_model": "gpt-4",
- "$ai_model_parameters": {"temperature": 0.5},
- }
- text_blob_data = "This is plain text LLM output with multiple lines.\nSecond line here.\nThird line."
-
- fields_text = {
- "event": ("event", json.dumps(event_data_text), "application/json"),
- "event.properties": ("event.properties", json.dumps(properties_data_text), "application/json"),
- "event.properties.$ai_output": ("blob_text", text_blob_data, "text/plain"),
- }
-
- multipart_data_text = MultipartEncoder(fields=fields_text)
- response_text = requests.post(
- f"{client.base_url}/i/v0/ai",
- data=multipart_data_text,
- headers={"Content-Type": multipart_data_text.content_type, "Authorization": f"Bearer {api_key}"},
- )
- assert response_text.status_code == 200, f"Expected 200, got {response_text.status_code}: {response_text.text}"
- response_data_text = response_text.json()
- assert len(response_data_text["accepted_parts"]) == 3
- parts_by_name_text = {part["name"]: part for part in response_data_text["accepted_parts"]}
- assert parts_by_name_text["event.properties.$ai_output"]["content-type"] == "text/plain"
-
- # Send Event 3: application/octet-stream blob
- logger.info("Sending event with application/octet-stream blob")
- distinct_id_binary = f"{base_distinct_id}_binary"
- event_data_binary = {
- "uuid": str(uuid.uuid4()),
- "event": "$ai_generation",
- "distinct_id": distinct_id_binary,
- "$set": {"test_user": True, "content_type_test": "binary"},
- }
- properties_data_binary = {
- "$ai_model": "gpt-4",
- "$ai_model_parameters": {"temperature": 0.9},
- }
- binary_blob_data = bytes([0x00, 0x01, 0x02, 0x03, 0x04, 0xFF, 0xFE, 0xFD])
-
- fields_binary = {
- "event": ("event", json.dumps(event_data_binary), "application/json"),
- "event.properties": ("event.properties", json.dumps(properties_data_binary), "application/json"),
- "event.properties.$ai_embedding_vector": ("blob_binary", binary_blob_data, "application/octet-stream"),
- }
-
- multipart_data_binary = MultipartEncoder(fields=fields_binary)
- response_binary = requests.post(
- f"{client.base_url}/i/v0/ai",
- data=multipart_data_binary,
- headers={"Content-Type": multipart_data_binary.content_type, "Authorization": f"Bearer {api_key}"},
- )
- assert response_binary.status_code == 200, (
- f"Expected 200, got {response_binary.status_code}: {response_binary.text}"
- )
- response_data_binary = response_binary.json()
- assert len(response_data_binary["accepted_parts"]) == 3
- parts_by_name_binary = {part["name"]: part for part in response_data_binary["accepted_parts"]}
- assert (
- parts_by_name_binary["event.properties.$ai_embedding_vector"]["content-type"] == "application/octet-stream"
- )
-
- logger.info("All three events sent successfully, now querying to verify storage")
-
- # Query and verify Event 1 (JSON blob)
- event_json = client.wait_for_event(project_id, "$ai_generation", distinct_id_json)
- assert event_json is not None, "Event with JSON blob not found"
- assert event_json["properties"]["$ai_model"] == "gpt-4"
- logger.info(f"Event 1 (JSON blob) verified: {distinct_id_json}")
-
- # Query and verify Event 2 (text blob)
- event_text = client.wait_for_event(project_id, "$ai_generation", distinct_id_text)
- assert event_text is not None, "Event with text blob not found"
- assert event_text["properties"]["$ai_model"] == "gpt-4"
- logger.info(f"Event 2 (text blob) verified: {distinct_id_text}")
-
- # Query and verify Event 3 (binary blob)
- event_binary = client.wait_for_event(project_id, "$ai_generation", distinct_id_binary)
- assert event_binary is not None, "Event with binary blob not found"
- assert event_binary["properties"]["$ai_model"] == "gpt-4"
- logger.info(f"Event 3 (binary blob) verified: {distinct_id_binary}")
-
- logger.info("All three content type events verified successfully")
-
- # Verify blob properties have S3 URLs
- # Event 1: $ai_input should be an S3 URL
- ai_input_url = event_json["properties"].get("$ai_input")
- assert ai_input_url is not None, "Event 1 should have $ai_input property"
- assert ai_input_url.startswith("s3://"), f"$ai_input should be an S3 URL, got: {ai_input_url}"
- assert "?range=" in ai_input_url, f"$ai_input URL should have range parameter, got: {ai_input_url}"
- logger.info(f"Event 1 $ai_input S3 URL verified: {ai_input_url}")
-
- # Event 2: $ai_output should be an S3 URL
- ai_output_url = event_text["properties"].get("$ai_output")
- assert ai_output_url is not None, "Event 2 should have $ai_output property"
- assert ai_output_url.startswith("s3://"), f"$ai_output should be an S3 URL, got: {ai_output_url}"
- assert "?range=" in ai_output_url, f"$ai_output URL should have range parameter, got: {ai_output_url}"
- logger.info(f"Event 2 $ai_output S3 URL verified: {ai_output_url}")
-
- # Event 3: $ai_embedding_vector should be an S3 URL
- ai_embedding_url = event_binary["properties"].get("$ai_embedding_vector")
- assert ai_embedding_url is not None, "Event 3 should have $ai_embedding_vector property"
- assert ai_embedding_url.startswith("s3://"), (
- f"$ai_embedding_vector should be an S3 URL, got: {ai_embedding_url}"
- )
- assert "?range=" in ai_embedding_url, (
- f"$ai_embedding_vector URL should have range parameter, got: {ai_embedding_url}"
- )
- logger.info(f"Event 3 $ai_embedding_vector S3 URL verified: {ai_embedding_url}")
-
- def test_ai_blob_data_stored_correctly_in_s3(self, shared_org_project):
- """Test that blob data is correctly stored in S3 as multipart/mixed format.
-
- Verifies:
- 1. Each property's byte range can be fetched and parsed as a standalone multipart document
- 2. The full S3 object can be parsed as a multipart document containing all parts
- 3. Headers (Content-Type, Content-Disposition) are preserved correctly
- 4. Body content matches the original data
- """
- client = shared_org_project["client"]
- project_id = shared_org_project["project_id"]
- api_key = shared_org_project["api_key"]
-
- logger.info("Sending event with multiple blobs to verify S3 multipart storage")
-
- distinct_id = f"s3_storage_test_{uuid.uuid4().hex[:8]}"
- event_uuid = str(uuid.uuid4())
-
- # Create distinct blob data that we can verify
- json_blob_data = {"test_key": "test_value", "number": 42, "nested": {"a": 1}}
- text_blob_data = "This is test text blob data for S3 verification.\nLine 2."
- binary_blob_data = bytes([0xDE, 0xAD, 0xBE, 0xEF, 0x00, 0x01, 0x02, 0x03])
-
- event_data = {
- "uuid": event_uuid,
- "event": "$ai_generation",
- "distinct_id": distinct_id,
- }
-
- properties_data = {
- "$ai_model": "test-s3-storage",
- }
-
- fields = {
- "event": ("event", json.dumps(event_data), "application/json"),
- "event.properties": ("event.properties", json.dumps(properties_data), "application/json"),
- "event.properties.$ai_input": ("json_blob", json.dumps(json_blob_data), "application/json"),
- "event.properties.$ai_output": ("text_blob", text_blob_data, "text/plain"),
- "event.properties.$ai_embedding_vector": ("binary_blob", binary_blob_data, "application/octet-stream"),
- }
-
- multipart_data = MultipartEncoder(fields=fields)
- response = requests.post(
- f"{client.base_url}/i/v0/ai",
- data=multipart_data,
- headers={"Content-Type": multipart_data.content_type, "Authorization": f"Bearer {api_key}"},
- )
- assert response.status_code == 200, f"Expected 200, got {response.status_code}: {response.text}"
-
- # Wait for event to be stored
- event = client.wait_for_event(project_id, "$ai_generation", distinct_id)
- assert event is not None, "Event not found"
-
- # Get and verify the S3 URLs from properties
- ai_input_url = event["properties"].get("$ai_input")
- ai_output_url = event["properties"].get("$ai_output")
- ai_embedding_url = event["properties"].get("$ai_embedding_vector")
-
- # Verify URLs exist and have correct format
- assert ai_input_url is not None, "$ai_input property not found"
- assert ai_output_url is not None, "$ai_output property not found"
- assert ai_embedding_url is not None, "$ai_embedding_vector property not found"
-
- assert ai_input_url.startswith("s3://"), f"$ai_input should be S3 URL, got: {ai_input_url}"
- assert ai_output_url.startswith("s3://"), f"$ai_output should be S3 URL, got: {ai_output_url}"
- assert ai_embedding_url.startswith("s3://"), f"$ai_embedding_vector should be S3 URL, got: {ai_embedding_url}"
-
- assert "?range=" in ai_input_url, f"$ai_input should have range param, got: {ai_input_url}"
- assert "?range=" in ai_output_url, f"$ai_output should have range param, got: {ai_output_url}"
- assert "?range=" in ai_embedding_url, f"$ai_embedding_vector should have range param, got: {ai_embedding_url}"
-
- logger.info("S3 URLs verified:")
- logger.info(f" $ai_input: {ai_input_url}")
- logger.info(f" $ai_output: {ai_output_url}")
- logger.info(f" $ai_embedding_vector: {ai_embedding_url}")
-
- # Verify all blobs are stored in the same S3 object (same base URL, different ranges)
- base_url_input = ai_input_url.split("?")[0]
- base_url_output = ai_output_url.split("?")[0]
- base_url_embedding = ai_embedding_url.split("?")[0]
-
- assert base_url_input == base_url_output == base_url_embedding, (
- f"All blobs should be in same S3 object. Got:\n"
- f" input: {base_url_input}\n"
- f" output: {base_url_output}\n"
- f" embedding: {base_url_embedding}"
- )
- logger.info(f"All blobs stored in same S3 object: {base_url_input}")
-
- # Verify ranges are sequential and non-overlapping
- # Note: ranges exclude boundaries, so first part doesn't start at 0
- _, _, input_start, input_end = parse_s3_url(ai_input_url)
- _, _, output_start, output_end = parse_s3_url(ai_output_url)
- _, _, embedding_start, embedding_end = parse_s3_url(ai_embedding_url)
-
- assert output_start > input_end, f"Second blob should start after first ends"
- assert embedding_start > output_end, f"Third blob should start after second ends"
-
- logger.info(
- f"Byte ranges verified: {input_start}-{input_end}, {output_start}-{output_end}, {embedding_start}-{embedding_end}"
- )
-
- # =========================================================================
- # TEST 1: Verify S3 object metadata and full document parses as multipart
- # =========================================================================
- logger.info("TEST 1: Verifying S3 object metadata and full document...")
-
- full_data, content_type = fetch_full_s3_object(ai_input_url)
- logger.info(f"Full S3 object size: {len(full_data)} bytes")
- logger.info(f"Content-Type header: {content_type}")
-
- # Extract boundary from Content-Type header (format: multipart/mixed; boundary=...)
- assert "multipart/mixed" in content_type, f"Expected multipart/mixed content type, got: {content_type}"
- boundary_match = re.search(r"boundary=([^\s;]+)", content_type)
- assert boundary_match, f"Could not extract boundary from Content-Type: {content_type}"
- boundary = boundary_match.group(1)
- logger.info(f"Boundary: {boundary}")
-
- # Parse the full document as multipart to verify it's valid
- all_parts = parse_multipart_data(full_data, boundary)
- assert len(all_parts) == 3, f"Expected 3 parts in full document, got {len(all_parts)}"
-
- # Verify all parts are present with correct content
- assert all_parts[0]["name"] == "$ai_input"
- assert all_parts[0]["content_type"] == "application/json"
- assert json.loads(all_parts[0]["body"].decode("utf-8")) == json_blob_data
-
- assert all_parts[1]["name"] == "$ai_output"
- assert all_parts[1]["content_type"] == "text/plain"
- assert all_parts[1]["body"].decode("utf-8") == text_blob_data
-
- assert all_parts[2]["name"] == "$ai_embedding_vector"
- assert all_parts[2]["content_type"] == "application/octet-stream"
- assert all_parts[2]["body"] == binary_blob_data
-
- logger.info("TEST 1 PASSED: Full document parses as valid multipart with all 3 parts")
-
- # =========================================================================
- # TEST 2: Fetch each range separately and parse as MIME part
- # Each range contains headers + body (no boundaries), which can be parsed
- # using the standard email/MIME parser.
- # =========================================================================
- logger.info("TEST 2: Fetching each range separately and parsing as MIME part...")
-
- # Test range fetch for $ai_input
- input_range_data = fetch_blob_from_s3(ai_input_url)
- input_headers, input_body = parse_mime_part(input_range_data)
- assert "$ai_input" in input_headers.get("content-disposition", "")
- assert input_headers.get("content-type") == "application/json"
- assert json.loads(input_body.decode("utf-8")) == json_blob_data
- logger.info("$ai_input range fetch and parse: PASSED")
-
- # Test range fetch for $ai_output
- output_range_data = fetch_blob_from_s3(ai_output_url)
- output_headers, output_body = parse_mime_part(output_range_data)
- assert "$ai_output" in output_headers.get("content-disposition", "")
- assert output_headers.get("content-type") == "text/plain"
- assert output_body.decode("utf-8") == text_blob_data
- logger.info("$ai_output range fetch and parse: PASSED")
-
- # Test range fetch for $ai_embedding_vector
- embedding_range_data = fetch_blob_from_s3(ai_embedding_url)
- embedding_headers, embedding_body = parse_mime_part(embedding_range_data)
- assert "$ai_embedding_vector" in embedding_headers.get("content-disposition", "")
- assert embedding_headers.get("content-type") == "application/octet-stream"
- assert embedding_body == binary_blob_data
- logger.info("$ai_embedding_vector range fetch and parse: PASSED")
-
- logger.info("TEST 2 PASSED: Each range can be fetched and parsed as MIME part")
- logger.info("S3 multipart blob storage verification complete")
-
- # ============================================================================
- # PHASE 5: AUTHORIZATION
- # ============================================================================
-
- # ----------------------------------------------------------------------------
- # Scenario 5.1: API Key Authentication
- # ----------------------------------------------------------------------------
-
def test_ai_endpoint_invalid_auth_returns_401(self, function_test_client):
- """Test that requests with invalid API key return 401 Unauthorized."""
client = function_test_client
event_data = {
@@ -1066,157 +279,55 @@ class TestAIObservability:
)
assert response.status_code == 401, f"Expected 401, got {response.status_code}"
- # ============================================================================
- # PHASE 7: COMPRESSION
- # ============================================================================
-
- # ----------------------------------------------------------------------------
- # Scenario 7.1: Mixed Compression
- # ----------------------------------------------------------------------------
-
def test_ai_generation_event_with_gzip_compression(self, shared_org_project):
- """Test $ai_generation event with gzip compression for the entire request."""
- logger.info("\n" + "=" * 60)
- logger.info("STARTING TEST: $ai_generation Event with Gzip Compression")
- logger.info("=" * 60)
-
client = shared_org_project["client"]
project_id = shared_org_project["project_id"]
project_api_key = shared_org_project["api_key"]
- logger.info("Step 1: Using shared organization and project")
-
- logger.info("Step 2: Preparing $ai_generation event")
distinct_id = f"test_user_{uuid.uuid4().hex[:8]}"
- event_uuid = str(uuid.uuid4())
-
event_data = {
- "uuid": event_uuid,
+ "uuid": str(uuid.uuid4()),
"event": "$ai_generation",
"distinct_id": distinct_id,
"timestamp": "2024-01-15T10:30:00Z",
- "properties": {
- "$ai_model": "gpt-4-compressed",
- "$ai_provider": "openai",
- "$ai_output_tokens": 75,
- "$ai_input_tokens": 30,
- "compression": "gzip",
- },
- }
-
- input_blob = {
- "messages": [
- {"role": "system", "content": "You are a helpful assistant."},
- {"role": "user", "content": "Explain compression in simple terms."},
- ],
}
-
- output_blob = {
- "choices": [
- {
- "message": {
- "role": "assistant",
- "content": "Compression reduces data size by encoding information more efficiently.",
- },
- "finish_reason": "stop",
- }
- ],
+ properties_data = {
+ "$ai_model": "gpt-4-compressed",
+ "$ai_provider": "openai",
+ "$ai_output_tokens": 75,
+ "$ai_input_tokens": 30,
+ "compression": "gzip",
}
- logger.info("Step 3: Creating multipart request")
- boundary = f"----WebKitFormBoundary{uuid.uuid4().hex[:16]}"
-
fields = {
"event": ("event", json.dumps(event_data), "application/json"),
- "event.properties.$ai_input": (
- f"blob_{uuid.uuid4().hex[:8]}",
- json.dumps(input_blob),
- "application/json",
- ),
- "event.properties.$ai_output_choices": (
- f"blob_{uuid.uuid4().hex[:8]}",
- json.dumps(output_blob),
- "application/json",
- ),
- }
-
- multipart_data = MultipartEncoder(fields=fields, boundary=boundary)
-
- logger.info("Step 4: Compressing request body with gzip")
- uncompressed_body = multipart_data.to_string()
- compressed_body = gzip.compress(uncompressed_body)
-
- logger.debug("Uncompressed size: %d bytes", len(uncompressed_body))
- logger.debug("Compressed size: %d bytes", len(compressed_body))
- logger.debug("Compression ratio: %.2f%%", (1 - len(compressed_body) / len(uncompressed_body)) * 100)
-
- logger.info("Step 5: Sending compressed multipart request to /i/v0/ai endpoint")
- capture_url = f"{client.base_url}/i/v0/ai"
- headers = {
- "Content-Type": multipart_data.content_type,
- "Content-Encoding": "gzip",
- "Authorization": f"Bearer {project_api_key}",
+ "event.properties": ("event.properties", json.dumps(properties_data), "application/json"),
}
+ multipart_data = MultipartEncoder(fields=fields)
+ compressed_body = gzip.compress(multipart_data.to_string())
- response = requests.post(capture_url, data=compressed_body, headers=headers)
+ response = requests.post(
+ f"{client.base_url}/i/v0/ai",
+ data=compressed_body,
+ headers={
+ "Content-Type": multipart_data.content_type,
+ "Content-Encoding": "gzip",
+ "Authorization": f"Bearer {project_api_key}",
+ },
+ )
response.raise_for_status()
- logger.info("Compressed multipart request sent successfully")
-
- # Verify response contains accepted parts
- response_data = response.json()
- assert "accepted_parts" in response_data
- accepted_parts = response_data["accepted_parts"]
- assert len(accepted_parts) == 3, f"Expected 3 parts, got {len(accepted_parts)}"
-
- # Verify each part has correct details (lengths should match uncompressed data)
- event_json = json.dumps(event_data)
- input_json = json.dumps(input_blob)
- output_json = json.dumps(output_blob)
+ accepted_parts = response.json()["accepted_parts"]
+ assert len(accepted_parts) == 2, f"Expected 2 parts, got {len(accepted_parts)}"
assert accepted_parts[0]["name"] == "event"
- assert accepted_parts[0]["length"] == len(event_json)
- assert accepted_parts[0]["content-type"] == "application/json"
-
- assert accepted_parts[1]["name"] == "event.properties.$ai_input"
- assert accepted_parts[1]["length"] == len(input_json)
- assert accepted_parts[1]["content-type"] == "application/json"
-
- assert accepted_parts[2]["name"] == "event.properties.$ai_output_choices"
- assert accepted_parts[2]["length"] == len(output_json)
- assert accepted_parts[2]["content-type"] == "application/json"
-
- logger.info("Response validation successful: decompressed parts have correct lengths")
+ assert accepted_parts[0]["length"] == len(json.dumps(event_data))
+ assert accepted_parts[1]["name"] == "event.properties"
+ assert accepted_parts[1]["length"] == len(json.dumps(properties_data))
- logger.info("Step 6: Waiting for event to be processed")
event = client.wait_for_event(
project_id=project_id, event_name="$ai_generation", distinct_id=distinct_id, timeout=30
)
-
assert event is not None, "$ai_generation event not found after 30 seconds"
- logger.info("Event found in query API")
-
- logger.info("Step 7: Verifying event properties")
- assert event.get("event") == "$ai_generation"
- assert event.get("distinct_id") == distinct_id
-
event_properties = event.get("properties", {})
-
assert event_properties.get("$ai_model") == "gpt-4-compressed"
- assert event_properties.get("$ai_provider") == "openai"
assert event_properties.get("compression") == "gzip"
-
- assert "$ai_input" in event_properties
- assert "$ai_output_choices" in event_properties
-
- ai_input_url = event_properties["$ai_input"]
- ai_output_url = event_properties["$ai_output_choices"]
-
- assert ai_input_url.startswith("s3://")
- assert ai_output_url.startswith("s3://")
- assert "range=" in ai_input_url
- assert "range=" in ai_output_url
-
- logger.info("All event properties verified successfully")
- logger.info("Gzip compression handled correctly")
- logger.info("Test completed successfully")
- logger.info("=" * 60)
diff --git a/docker-compose.base.yml b/docker-compose.base.yml
index ac3e0c5d4e08..7adc234b8f15 100644
--- a/docker-compose.base.yml
+++ b/docker-compose.base.yml
@@ -419,13 +419,6 @@ services:
REDIS_URL: 'redis://redis7:6379/'
CAPTURE_MODE: events
RUST_LOG: 'info,rdkafka=warn'
- # AI endpoint S3 blob storage
- AI_S3_BUCKET: ai-blobs
- AI_S3_PREFIX: 'llma/'
- AI_S3_ENDPOINT: 'http://objectstorage:19000'
- AI_S3_REGION: us-east-1
- AI_S3_ACCESS_KEY_ID: object_storage_root_user
- AI_S3_SECRET_ACCESS_KEY: object_storage_root_password
capture-logs:
image: ghcr.io/posthog/posthog/capture-logs:master
diff --git a/products/ingestion/skills/resolving-ingestion-warnings/references/fixing-ai-endpoint-rejections.md b/products/ingestion/skills/resolving-ingestion-warnings/references/fixing-ai-endpoint-rejections.md
index 71625b1f0bec..6ed7de3acd2c 100644
--- a/products/ingestion/skills/resolving-ingestion-warnings/references/fixing-ai-endpoint-rejections.md
+++ b/products/ingestion/skills/resolving-ingestion-warnings/references/fixing-ai-endpoint-rejections.md
@@ -4,7 +4,7 @@ Covers `invalid_ai_event`, `invalid_ai_payload`, and `no_ai_spans_ingested`.
These come from capture's two dedicated LLM analytics endpoints, not from the ingestion pipeline:
-- `/i/v0/ai` — one event per request, sent as multipart so large prompt and completion bodies can ride along as separate parts. Warnings carry `path: ai_events`.
+- `/i/v0/ai` — one event per request, sent as multipart with an `event` part and an optional `event.properties` part. Warnings carry `path: ai_events`.
- `/i/v0/ai/otel` — OTLP trace export, protobuf or JSON. Warnings carry `path: ai_otel`.
Both reject at the edge, so a rejected event reaches nothing downstream. It is not in `events`, not in any insight, and has no other trace beyond the warning. `count` is the number of events or spans that didn't land.
@@ -34,7 +34,7 @@ The request body couldn't be used. Read the details to see which check failed.
**`stage`** and `spanCount` are present when an export carried too many spans. `stage: raw` means more than 1000 spans arrived before filtering; `stage: ai` means more than 100 AI spans survived filtering. Both mean the exporter needs a smaller batch size or a shorter flush interval. `limit` is the cap that was exceeded.
-**`part`** is present for multipart problems on `/i/v0/ai`, naming the offending part. Common cases: a field that isn't `event`, `event.properties`, or `event.properties.<name>`; a blob part with no `Content-Type` or an unsupported one (only `application/octet-stream`, `application/json`, and `text/plain` are accepted, reported in `contentType`); an empty blob; or a blob property name containing dots, which isn't allowed since only top-level properties can be sent as blobs.
+**`part`** is present for multipart problems on `/i/v0/ai`, naming the offending part. The only valid parts are `event` and `event.properties`; anything else is rejected. Per-property blob parts (`event.properties.<name>`) were a discarded experiment and are no longer accepted: media belongs inline in the event JSON, where ingestion offloads it to blob storage.
**Neither** means the multipart framing itself was wrong, or the event part wasn't valid UTF-8 JSON.
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index 92931a3123da..a511f3c15b4f 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -2152,7 +2152,6 @@ dependencies = [
"hex",
"hmac 0.12.1",
"http-body-util",
- "httparse",
"hyper 1.9.0",
"hyper-util",
"lifecycle",
diff --git a/rust/capture/Cargo.toml b/rust/capture/Cargo.toml
index ef37a3edfdb2..b5c256d13703 100644
--- a/rust/capture/Cargo.toml
+++ b/rust/capture/Cargo.toml
@@ -75,7 +75,6 @@ common-continuous-profiling = { path = "../common/continuous_profiling" }
anyhow = { workspace = true }
axum-test-helper = { git = "https://github.com/posthog/axum-test-helper.git" }
futures = { workspace = true }
-httparse = "1.8"
metrics-util = { workspace = true }
once_cell = { workspace = true }
rand = { workspace = true }
diff --git a/rust/capture/docs/ai-endpoint-parity.md b/rust/capture/docs/ai-endpoint-parity.md
index 4099c0aa6e44..76b2f11461b3 100644
--- a/rust/capture/docs/ai-endpoint-parity.md
+++ b/rust/capture/docs/ai-endpoint-parity.md
@@ -27,15 +27,11 @@ This document compares the `/i/v0/ai` endpoint with the `/i/v0/e` (events) endpo
| Feature | Description | Notes |
|---------|-------------|-------|
-| Multipart form-data parsing | Parse and validate multipart requests with events + blobs | AI-specific |
+| Multipart form-data parsing | Parse and validate multipart requests with an event part and an optional properties part | AI-specific |
| Authorization header requirement | Require `Bearer <token>` in Authorization header | AI-specific |
| AI event type validation | Validate against 6 allowed AI event types: `$ai_generation`, `$ai_trace`, `$ai_span`, `$ai_embedding`, `$ai_metric`, `$ai_feedback` | AI-specific |
| `$ai_model` property validation | Ensure `$ai_model` is present and non-empty | AI-specific |
-| Blob part handling | Handle blob parts and generate S3 placeholders | AI-specific |
-| Byte range calculation | Calculate byte ranges for blob parts in concatenated format | AI-specific |
-| Content-Type validation per part | Validate Content-Type for each multipart part | AI-specific |
-| Strict size limits per part type | 32KB event, 960KB properties + event, configurable total | AI-specific |
-| Duplicate property name detection | Prevent duplicate property names across parts | AI-specific |
+| Strict size limits per part type | 32KB event, 960KB properties + event | AI-specific |
### Features Present in Both
@@ -73,16 +69,14 @@ This document compares the `/i/v0/ai` endpoint with the `/i/v0/e` (events) endpo
### 2. Token Dropper Filtering ✅ DONE
-**Implementation:** The AI endpoint now checks the token dropper before processing blob parts.
+**Implementation:** The AI endpoint now checks the token dropper before parsing the remaining multipart parts.
**How it works:**
1. After parsing just the event metadata (via `retrieve_event_metadata()`), checks `state.token_dropper.should_drop(token, distinct_id)`
2. If dropped, returns HTTP 429 (Too Many Requests) with "billing limit reached" error
3. Metrics reported via `report_dropped_events("token_dropper", 1)`
-4. Early return avoids parsing potentially large blob parts for dropped events
-
-**Optimization:** The token dropper check happens before parsing blob parts, saving processing time when events are dropped.
+4. Early return avoids parsing the remaining parts for dropped events
### 3. Historical Rerouting - Not Needed
@@ -107,7 +101,7 @@ flag.
## Notes
-- The AI endpoint's unique features (multipart parsing, blob handling, etc.) are intentional and should be preserved
+- The AI endpoint's unique features (multipart parsing, AI event validation, etc.) are intentional and should be preserved
- Some differences are by design rather than gaps:
- **Event type filtering**: `/e` uses denylist (blocks `$performance_event`), AI uses allowlist (only accepts 6 `$ai_*` events)
- **Single event vs batch**: AI processes single events, `/e` supports batches
diff --git a/rust/capture/docs/llma-acceptance-test-suite.md b/rust/capture/docs/llma-acceptance-test-suite.md
deleted file mode 100644
index c5c1ce8791ca..000000000000
--- a/rust/capture/docs/llma-acceptance-test-suite.md
+++ /dev/null
@@ -1,218 +0,0 @@
-# LLMA Acceptance Test Suite
-
-## Overview
-
-This document describes the Python acceptance test suite for the AI observability pipeline. These tests validate **end-to-end functionality** that requires real PostHog infrastructure: database, S3 storage, Kafka, authentication services, and the full ingestion pipeline.
-
-**Implementation Requirement**: Each phase in the implementation plan must pass its corresponding acceptance tests before proceeding to the next phase. This ensures incremental validation and prevents regression as new features are added.
-
-## Test Architecture
-
-### Test Environment
-
-- **Local PostHog Deployment**: Complete local PostHog setup including capture service with `/i/v0/ai` endpoint
-- **S3-Compatible Storage**: Local S3-compatible storage for blob storage with direct access for verification
-- **PostHog Query API**: Used to fetch processed events from the ingestion pipeline for validation
-- **Direct S3 Access**: Test suite has direct S3 client access to verify blob storage and retrieval
-- **Database**: PostgreSQL for team/token storage and event metadata
-- **Kafka**: Event streaming for ingestion pipeline
-- **ClickHouse**: Event storage and query API
-
-### Test Framework
-
-- **Acceptance Tests**: Full pipeline tests from HTTP request through ingestion to event storage
-- **PostHog API Client**: Direct integration with PostHog query API to verify event processing
-- **S3 Client**: Direct access to verify S3 blob storage, metadata, and retrieval
-- **Parameterized Tests**: Test variations across different event types, blob sizes, and configurations
-- **Async Testing**: Support for testing concurrent requests and large payload processing
-
-### Test Data
-
-- **AI Event Types**: `$ai_trace`, `$ai_span`, `$ai_generation`, `$ai_embedding`, `$ai_metric`, `$ai_feedback`
-- **Blob Sizes**: Small (1KB), Medium (100KB), Large (1MB), Extra Large (10MB+)
-- **Content Types**: `application/json`, `text/plain`, `application/octet-stream`
-- **Compression**: Gzipped and uncompressed blobs
-- **Encoding**: Raw binary, text, and base64-encoded blobs
-- **Multipart Boundaries**: Various boundary strings to test collision handling
-
-## Test Scenarios
-
-**Phase Completion Requirement**: All acceptance tests for a phase must pass before implementation can proceed to the next phase. This gate ensures quality and prevents compound issues from multiple incomplete features.
-
-### Phase 1: HTTP Endpoint
-
-#### Scenario 1.1: Event Processing Verification
-
-- **Test**: Send multipart request and verify event reaches PostHog query API
-- **Validation**: Use PostHog query API to fetch processed event, verify blob placeholders correctly inserted
-- **Tests Implemented**:
- - `test_basic_ai_generation_event`: Full end-to-end event processing
- - `test_all_accepted_ai_event_types`: Verify all six supported AI event types are accepted and stored
-
-### Phase 2: Basic S3 Uploads
-
-#### Scenario 2.1: Individual Blob Upload
-
-- **Test**: Upload blobs of various sizes as separate S3 objects
-- **Validation**: Verify each blob stored correctly, S3 URLs generated in event properties
-- **Variations**: Small/medium/large blobs, different content types
-
-#### Scenario 2.2: S3 URL Generation and Access
-
-- **Test**: Verify generated S3 URLs in PostHog events point to accessible objects
-- **Validation**: Query PostHog API for events, extract S3 URLs, verify blobs retrievable from S3
-
-#### Scenario 2.3: Blob Metadata Storage
-
-- **Test**: Verify S3 object metadata is stored correctly
-- **Validation**: Use S3 client to inspect object metadata - Content-Type, size, team_id present
-
-#### Scenario 2.4: Team Data Isolation
-
-- **Test**: Multiple teams uploading simultaneously
-- **Validation**: Verify S3 key prefixes are team-scoped, no cross-team data access, proper S3 path isolation
-
-### Phase 4: Multipart File Processing
-
-#### Scenario 4.1: Multipart File Creation
-
-- **Test**: Upload events with multiple blobs, verify multipart/mixed format
-- **Validation**: Use S3 client to verify single S3 file contains all blobs, proper MIME boundaries, metadata preserved
-- **Variations**: 2-10 blobs per event, mixed content types, different blob sizes
-
-#### Scenario 4.2: Byte Range URLs and Access
-
-- **Test**: Verify S3 URLs in PostHog events include correct byte range parameters
-- **Validation**: Query PostHog API for events, verify URLs contain range parameters, use S3 client to test range requests
-
-#### Scenario 4.3: Content Type Handling
-
-- **Test**: Mix of JSON, text, and binary blobs in single multipart file
-- **Validation**: Content types preserved in multipart format, correctly parsed
-
-### Phase 5: Authorization
-
-#### Scenario 5.1: API Key Authentication
-
-- **Test**: Send requests with valid/invalid/missing API keys
-- **Validation**: Valid keys accepted, invalid keys rejected with 401, proper error messages
-- **Tests Implemented**:
- - `test_ai_endpoint_invalid_auth_returns_401`: Invalid token validation
-
-### Phase 7: Compression
-
-#### Scenario 7.1: Mixed Compression
-
-- **Test**: Single request with both compressed and uncompressed blobs
-- **Validation**: Each blob handled according to its compression state
-
-### Phase 9: Limits (Optional) - DO NOT IMPLEMENT, TBD
-
-### Phase 10: Data Deletion (Optional) - DO NOT IMPLEMENT, TBD
-
-### Cross-Team Isolation Testing
-
-## Error Recovery and Edge Cases
-
-### Edge Case Scenarios
-
-#### Scenario E.1: S3 Service Interruption
-
-- **Test**: Simulate S3 unavailability during uploads
-- **Validation**: Proper error responses, retry logic works, no data loss
-
-#### Scenario E.2: Kafka Unavailability
-
-- **Test**: Simulate Kafka unavailability during event publishing
-- **Validation**: Appropriate error handling, request failure communicated to client
-
-## Local Development Testing
-
-### Test Implementation
-
-The acceptance test suite is implemented in Python using pytest to test against full PostHog infrastructure.
-
-#### Test Structure
-
-- **Location**: `common/ingestion/acceptance_tests/test_llm_analytics.py`
-- **Framework**: pytest with async support
-- **Dependencies**:
- - `requests` for HTTP client operations
- - `boto3` for S3 client operations (when needed)
- - PostHog SDK or API for event querying
- - Django test utilities for setup
-
-### Local Test Environment Setup
-
-#### Prerequisites
-
-- **Local PostHog Instance**: Full PostHog deployment running locally with all services (Django, capture, Kafka, ClickHouse, PostgreSQL)
-- **Capture Service**: Running with `/i/v0/ai` endpoint enabled
-- **Personal API Key**: PostHog personal API key for creating test organizations/projects
-
-#### Environment Configuration
-
-```bash
-# PostHog Instance (defaults to http://localhost:8010 if not set)
-export POSTHOG_TEST_BASE_URL="http://localhost:8010"
-
-# Personal API Key (required - no default)
-export POSTHOG_PERSONAL_API_KEY="your_personal_api_key_here"
-```
-
-**Creating a Personal API Key:**
-
-1. Navigate to your PostHog instance (e.g., `http://localhost:8010`)
-2. Go to **Settings** (sidebar) → **Account** → **Personal API Keys**
-3. Click **Create personal API key**
-4. Configure the key:
- - **Organization & project access**: Set to **All** (to avoid permission issues)
- - **Scopes**: Set to **All access** (required for creating/deleting test organizations and projects)
-5. Copy the generated key and set it as `POSTHOG_PERSONAL_API_KEY`
-
-**Note**: The test suite automatically creates temporary organizations and projects for each test class and cleans them up after tests complete. S3 configuration is handled by the PostHog instance itself.
-
-### Test Execution
-
-#### Running Tests
-
-```bash
-# Run all acceptance tests using the test runner
-cd common/ingestion/acceptance_tests
-python run_tests.py
-
-# Or run pytest directly for specific tests
-pytest test_llm_analytics.py::TestAIObservability::test_basic_ai_generation_event -v
-
-# Run specific test class
-pytest test_llm_analytics.py::TestAIObservability -v
-```
-
-The `run_tests.py` script automatically:
-
-- Configures pytest with appropriate logging and verbosity settings
-- Runs tests in parallel using `--numprocesses=auto` for faster execution
-- Shows detailed debug logs during test execution
-
-#### Test Utilities
-
-Each test phase will include common utilities for:
-
-- **Multipart Request Builder**: Construct multipart/form-data requests with event JSON and blob parts
-- **S3 Client Wrapper**: Direct S3 operations for validation and cleanup
-- **PostHog API Client**: Query PostHog API to verify event processing
-- **Test Data Generators**: Create various blob sizes, content types, and event payloads
-- **Cleanup Helpers**: Remove test data from S3 and PostHog between test runs
-
-#### Test Data Management
-
-- **Isolated Test Teams**: Each test uses unique team IDs to prevent interference
-- **Cleanup Between Tests**: Automatic cleanup of S3 objects and PostHog test data
-- **Fixture Data**: Predefined multipart requests and blob data for consistent testing
-- **Random Data Generation**: Configurable blob sizes and content for stress testing
-
-## Phase Gating
-
-- **Mandatory Testing**: All acceptance tests for a phase must pass before proceeding to implementation of the next phase
-- **Regression Prevention**: Previous phase tests continue to run to ensure no regression
-- **Incremental Validation**: Each phase builds upon validated functionality from previous phases
diff --git a/rust/capture/docs/llma-capture-implementation-plan.md b/rust/capture/docs/llma-capture-implementation-plan.md
deleted file mode 100644
index abdff972368b..000000000000
--- a/rust/capture/docs/llma-capture-implementation-plan.md
+++ /dev/null
@@ -1,183 +0,0 @@
-# AI observability capture implementation plan
-
-## Overview
-
-This document outlines the implementation steps for the AI observability capture pipeline based on the design specified in `llma-capture-overview.md`.
-
-## Implementation Phases
-
-### Phase 0: Local Development Setup
-
-#### 0.1 Routing Configuration
-
-- [x] Create new `/i/v0/ai` endpoint in capture service
-- [x] Set up routing for `/i/v0/ai` endpoint to capture service (Caddy routes in docker-compose, capture-ai service on port 3308)
-
-#### 0.2 End-to-End Integration Tests
-
-- [x] Implement Rust integration tests for multipart parsing and validation
-- [x] Create Python acceptance test scenarios with multipart requests and blob data
-- [x] Test Kafka message output and S3 storage integration
-
-### Phase 1: HTTP Endpoint
-
-#### 1.1 HTTP Endpoint Foundation
-
-- [x] Implement multipart/form-data request parsing
-- [x] Add server-side boundary validation
-- [x] Support separate `event.properties` multipart part
-- [x] Implement gzip decompression for compressed requests
-- [x] Output events with blob placeholders to Kafka
-- [x] Implement error schema
-
-#### 1.2 Basic Validation
-
-- [x] Implement specific AI event type validation ($ai_generation, $ai_trace, $ai_span, $ai_embedding, $ai_metric, $ai_feedback)
-- [x] Validate blob part names against event properties
-- [x] Prevent blob overwriting of existing properties (reject if both embedded and separate properties)
-- [x] Validate event part is first in multipart request
-- [x] Validate required fields (event name, distinct_id, $ai_model)
-- [x] Implement size limits (32KB event, 960KB combined, 25MB total, 27.5MB request body)
-
-#### 1.3 Initial Deployment (Dev)
-
-- [x] Deploy capture-ai service to dev with basic `/i/v0/ai` endpoint
-- [x] Test basic multipart parsing and Kafka output functionality
-- [x] Verify endpoint responds correctly to AI events
-
-### Phase 2: Basic S3 Uploads
-
-#### 2.1 Simple S3 Upload (per blob)
-
-- [x] Upload individual blobs to S3 as separate objects (concatenated into single file per event)
-- [x] Generate S3 URLs for blobs (format: `s3://{bucket}/{prefix}{token}/{uuid}?range={start}-{end}`)
-- [x] Store S3 blob metadata (URLs stored in event properties)
-- [ ] Track S3 upload success/failure rates
-- [ ] Monitor blob size distributions
-
-### Phase 3: S3 Infrastructure & Deployment
-
-#### 3.1 S3 Bucket Configuration
-
-- [x] Set up S3 buckets for local dev (MinIO: `ai-blobs` bucket via docker-compose)
-- [x] Set up bucket structure with `llma/` prefix
-- [ ] Set up S3 buckets for dev environment
-- [ ] Configure S3 lifecycle policies for retention (30d default)
-- [ ] Set up S3 access policies for capture service
-- [ ] Create service accounts with appropriate S3 permissions
-
-#### 3.2 Capture S3 Configuration (Dev)
-
-- [x] Configure capture-ai service for local dev with S3 (bin/start-rust-service, mprocs.yaml)
-- [x] Test S3 connectivity and uploads (acceptance tests pass)
-- [ ] Deploy capture-ai service to dev environment with S3 configuration
-- [ ] Set up IAM roles and permissions for capture-ai service
-- [ ] Configure S3 read/write permissions
-
-### Phase 4: Multipart File Processing
-
-#### 4.1 Multipart File Creation
-
-- [x] Implement multipart/mixed format for S3 storage
-- [x] Store headers (Content-Type, Content-Disposition, Content-Encoding) within multipart format
-- [x] Generate S3 URLs with byte range parameters (ranges exclude boundaries, include headers + body)
-- [x] Full document parseable as valid multipart/mixed
-- [x] Individual ranges parseable as MIME parts using standard parsers (httparse in Rust, email.parser in Python)
-
-### Phase 5: Authorization
-
-#### 5.1 Request Signature Verification
-
-- [x] Implement basic API key validation (Bearer token authentication)
-- [ ] Implement PostHog API key authentication
-- [ ] Add request signature verification
-- [ ] Validate API key before processing multipart data
-- [ ] Add proper error responses for authentication failures
-- [ ] Test authentication with valid and invalid keys
-
-### Phase 6: Operations
-
-#### 6.1 Monitoring Setup
-
-- [ ] Set up monitoring dashboards for capture-ai
-
-#### 6.2 Alerting
-
-- [ ] Configure alerts for S3 upload failures
-- [ ] Set up alerts for high error rates on `/i/v0/ai` endpoint
-- [ ] Set up alerts for high latency on `/i/v0/ai` endpoint
-
-#### 6.3 Runbooks
-
-- [ ] Create runbook for capture-ai S3 connectivity issues
-
-### Phase 7: Compression
-
-#### 7.1 Compression Support
-
-- [x] Parse Content-Encoding: gzip header for request-level compression
-- [x] Implement streaming gzip decompression for compressed requests
-- [x] Test with gzip-compressed multipart requests
-- [ ] Implement server-side compression for uncompressed blobs before S3 storage
-- [ ] Add compression metadata to S3 objects
-- [ ] Track compression ratio effectiveness
-
-### Phase 8: Schema Validation
-
-#### 8.1 Schema Validation
-
-- [x] Validate Content-Type headers on blob parts (required: application/json, text/plain, application/octet-stream)
-- [x] Validate event JSON structure (event, distinct_id, properties fields)
-- [x] Validate required AI properties ($ai_model)
-- [x] Test with different supported content types
-- [ ] Create comprehensive schema definitions for each AI event type
-- [ ] Add detailed schema validation for event-specific properties
-- [ ] Add Content-Length validation beyond size limits
-
-### Phase 9: Limits (Optional)
-
-#### 9.1 Request Validation & Limits
-
-- [x] Add request size limits and validation (configurable via `ai_max_sum_of_parts_bytes`)
-- [x] Implement event part size limit (32KB)
-- [x] Implement combined event+properties size limit (960KB)
-- [x] Implement total parts size limit (25MB default, configurable)
-- [x] Implement request body size limit (110% of total parts limit)
-- [x] Return 413 Payload Too Large for size violations
-- [x] Add quota limiting per team (via `quota_limiter.check_and_filter()`, returns `BillingLimit` error when exceeded)
-- [ ] Implement per-team payload size limits
-
-### Phase 10: Production Deployment
-
-#### 10.1 Production S3 Infrastructure
-
-- [ ] Set up S3 buckets for production environment
-- [ ] Configure S3 lifecycle policies for production
-- [ ] Set up S3 access policies for production capture service
-- [ ] Create production service accounts with appropriate S3 permissions
-
-#### 10.2 Capture Service Production Deployment
-
-- [ ] Deploy capture-ai service to production with basic `/i/v0/ai` endpoint
-- [ ] Test basic multipart parsing and Kafka output functionality in production
-- [ ] Verify endpoint responds correctly to AI events in production
-- [ ] Deploy capture-ai service to production environment with S3 configuration
-- [ ] Set up production IAM roles and permissions for capture-ai service
-- [ ] Configure production S3 read/write permissions
-
-### Phase 11: Data Deletion (Optional)
-
-#### 11.1 Data Deletion (Choose One Approach)
-
-- [ ] Option A: S3 expiry (passive) - rely on lifecycle policies
-- [ ] Option B: S3 delete by prefix functionality
-- [ ] Option C: Per-team encryption keys
-
-### Phase 12: Automated Testing
-
-#### 12.1 Continuous Validation
-
-- [ ] Set up automated test suite for continuous validation
-- [ ] Configure CI/CD pipeline integration for capture-ai tests
-- [ ] Set up automated regression testing for `/i/v0/ai` endpoint
-- [ ] Implement automated S3 integration validation tests
diff --git a/rust/capture/docs/llma-capture-overview.md b/rust/capture/docs/llma-capture-overview.md
index abe90b1dee0e..54cc2d6bf855 100644
--- a/rust/capture/docs/llma-capture-overview.md
+++ b/rust/capture/docs/llma-capture-overview.md
@@ -2,556 +2,69 @@
## Objective
-Implement a dedicated capture pathway for AI observability events that enables efficient processing of large-scale language model interactions. This specialized pipeline will:
+`/i/v0/ai` is the dedicated single-event ingress for AI observability events.
+It accepts one AI event per request as `multipart/form-data`, validates it against the AI event contract, and publishes it to Kafka like any other captured event.
+Heavy content (prompts, completions, media) rides inline in the event JSON;
+oversized media is offloaded to blob storage later, at ingestion, by the Node AI pipeline's blob-offload step (`nodejs/src/ingestion/pipelines/ai/blob-offload/`), not by capture.
-- Store LLM inputs and outputs directly in S3 for scalable, cost-effective storage
-- Route events through the main ingestion pipeline while bypassing the processing of large LLM context payloads
-- Ensure the core analytics pipeline remains performant by separating heavy LLM content from standard event processing
-- Enable dedicated processing of events containing LLM context through a separate evaluation service, allowing for specialized analysis and computation on LLM interactions
+Batch traffic uses `/i/v0/ai/batch`, which dispatches to the standard batch handler.
+OTLP trace export uses `/i/v0/ai/otel`.
+This document covers only the single-event multipart endpoint.
-This approach allows us to capture comprehensive LLM usage data without impacting the performance of our primary event ingestion system.
+## Supported events
-## Supported Events
+The endpoint accepts exactly six event names (`ALLOWED_AI_EVENTS` in `ai_rejection.rs`):
+`$ai_generation`, `$ai_trace`, `$ai_span`, `$ai_embedding`, `$ai_metric`, and `$ai_feedback`.
+Every event must carry a non-empty string `$ai_model` property, a `distinct_id`, and a client-supplied `uuid`.
-The AI observability capture endpoint supports four primary AI event types. Events are sent to the `/i/v0/ai` endpoint with multipart payloads to handle large context data efficiently.
+## Request format
-### `$ai_generation`
+The body is `multipart/form-data` with at most two parts, in order:
-A generation represents a single call to an LLM (e.g., a chat completion request).
+1. `event` (required, first): the event JSON, including `uuid`, `event`, `distinct_id`, and optionally `timestamp`, `sent_at`, and embedded `properties`.
+2. `event.properties` (optional): the properties object as its own JSON part.
+ Mutually exclusive with embedded `properties` on the event part; sending both is rejected as `ConflictingProperties`.
-**Core Properties:**
+Any other part name is rejected as `UnknownField`.
+This includes the per-property blob parts (`event.properties.<name>`) from a discarded experiment that stored blobs in S3 at capture time;
+media now belongs inline in the event JSON, where the ingestion pipeline offloads it content-addressed to S3 and rewrites it to `phaiblob://` pointers.
-- `$ai_trace_id` (required) - UUID to group AI events (e.g., conversation_id)
-- `$ai_model` (required) - The model used (e.g., "gpt-4o", "claude-3-opus")
-- `$ai_provider` (required) - The LLM provider (e.g., "openai", "anthropic", "gemini")
-- `$ai_input` - List of messages sent to the LLM (can be stored as blob)
- - Can contain 300,000+ tokens, making blob storage essential
- - Each message has a `role` ("user", "system", or "assistant") and `content` array
- - Content types: text, image URLs, function calls
-- `$ai_output_choices` - List of response choices from the LLM (can be stored as blob)
- - Each choice has a `role` and `content` array
-- `$ai_input_tokens` - Number of tokens in the input
-- `$ai_output_tokens` - Number of tokens in the output
-- `$ai_span_id` (optional) - Unique identifier for this generation
-- `$ai_span_name` (optional) - Name given to this generation
-- `$ai_parent_id` (optional) - Parent span ID for tree view grouping
-- `$ai_latency` (optional) - LLM call latency in seconds
-- `$ai_time_to_first_token` (optional) - Time to first token in seconds (streaming only)
-- `$ai_http_status` (optional) - HTTP status code of the response
-- `$ai_base_url` (optional) - Base URL of the LLM provider
-- `$ai_request_url` (optional) - Full URL of the request
-- `$ai_is_error` (optional) - Boolean indicating if the request was an error
-- `$ai_error` (optional) - Error message or object
+Authentication is a `Bearer <token>` Authorization header, validated before any decompression work.
-**Cost Properties** (optional, auto-calculated from model and token counts if not provided):
+### Size limits
-- `$ai_input_cost_usd` - Cost in USD of input tokens
-- `$ai_output_cost_usd` - Cost in USD of output tokens
-- `$ai_total_cost_usd` - Total cost in USD
-
-**Cache Properties** (optional):
-
-- `$ai_cache_read_input_tokens` - Number of tokens read from cache
-- `$ai_cache_creation_input_tokens` - Number of tokens written to cache (Anthropic-specific)
-
-**Model Parameters** (optional):
-
-- `$ai_temperature` - Temperature parameter used
-- `$ai_stream` - Whether the response was streamed
-- `$ai_max_tokens` - Maximum tokens setting
-- `$ai_tools` - Tools/functions available to the LLM
-
-### `$ai_trace`
-
-A trace represents a complete AI interaction flow (e.g., a full conversation or agent execution).
-
-**Key Properties:**
-
-- `$ai_trace_id` (required) - UUID identifying this trace
-- `$ai_input_state` - Initial state of the trace (can be stored as blob)
-- `$ai_output_state` - Final state of the trace (can be stored as blob)
-
-### `$ai_span`
-
-A span represents a logical unit of work within a trace (e.g., a tool call, a retrieval step).
-
-**Key Properties:**
-
-- `$ai_trace_id` (required) - Parent trace UUID
-- `$ai_span_id` (required) - Unique identifier for this span
-- `$ai_parent_id` (optional) - Parent span ID for nesting
-- `$ai_span_name` - Name describing this span
-- `$ai_input_state` - Input state for this span (can be stored as blob)
-- `$ai_output_state` - Output state for this span (can be stored as blob)
-
-### `$ai_embedding`
-
-An embedding event captures vector generation for semantic search or RAG systems.
-
-**Key Properties:**
-
-- `$ai_trace_id` (required) - Parent trace UUID
-- `$ai_model` (required) - Embedding model used
-- `$ai_provider` (required) - Provider (e.g., "openai", "cohere")
-- `$ai_input` - Text or data being embedded (can be stored as blob)
-- `$ai_input_tokens` - Number of tokens in the input
-- Note: Output vectors are typically not captured in events
-
-### Standard Events (No Blob Storage Required)
-
-These events are lightweight and processed through the regular pipeline:
-
-- **`$ai_metric`** - Performance metrics, usage statistics
-- **`$ai_feedback`** - User feedback on AI responses
-
-### Blob Storage Strategy
-
-Properties that can contain large payloads (marked as "can be stored as blob" above) should be sent as separate multipart parts with names like `event.properties.$ai_input` or `event.properties.$ai_output_choices`. This keeps the event JSON small while allowing arbitrarily large context data to be stored efficiently in S3.
-
-**Reference:** [PostHog AI observability manual capture documentation](https://posthog.com/docs/ai-observability/installation/manual-capture)
-
-## General Architecture
-
-The AI observability capture system implements a specialized data flow that efficiently handles large language model payloads:
-
-### Data Flow
-
-1. **Event Ingestion**
- - Events are transmitted using server-side PostHog SDKs via HTTP to a dedicated `/i/v0/ai` endpoint
- - Requests utilize multipart payloads containing:
- - Event payload (metadata and standard properties)
- - Binary blobs containing LLM context (e.g., input state, output state property values)
-
-2. **Blob Processing**
- - The capture service extracts blob data from multipart requests
- - Blobs are uploaded directly to S3 for persistent storage
- - Upon successful upload, the corresponding AI state properties in the event are replaced with S3 URLs
- - This transformation replaces inline LLM data with S3 references
-
-3. **Event Routing**
- - Modified events (now containing S3 references instead of raw LLM data) are published to the standard Kafka topic
- - Events flow through the regular ingestion pipeline without the overhead of processing large LLM payloads
-
-4. **Evaluation Pipeline**
- - A dedicated evaluation service consumes events from the ingestion pipeline's output topic
- - For events requiring LLM context analysis:
- - The service fetches the corresponding blobs from S3 using the stored URLs
- - Performs specialized evaluation and analysis on the LLM interactions
- - Generates new evaluation events with insights and metrics
- - These evaluation events are fed back into the system for further analytics
-
-## Design
-
-### HTTP Endpoint
-
-The `/i/v0/ai` endpoint accepts multipart POST requests with the following structure:
-
-#### Request Format
-
-**Headers:**
-
-- `Content-Type: multipart/form-data; boundary=<boundary>`
-- Standard PostHog authentication headers
-
-**Multipart Parts:**
-
-1. **Event Part** (required)
- - `Content-Disposition: form-data; name="event"` (required)
- - `Content-Type: application/json` (required)
- - Body: Standard PostHog event JSON payload (without properties, or with properties that will be rejected if `event.properties` part is also present)
-
-2. **Event Properties Part** (optional)
- - `Content-Disposition: form-data; name="event.properties"` (required)
- - `Content-Type: application/json` (required)
- - Body: JSON object containing event properties
- - Cannot be used together with embedded properties in the event part (request will be rejected with 400 Bad Request)
- - Properties from this part are merged into the event as the `properties` field
-
-3. **Blob Parts** (optional, multiple allowed)
- - `Content-Disposition: form-data; name="event.properties.<property_name>"; filename="<blob_id>"` (required)
- - `Content-Type: application/octet-stream | application/json | text/plain` (required)
- - Body: Binary blob data
- - The part name follows the JSON path in the event object (e.g., `event.properties.$ai_input_state`)
-
-**Allowed Part Headers:**
-
-- `Content-Disposition` (required for all parts)
-- `Content-Type` (required for all parts)
-- No other headers are supported on individual parts (e.g., `Content-Encoding` is not allowed on parts)
-
-**Note:** Individual parts cannot have their own compression. To compress the entire request payload, use the `Content-Encoding: gzip` header at the HTTP request level.
-
-#### Example Request Structure
-
-```http
-POST /i/v0/ai HTTP/1.1
-Content-Type: multipart/form-data; boundary=----boundary123
-
-------boundary123
-Content-Disposition: form-data; name="event"
-Content-Type: application/json
-
-{
- "event": "$ai_generation",
- "distinct_id": "user_123",
- "timestamp": "2024-01-15T10:30:00Z"
-}
-
-------boundary123
-Content-Disposition: form-data; name="event.properties"
-Content-Type: application/json
-
-{
- "$ai_model": "gpt-4",
- "completion_tokens": 150
-}
-
-------boundary123
-Content-Disposition: form-data; name="event.properties.$ai_input"; filename="blob_abc123"
-Content-Type: application/json
-
-[JSON LLM input data]
-
-------boundary123
-Content-Disposition: form-data; name="event.properties.$ai_output_choices"; filename="blob_def456"
-Content-Type: application/json
-
-[JSON LLM output data]
-
-------boundary123
-Content-Disposition: form-data; name="event.properties.$ai_embedding_vector"; filename="blob_ghi789"
-Content-Type: application/octet-stream
-
-[Binary embedding vector data]
-------boundary123--
-```
-
-#### Boundary Collision Prevention
-
-To prevent LLM data from accidentally containing the multipart boundary sequence:
-
-1. **Client-side**: SDKs should generate a random boundary string and verify it doesn't appear in any blob data before using it
-2. **Server-side**: If a boundary collision is detected during parsing, return a 400 error with instructions to retry with a different boundary
-3. **Alternative**: Use Content-Transfer-Encoding: base64 for blob parts, though this increases payload size by ~33%
-
-#### Processing Flow
-
-1. **Parse multipart request**
- - Validate that the first part is the `event` part
- - Extract event JSON from the "event" part
-
-2. **Handle event properties**
- - If `event.properties` part exists: extract properties JSON from it
- - If embedded properties exist in the event part AND `event.properties` part exists: reject with 400 Bad Request
- - Merge properties into the event (from `event.properties` part if present, otherwise use embedded properties)
-
-3. **Validate event structure**
- - Check event name starts with `$ai_`
- - Verify required fields (distinct_id, properties, etc.)
- - Validate required AI properties (e.g., `$ai_model`)
-
-4. **Collect all blob parts**
- - Extract property path from each part name (e.g., `event.properties.$ai_input`)
- - Store blob data with metadata (property path, content type, size)
- - Check for duplicate blob property names
-
-5. **Validate size limits**
- - Event part ≤ 32KB
- - Event + properties combined ≤ 960KB
- - Sum of all parts ≤ 25MB (configurable)
-
-6. **Create multipart file containing all blobs with index**
-
-7. **Upload single multipart file to S3**
- - Generate S3 key using team_id, event_id, and random string
- - Include blob index in S3 object metadata
-
-8. **Replace blob properties with S3 URLs**
- - Add properties to event with S3 URLs including byte ranges
-
-9. **Send modified event to Kafka**
-
-### S3 Storage
-
-All blobs for an event are stored as a single multipart file in S3:
-
-#### Format
-
-**Multipart/mixed format** - Similar to email MIME, with boundaries separating each blob part
-
-#### Bucket Structure
-
-```text
-s3://<bucket>/
- llma/
- <team_id>/
- <YYYY-MM-DD>/
- <event_id>_<random_string>.multipart
-```
-
-With retention prefixes:
-
-```text
-s3://<bucket>/
- llma/
- <retention>/
- <team_id>/
- <YYYY-MM-DD>/
- <event_id>_<random_string>.multipart
-```
-
-#### Storage Details
-
-- **Bucket**: Dedicated bucket or shared bucket with `llma/` prefix
-- **Partitioning**: By team_id and date for efficient access patterns and lifecycle policies
-- **Object naming**: Combination of event_id and random string
-- **File format**: Contains all blobs for a single event in multipart format
-- **Metadata**: S3 object metadata includes:
- - `team_id`
- - `event_id`
- - `upload_timestamp`
- - `content_type` (multipart/mixed or similar)
- - Index of blob positions within the file
-
-#### Event Property Format
-
-Properties contain S3 URLs with byte range parameters:
-
-```json
-{
- "event": "$ai_generation",
- "properties": {
- "$ai_input": "s3://bucket/llma/123/2024-01-15/event_456_x7y9z.multipart?range=0-50000",
- "$ai_output_choices": "s3://bucket/llma/123/2024-01-15/event_456_x7y9z.multipart?range=50001-75000",
- "model": "gpt-4",
- "completion_tokens": 150
- }
-}
-```
-
-#### Access Patterns
-
-- **Individual blob access**: Use S3 range requests to fetch specific blobs
-- **Full event access**: Download entire multipart file when multiple blobs are needed
-- The evaluation service can optimize by detecting when multiple properties reference the same file
-
-#### Example S3 paths
-
-Without retention prefix (default 30 days):
-
-```text
-s3://posthog-llm-analytics/llma/123/2024-01-15/event_456_x7y9z.multipart
-s3://posthog-llm-analytics/llma/456/2024-01-15/event_789_a3b5c.multipart
-```
-
-With retention prefixes:
-
-```text
-s3://posthog-llm-analytics/llma/30d/123/2024-01-15/event_012_m2n4p.multipart
-s3://posthog-llm-analytics/llma/90d/456/2024-01-15/event_345_q6r8s.multipart
-s3://posthog-llm-analytics/llma/1y/789/2024-01-15/event_678_t1u3v.multipart
-```
-
-#### Access Control
-
-- Write access: Only capture service
-- Read access: Capture service, evaluation service, and authorized backend services
-
-#### Lifecycle Policies
-
-- Default retention: 30 days
-- Optional retention prefixes for different durations (e.g., `30d/`, `90d/`, `1y/`)
-- Since S3 paths are stored in events, retention can be determined at upload time without later computation
-
-### Content Types
-
-#### Supported Content Types for Blob Parts
-
-The following content types are accepted for blob parts:
-
-- `application/octet-stream` - For binary data
-- `application/json` - For JSON formatted LLM context
-- `text/plain` - For plain text LLM inputs/outputs
-
-The event and event.properties parts must use `application/json`.
-
-#### Content Type Handling
-
-- All parts must include a Content-Type header
-- Blob parts with unsupported content types are rejected with 400 Bad Request
-- Blob parts missing Content-Type header are rejected with 400 Bad Request
-- The Content-Type is stored within the multipart file for each part
-- Content-Type is used by the evaluation service to determine how to parse each blob within the multipart file
+- Event part: 32KB (`MAX_EVENT_SIZE`).
+- Event + properties combined: 960KB (`MAX_COMBINED_SIZE`, 1MB minus 64KB of headroom).
+- Request body: 110% of `AI_MAX_SUM_OF_PARTS_BYTES` (default 25MB), enforced by the router's body limit and the streaming body reader.
### Compression
-#### Request-Level Compression
-
-The endpoint supports request-level gzip compression to reduce bandwidth usage:
-
-- **Compression algorithm**: gzip
-- **How to compress**: Add `Content-Encoding: gzip` header to the HTTP request and compress the entire multipart request body
-- **Server behavior**: The capture service will detect the `Content-Encoding: gzip` header and decompress the entire request before processing the multipart data
-- **Recommendation**: SDKs should compress large requests (e.g., > 10KB) to minimize network transfer time
-
-**Example Compressed Request:**
-
-```http
-POST /i/v0/ai HTTP/1.1
-Content-Type: multipart/form-data; boundary=----boundary123
-Content-Encoding: gzip
-
-[Gzipped multipart request body]
-```
-
-The entire multipart body (including all parts) is compressed as a single gzip stream.
-
-#### Server-side Compression (S3 Storage)
-
-For data received from SDKs (after request decompression, if any):
-
-- The capture service will automatically compress the following content types before storing in S3:
- - `application/json`
- - `text/*` (all text subtypes)
-- Binary formats (`application/octet-stream`) will not be automatically compressed
-- Compression is applied before storing in S3
-- S3 object metadata will indicate if server-side compression was applied
-- This compression is transparent to clients and reduces storage costs
-
-## Reliability Concerns
-
-### S3 Upload Reliability
-
-- S3 provides 99.99% uptime SLA, which meets our availability requirements
-- Retry logic can be implemented at multiple layers:
- - In the capture service for failed S3 uploads
- - In the SDKs for failed requests to the capture endpoint
-- Failed uploads should return appropriate error codes to clients for retry
-
-## Security Concerns
-
-### Preventing Malicious Uploads
-
-- All requests to the `/i/v0/ai` endpoint must be authenticated using the project's private API key
-- The capture service validates the API key before processing any multipart data
-- This prevents unauthorized uploads and ensures blob storage is only used by legitimate PostHog projects
-
-### Payload Authentication Implementation
-
-The authentication process for AI observability events follows these steps:
-
-1. **API Key Extraction**
- - Extract the API key from the request headers (e.g., `Authorization: Bearer <api_key>`)
- - API key must be present for all requests to `/i/v0/ai`
-
-2. **Early Validation**
- - Validate the API key format and existence before parsing multipart data
- - Reject requests with missing or malformed keys immediately (400 Bad Request)
-
-3. **Team Resolution**
- - Look up the team associated with the API key
- - Cache team lookups to minimize database queries
- - Return 401 Unauthorized for invalid keys
-
-4. **Request Processing**
- - Only after successful authentication, begin parsing the multipart payload
- - This prevents processing and storing data from unauthenticated requests
- - Team ID from authentication is used for S3 path generation
-
-5. **Error Handling**
- - Authentication failures should not reveal whether a key exists
- - Use consistent error messages to prevent key enumeration attacks
-
-### Tenant Isolation
-
-- S3 paths include team IDs as part of the directory structure
-- Every service accessing S3 must validate that the requesting team has access to the path
-- Services must never allow cross-team access to S3 blobs
-- Path traversal attempts must be detected and blocked
-- Optional: Per-team encryption keys can provide additional isolation by making data cryptographically inaccessible without the correct team's key
-
-### Data Deletion
-
-Three approaches for handling data deletion requests:
-
-1. **S3 Expiry (Passive)**
- - Rely on S3 lifecycle policies to automatically delete expired blobs
- - No immediate action required for deletion requests
- - Simple implementation but data remains accessible until expiry
- - Suitable for compliance requirements with defined retention periods
-
-2. **S3 Delete by Prefix**
- - Use S3's delete by prefix functionality to remove all objects for a team
- - Simple to implement but requires listing and deleting potentially many objects
- - Example: Delete all data for team 123:
-
- ```bash
- aws s3 rm s3://posthog-llm-analytics/llma/123/ --recursive
- ```
-
- Or using S3 API to delete objects with prefix `llma/123/`
-
-3. **Per-Team Encryption**
- - Encrypt blobs with per-team encryption keys
- - Data deletion achieved by deleting the team's encryption key
- - More complex but provides immediate cryptographic deletion
- - Reduces S3 API calls for large-scale deletions
- - Security benefit: accessing data requires fetching the team's encryption key every time
- - Easier to audit and verify that services only access data for the correct team, as key fetching code is centralized
-
-### Payload Schema Verification
-
-The capture service enforces strict validation on incoming events:
-
-1. **Event Name Validation**
- - All events sent to `/i/v0/ai` must have an event name starting with `$ai_`
- - Requests with non-AI events are rejected with 400 Bad Request
- - This ensures the endpoint is only used for its intended purpose
-
-2. **Required Fields**
- - Event must contain standard PostHog event fields (event, properties, timestamp)
- - Properties object must be present, even if empty
-
-3. **Blob Property Validation**
- - Blob part names indicate which properties they populate
- - Blobs cannot overwrite existing properties in the event JSON
- - If a blob targets a property that already exists in the event, the request is rejected
-
-4. **Property Path Validation**
- - Blob part names must match valid property paths in the event JSON
- - Nested property paths are supported (e.g., `event.properties.nested.$ai_input`)
-
-5. **Size Limits**
- All size limit violations return 413 Payload Too Large:
- - **Request body**: Maximum 27.5MB (110% of sum of all parts limit, enforced by Axum)
- - Computed as 110% of `AI_MAX_SUM_OF_PARTS_BYTES` to account for multipart overhead
- - This is the first check, applied before any request processing
- - **Event part**: Maximum 32KB (enforced by handler)
- - **Event + properties combined**: Maximum 960KB (1MB - 64KB, enforced by handler)
- - **Sum of all parts** (event, properties, and all blobs): Maximum 25MB (default, configurable via `AI_MAX_SUM_OF_PARTS_BYTES`, enforced by handler)
- - These limits are configurable via environment variables and can be adjusted per deployment
+`Content-Encoding: gzip` on the whole request body is supported and decompressed before multipart parsing.
+No other encoding is accepted.
-6. **Strict Schema Validation**
- - Each `$ai_` event type has a strictly defined schema
- - Events must conform exactly to their schema - no extra properties allowed
- - Required properties must be present with correct types
- - Blob properties must match expected blob fields for each event type
- - Non-conforming events are rejected with detailed validation errors
+## Processing flow
-## Rejected Solutions
+1. Stream the body in with a timeout, bounded by the body limit.
+2. Validate the Bearer token.
+3. Gunzip if `Content-Encoding: gzip`.
+4. Parse the `event` part only, extracting event name, distinct id, and uuid for the early gates.
+5. Early gates: event restrictions (drop/redirect/force-overflow), token dropper (silent 200), AI-gateway provenance verification, then the quota limiter (`LLMEvents` scoped quota, or the global Events quota for verified gateway events).
+6. Parse the remaining parts and merge properties onto the event.
+7. Validate the full event structure (allowed name, `$ai_model`, distinct id, uuid).
+8. Stamp or strip the `$ai_gateway*` provenance namespace depending on signature verification.
+9. Build the `ProcessedEvent`, apply overflow stamping, and publish to the Kafka sink.
-### WarpStream-based Processing
+Failures after the token parses emit customer-facing ingestion warnings (`invalid_ai_event`, `invalid_ai_payload`) through the mapping in `src/ingestion_warnings/ai.rs`;
+see that module for which rejections warn and which stay silent.
-**Architecture:**
+## Rejections
-- Push entire request payloads (including large LLM content) to WarpStream, which supports large messages
-- A separate service consumes from WarpStream and uploads blobs to S3
-- Events are then forwarded to the regular ingestion pipeline
+`AiRejection` in `src/ai_rejection.rs` is the single vocabulary for customer-caused failures:
+framing problems (not multipart, bad boundary), part problems (missing or duplicated event part, unknown fields, non-UTF-8 or non-JSON payloads), size limits, and AI-contract violations (disallowed event name, missing `$ai_model`).
+Server-side failures (Kafka, serialization) stay `CaptureError` and never surface as customer warnings.
-**Downsides:**
+## History
-- WarpStream is less reliable than S3, reducing overall system availability
-- Additional transfer costs for moving data through WarpStream
-- Additional processing costs for the intermediate service
-- No meaningful batching opportunity - the service would upload files to S3 individually, same as direct upload from capture
-- Adds complexity and another point of failure without significant benefits
+The endpoint originally accepted per-property binary blob parts and stored them in S3 as byte-range-addressed multipart documents, substituting `s3://` URLs into the event properties.
+That capability was an experiment that never shipped to SDKs and was removed;
+the ingestion-side blob offload (content-addressed `phaiblob://` pointers written by the Node AI pipeline) replaced it.
diff --git a/rust/capture/docs/llma-integration-test-suite.md b/rust/capture/docs/llma-integration-test-suite.md
deleted file mode 100644
index 84c11661ca09..000000000000
--- a/rust/capture/docs/llma-integration-test-suite.md
+++ /dev/null
@@ -1,194 +0,0 @@
-# LLMA Integration Test Suite
-
-## Overview
-
-This document describes the Rust integration test suite for the AI observability capture service. These tests validate HTTP endpoint behavior, multipart parsing, and validation logic without requiring external dependencies.
-
-**Implementation Requirement**: Each phase in the implementation plan must pass its corresponding integration tests before proceeding to the next phase. This ensures incremental validation and prevents regression as new features are added.
-
-**See Also**: `llma-acceptance-test-suite.md` for end-to-end tests that require full PostHog infrastructure.
-
-## Test Architecture
-
-### Test Environment
-
-- **In-Memory Router**: Axum router running in test process using `axum-test-helper::TestClient`
-- **Multipart Construction**: Using `reqwest::multipart::Form` to build proper multipart bodies
-- **Mock Dependencies**: Mock Redis, time source, and event sink for isolation
-- **No External Services**: No database, S3, Kafka, or real authentication required
-
-### Test Framework
-
-- **Integration Tests**: Capture service tests from HTTP request through parsing and validation
-- **Parameterized Tests**: Test variations across different event types, blob sizes, and configurations
-- **Async Testing**: Support for testing concurrent requests and large payload processing
-- **Test Utilities**:
- - `CapturingSink`: Mock event sink that stores events in memory for Kafka output verification
- - `FixedTime`: Deterministic time source for reproducible tests
- - `TestSink`: Simple no-op sink for HTTP endpoint tests
-
-### Test Data
-
-- **AI Event Types**: Primarily `$ai_generation` for validation testing
-- **Blob Sizes**: Small (< 1KB), Medium (~100KB), Empty
-- **Content Types**: `application/json`, `text/plain`, `application/octet-stream`
-- **Multipart Boundaries**: Various boundary strings including custom boundaries
-
-## Test Scenarios
-
-**Phase Completion Requirement**: All integration tests for a phase must pass before implementation can proceed to the next phase. This gate ensures quality and prevents compound issues from multiple incomplete features.
-
-### Phase 1: HTTP Endpoint
-
-#### Scenario 1.1: Basic Routing
-
-- **Test**: Verify `/i/v0/ai` endpoint is accessible and returns correct response codes
-- **Validation**: HTTP 200 for valid requests, proper error codes for invalid requests
-- **Tests Implemented**:
- - `test_ai_endpoint_get_returns_405`: GET requests return 405
- - `test_ai_endpoint_put_returns_405`: PUT requests return 405
- - `test_ai_endpoint_delete_returns_405`: DELETE requests return 405
- - `test_ai_endpoint_no_auth_returns_401`: No auth header returns 401
-
-#### Scenario 1.2: Multipart Parsing
-
-- **Test**: Send multipart requests with various boundary strings and blob configurations
-- **Validation**: All parts parsed correctly, blob data extracted without corruption
-- **Variations**: Different boundary formats, multiple blobs, mixed content types
-- **Tests Implemented**:
- - `test_multipart_parsing_with_multiple_blobs`: Parse 4 parts (event + 3 blobs)
- - `test_multipart_parsing_with_mixed_content_types`: JSON, text, binary
- - `test_multipart_parsing_with_large_blob`: Large blob (~100KB)
- - `test_multipart_parsing_with_empty_blob`: Empty blob handling
-
-#### Scenario 1.3: Boundary Validation
-
-- **Test**: Send requests with malformed boundaries, missing boundaries, boundary collisions
-- **Validation**: Appropriate error responses, no server crashes, proper error logging
-- **Tests Implemented**:
- - `test_multipart_missing_boundary_returns_400`: Missing boundary parameter
- - `test_multipart_corrupted_boundary_returns_400`: Mismatched boundary
-
-#### Scenario 1.4: Basic Validation
-
-- **Test**: Send events with valid/invalid event types, missing required properties, duplicate blob properties
-- **Validation**: Only accepted AI event types (`$ai_generation`, `$ai_trace`, `$ai_span`, `$ai_embedding`, `$ai_metric`, `$ai_feedback`) are processed; invalid events rejected with proper error messages
-- **Tests Implemented**:
- - `test_all_allowed_ai_event_types_accepted`: All six accepted event types pass validation
- - `test_invalid_ai_event_type_returns_400`: Invalid AI event types rejected (e.g., `$ai_unknown`, `$ai_custom`)
- - `test_invalid_event_name_not_ai_prefix_returns_400`: Non-AI event names rejected
- - `test_invalid_event_name_regular_event_returns_400`: Regular events rejected (e.g., `$pageview`)
- - `test_invalid_event_name_custom_event_returns_400`: Custom events rejected
- - `test_missing_required_ai_properties_returns_400`: Missing `$ai_model`
- - `test_empty_event_name_returns_400`: Empty event names
- - `test_missing_distinct_id_returns_400`: Missing distinct_id
- - `test_multipart_event_not_first_returns_400`: Event part ordering
-
-#### Scenario 1.5: Content Type Validation
-
-- **Test**: Send requests with wrong content type or empty body
-- **Validation**: Only `multipart/form-data` accepted
-- **Tests Implemented**:
- - `test_ai_endpoint_wrong_content_type_returns_400`: Non-multipart type
- - `test_ai_endpoint_empty_body_returns_400`: Empty body
-
-#### Scenario 1.6: Kafka Publishing and S3 Placeholders
-
-- **Test**: Verify events are correctly published to Kafka with S3 placeholder URLs
-- **Validation**: Events contain S3 placeholders with sequential byte ranges pointing to same file
-- **Tests Implemented**:
- - `test_ai_event_published_to_kafka`: Basic event publishing verification
- - `test_ai_event_with_blobs_published_with_s3_placeholders`: S3 placeholder URL format and sequential ranges
- - `test_ai_event_with_multiple_blobs_sequential_ranges`: Multiple blobs with correct sequential byte ranges
- - `test_ai_event_metadata_preserved_in_kafka`: Event metadata preservation in Kafka
-
-### Phase 5: Authorization
-
-#### Scenario 5.1: Request Signature Verification
-
-- **Test**: Test signature validation for various request formats
-- **Validation**: Valid signatures accepted, invalid signatures rejected
-
-#### Scenario 5.2: Pre-processing Authentication
-
-- **Test**: Verify authentication occurs before multipart parsing
-- **Validation**: Invalid auth rejected immediately, no resource consumption for unauthorized requests
-
-### Phase 7: Compression
-
-#### Scenario 7.1: Client-side Compression
-
-- **Test**: Send pre-compressed blobs with `Content-Encoding: gzip`
-- **Validation**: Compressed blobs stored correctly, decompression works for retrieval
-
-#### Scenario 7.2: Server-side Compression
-
-- **Test**: Send uncompressed JSON/text blobs
-- **Validation**: Server compresses before S3 storage, compression metadata preserved
-
-### Phase 8: Schema Validation
-
-#### Scenario 8.1: Event Schema Validation
-
-- **Test**: Send events conforming to and violating strict schemas for each AI event type
-- **Validation**: Valid events accepted, invalid events rejected with detailed error messages
-- **Variations**: Missing required fields, extra properties, wrong data types
-
-#### Scenario 8.2: Content-Type Validation
-
-- **Test**: Send blobs with various Content-Type headers
-- **Validation**: Supported types accepted, unsupported types handled according to policy
-
-#### Scenario 8.3: Content-Length Validation
-
-- **Test**: Mismatched Content-Length headers and actual blob sizes
-- **Validation**: Mismatches detected and handled appropriately
-
-## Error Recovery and Edge Cases
-
-### Edge Case Scenarios
-
-#### Scenario E.1: Malformed Requests
-
-- **Test**: Invalid JSON, corrupted multipart data, missing required headers
-- **Validation**: Graceful error handling, no server crashes, proper error responses
-
-## Local Development Testing
-
-### Test Implementation
-
-**Location**: `rust/capture/tests/integration_ai_endpoint.rs`
-
-**Framework**: Tokio async tests with `axum-test-helper`
-
-**Dependencies**:
-
-- `reqwest` with `multipart` feature for constructing test requests
-- `axum-test-helper` for in-memory HTTP testing
-- `serde_json` for JSON manipulation
-
-### Running Tests
-
-```bash
-# Run all AI endpoint integration tests
-cargo test --test integration_ai_endpoint
-
-# Run specific test
-cargo test --test integration_ai_endpoint test_multipart_parsing_with_multiple_blobs
-
-# Run with detailed output
-cargo test --test integration_ai_endpoint -- --nocapture
-```
-
-### Test Characteristics
-
-- Run in-memory with no external dependencies
-- Mock Redis, time source, and event sink
-- Fast execution suitable for CI/CD
-- Test HTTP request/response handling only
-
-## Phase Gating
-
-- **Mandatory Testing**: All integration tests for a phase must pass before proceeding to implementation of the next phase
-- **Regression Prevention**: Previous phase tests continue to run to ensure no regression
-- **Incremental Validation**: Each phase builds upon validated functionality from previous phases
diff --git a/rust/capture/src/ai_endpoint.rs b/rust/capture/src/ai_endpoint.rs
index 3d7e060efc38..69e06d66b5c5 100644
--- a/rust/capture/src/ai_endpoint.rs
+++ b/rust/capture/src/ai_endpoint.rs
@@ -7,22 +7,15 @@ use bytes::Bytes;
use common_types::{CapturedEvent, HasEventName};
use futures::stream;
use limiters::redis::QuotaResource;
-use metrics::{counter, histogram};
+use metrics::counter;
use multer::{parse_boundary, Multipart};
use serde::{Deserialize, Serialize};
use serde_json::Value;
-use std::collections::HashSet;
use time::format_description::well_known::Iso8601;
use time::OffsetDateTime;
use tracing::{debug, error, warn};
use uuid::Uuid;
-// Blob metrics
-const AI_BLOB_COUNT_PER_EVENT: &str = "capture_ai_blob_count_per_event";
-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};
@@ -57,29 +50,6 @@ pub struct AIEndpointResponse {
pub accepted_parts: Vec<PartInfo>,
}
-/// A blob part from the multipart request, including headers for S3 storage
-#[derive(Debug)]
-struct BlobPart {
- name: String,
- content_type: Option<String>,
- content_encoding: Option<String>,
- data: Bytes,
-}
-
-/// Insert S3 URLs from uploaded blobs into event properties.
-fn insert_blob_urls_into_properties(
- uploaded: &crate::ai_s3::UploadedBlobs,
- properties: &mut serde_json::Map<String, Value>,
-) {
- for part in &uploaded.parts {
- let url = format!(
- "{}?range={}-{}",
- uploaded.base_url, part.range_start, part.range_end
- );
- properties.insert(part.property_name.clone(), Value::String(url));
- }
-}
-
/// Metadata extracted from the event part for early checks (token dropper, quota)
#[derive(Debug)]
struct EventMetadata {
@@ -110,7 +80,6 @@ impl HasEventName for EventMetadata {
struct RetrievedMultipartParts {
event_json: Value,
properties_json: Value,
- blob_parts: Vec<BlobPart>,
accepted_parts: Vec<PartInfo>,
}
@@ -124,7 +93,6 @@ struct ParsedMultipartData {
event_uuid: Uuid,
timestamp: Option<String>,
sent_at: Option<OffsetDateTime>,
- blob_parts: Vec<BlobPart>,
}
pub async fn ai_handler(
@@ -335,90 +303,11 @@ async fn ai_handler_inner(
};
// Step 5: Retrieve and validate remaining multipart parts (continues parsing from multipart)
- let parts = retrieve_multipart_parts(
- &mut multipart,
- state.ai_max_sum_of_parts_bytes,
- event_metadata,
- )
- .await?;
+ let parts = retrieve_multipart_parts(&mut multipart, event_metadata).await?;
// Step 6: Parse the parts
let mut parsed = parse_multipart_data(parts)?;
- // Step 7: Record blob metrics and upload to S3
- let blob_count = parsed.blob_parts.len();
- if blob_count > 0 {
- // Record blob metrics
- histogram!(AI_BLOB_COUNT_PER_EVENT).record(blob_count as f64);
-
- let mut total_blob_bytes: usize = 0;
- for blob in &parsed.blob_parts {
- let blob_size = blob.data.len();
- total_blob_bytes += blob_size;
- histogram!(AI_BLOB_SIZE_BYTES).record(blob_size as f64);
-
- // Track content type distribution (normalize to known types)
- let content_type = match blob.content_type.as_deref() {
- Some("application/json") => "application/json",
- Some("application/octet-stream") => "application/octet-stream",
- Some(ct) if ct.starts_with("text/plain") => "text/plain",
- Some(_) => "other",
- None => "unknown",
- };
- counter!(AI_BLOB_EVENTS_TOTAL, "has_blobs" => "true", "content_type" => content_type)
- .increment(1);
- }
- histogram!(AI_BLOB_TOTAL_BYTES_PER_EVENT).record(total_blob_bytes as f64);
- } else {
- counter!(AI_BLOB_EVENTS_TOTAL, "has_blobs" => "false", "content_type" => "none")
- .increment(1);
- }
-
- // Upload blobs to S3 and insert URLs into event properties
- if !parsed.blob_parts.is_empty() {
- let blob_storage = state.ai_blob_storage.as_ref().ok_or_else(|| {
- error!("AI endpoint received blobs but S3 is not configured");
- CaptureError::ServiceUnavailable("blob storage not configured".to_string())
- })?;
-
- // Convert blob_parts to format expected by AiBlobStorage
- let blobs: Vec<crate::ai_s3::BlobData> = parsed
- .blob_parts
- .iter()
- .filter_map(|bp| {
- bp.name
- .strip_prefix("event.properties.")
- .map(|prop_name| crate::ai_s3::BlobData {
- property_name: prop_name.to_string(),
- content_type: bp.content_type.clone(),
- content_encoding: bp.content_encoding.clone(),
- data: bp.data.clone(),
- })
- })
- .collect();
-
- // Upload blobs and get URLs
- // TODO: Replace token with team_id once secret key signing is implemented
- // and we can resolve tokens to team IDs in capture
- let uploaded = blob_storage
- .upload_blobs(token, &parsed.event_uuid.to_string(), blobs)
- .await
- .map_err(|e| {
- warn!("Failed to upload blobs to S3: {:?}", e);
- CaptureError::NonRetryableSinkError
- })?;
-
- // Insert S3 URLs into event properties
- if let Some(properties) = parsed
- .event
- .as_object_mut()
- .and_then(|obj| obj.get_mut("properties"))
- .and_then(|p| p.as_object_mut())
- {
- insert_blob_urls_into_properties(&uploaded, properties);
- }
- }
-
// AI-gateway provenance: stamp the trusted marker (overwriting client values) on a
// verified event, else strip the whole $ai_gateway* namespace so a forged marker
// can't reach billing. The verified metric always fires; the strip metric only fires
@@ -592,15 +481,6 @@ async fn retrieve_event_metadata(
})
}
-/// Validate blob part content type
-fn is_valid_blob_content_type(content_type: &str) -> bool {
- // Supported content types for blob parts
- content_type == "application/octet-stream"
- || content_type == "application/json"
- || content_type == "text/plain"
- || content_type.starts_with("text/plain;") // Allow text/plain with charset
-}
-
/// Build a Kafka event from parsed multipart data
fn build_kafka_event(
parsed: ParsedMultipartData,
@@ -758,60 +638,11 @@ fn process_properties_part(
Ok((properties_json, part_info))
}
-/// Process a blob part
-fn process_blob_part(
- field_name: String,
- field_data: Bytes,
- content_type: Option<String>,
- content_encoding: Option<String>,
-) -> 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(AiRejection::BlobContentTypeUnsupported {
- field: field_name,
- content_type: ct.clone(),
- });
- }
- } else {
- return Err(AiRejection::BlobContentTypeMissing(field_name));
- }
-
- // Get length before moving data
- let field_data_len = field_data.len();
-
- // Reject empty blobs
- if field_data_len == 0 {
- return Err(AiRejection::BlobEmpty(field_name));
- }
-
- // Create part info (clones needed for response)
- let part_info = PartInfo {
- name: field_name.clone(),
- length: field_data_len,
- content_type: content_type.clone(),
- content_encoding: content_encoding.clone(),
- };
-
- // Create blob part - moves field_name, field_data, includes headers for S3 storage
- let blob_part = BlobPart {
- name: field_name,
- content_type,
- content_encoding,
- data: field_data, // MOVE - no clone of actual blob data!
- };
-
- debug!("Blob part processed successfully");
- Ok((blob_part, part_info))
-}
-
/// Retrieve and validate multipart parts from the request body.
/// The event metadata (first part) has already been parsed by retrieve_event_metadata.
/// Continues parsing from where retrieve_event_metadata left off.
async fn retrieve_multipart_parts(
multipart: &mut Multipart<'_>,
- max_sum_of_parts_bytes: usize,
event_metadata: EventMetadata,
) -> Result<RetrievedMultipartParts, AiRejection> {
// Size limits
@@ -819,12 +650,9 @@ async fn retrieve_multipart_parts(
let mut part_count = 0;
let mut accepted_parts = Vec::new();
- let mut seen_property_names = HashSet::new();
- let mut blob_parts: Vec<BlobPart> = Vec::new();
let mut properties_json: Option<Value> = None;
let event_size: usize = event_metadata.event_part_info.length;
let mut properties_size: usize = 0;
- let mut sum_of_parts_bytes: usize = event_size;
// Add the pre-parsed event part info
accepted_parts.push(event_metadata.event_part_info);
@@ -862,9 +690,6 @@ async fn retrieve_multipart_parts(
.await
.map_err(|e| AiRejection::FieldDataUnreadable(e.to_string()))?;
- // Track sum of all part sizes
- sum_of_parts_bytes += field_data.len();
-
// Process based on field name
if field_name == "event.properties" {
properties_size = field_data.len();
@@ -872,30 +697,7 @@ async fn retrieve_multipart_parts(
process_properties_part(field_data, content_type, content_encoding)?;
properties_json = Some(properties);
accepted_parts.push(part_info);
- } else if let Some(property_name) = field_name.strip_prefix("event.properties.") {
- // 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(AiRejection::BlobPropertyNested(field_name));
- }
-
- // Check for duplicates before processing
- if seen_property_names.contains(&field_name) {
- return Err(AiRejection::BlobPropertyDuplicate(field_name));
- }
-
- let (blob_part, part_info) = process_blob_part(
- field_name.clone(),
- field_data,
- content_type,
- content_encoding,
- )?;
-
- seen_property_names.insert(field_name);
- blob_parts.push(blob_part);
- accepted_parts.push(part_info);
} else {
- // Reject unknown fields that don't match expected patterns
return Err(AiRejection::UnknownField(field_name));
}
}
@@ -909,14 +711,6 @@ async fn retrieve_multipart_parts(
});
}
- // Check sum of all parts limit
- if sum_of_parts_bytes > max_sum_of_parts_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
let event = event_metadata.event_json;
@@ -944,22 +738,16 @@ async fn retrieve_multipart_parts(
.unwrap_or(serde_json::json!({}))
};
- debug!(
- "Multipart parts retrieved: {} parts processed, {} blob parts found",
- part_count,
- blob_parts.len()
- );
+ debug!("Multipart parts retrieved: {part_count} parts processed");
Ok(RetrievedMultipartParts {
event_json: event,
properties_json: final_properties,
- blob_parts,
accepted_parts,
})
}
/// Parse retrieved multipart parts and validate event structure.
-/// Returns parsed data with blob_parts for later S3 upload.
fn parse_multipart_data(
parts: RetrievedMultipartParts,
) -> Result<ParsedMultipartData, AiRejection> {
@@ -1012,11 +800,6 @@ fn parse_multipart_data(
.and_then(|v| v.as_str())
.and_then(|sent_at_str| OffsetDateTime::parse(sent_at_str, &Iso8601::DEFAULT).ok());
- debug!(
- "Multipart parsing completed: {} blob parts",
- parts.blob_parts.len()
- );
-
Ok(ParsedMultipartData {
accepted_parts: parts.accepted_parts,
event,
@@ -1025,7 +808,6 @@ fn parse_multipart_data(
event_uuid,
timestamp,
sent_at,
- blob_parts: parts.blob_parts,
})
}
@@ -1085,41 +867,3 @@ fn validate_event_structure(event: &Value) -> Result<(), AiRejection> {
Ok(())
}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use crate::ai_s3::{BlobPartRange, UploadedBlobs};
-
- #[test]
- fn test_insert_blob_urls_into_properties() {
- let uploaded = UploadedBlobs {
- base_url: "s3://capture/llma/phc_test_token/abc-def".to_string(),
- boundary: "----posthog-ai-abc-def".to_string(),
- parts: vec![
- BlobPartRange {
- property_name: "$ai_input".to_string(),
- range_start: 0,
- range_end: 99,
- },
- BlobPartRange {
- property_name: "$ai_output".to_string(),
- range_start: 100,
- range_end: 249,
- },
- ],
- };
-
- let mut properties = serde_json::Map::new();
- insert_blob_urls_into_properties(&uploaded, &mut properties);
-
- assert_eq!(
- properties.get("$ai_input").unwrap().as_str().unwrap(),
- "s3://capture/llma/phc_test_token/abc-def?range=0-99"
- );
- assert_eq!(
- properties.get("$ai_output").unwrap().as_str().unwrap(),
- "s3://capture/llma/phc_test_token/abc-def?range=100-249"
- );
- }
-}
diff --git a/rust/capture/src/ai_rejection.rs b/rust/capture/src/ai_rejection.rs
index 2187375ecc6a..36f022e45507 100644
--- a/rust/capture/src/ai_rejection.rs
+++ b/rust/capture/src/ai_rejection.rs
@@ -41,9 +41,9 @@ enum ErrorKind {
/// 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.
+/// Server-side failures (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
@@ -67,17 +67,9 @@ pub enum AiRejection {
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,
@@ -113,7 +105,7 @@ impl AiRejection {
}
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>'"
+ "Unknown multipart field: '{field_name}'. Expected 'event' or 'event.properties'"
),
Self::EventPartNotUtf8 => "Event part must be valid UTF-8".to_string(),
@@ -128,34 +120,12 @@ impl AiRejection {
}
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(),
@@ -185,9 +155,9 @@ impl AiRejection {
| Self::MultipartParseFailed(_)
| Self::FieldDataUnreadable(_) => ErrorKind::Decoding,
- Self::EventPartTooBig { .. }
- | Self::EventAndPropertiesTooBig { .. }
- | Self::SumOfPartsTooBig { .. } => ErrorKind::TooBig,
+ Self::EventPartTooBig { .. } | Self::EventAndPropertiesTooBig { .. } => {
+ ErrorKind::TooBig
+ }
Self::MissingEventPart
| Self::FirstPartNotEvent(_)
@@ -200,11 +170,6 @@ impl AiRejection {
| Self::PropertiesPartNotJson
| Self::ConflictingProperties
| Self::EventMissingProperties
- | Self::BlobContentTypeMissing(_)
- | Self::BlobContentTypeUnsupported { .. }
- | Self::BlobEmpty(_)
- | Self::BlobPropertyNested(_)
- | Self::BlobPropertyDuplicate(_)
| Self::EventMissingName
| Self::EventNameRequired
| Self::EventNameEmpty
@@ -267,7 +232,7 @@ pub(crate) fn all_variants_with_messages() -> Vec<(AiRejection, &'static str)> {
),
(
AiRejection::UnknownField("nope".to_string()),
- "Unknown multipart field: 'nope'. Expected 'event', 'event.properties', or 'event.properties.<property_name>'",
+ "Unknown multipart field: 'nope'. Expected 'event' or 'event.properties'",
),
(
AiRejection::EventPartNotUtf8,
@@ -294,29 +259,6 @@ pub(crate) fn all_variants_with_messages() -> Vec<(AiRejection, &'static str)> {
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,
@@ -331,13 +273,6 @@ pub(crate) fn all_variants_with_messages() -> Vec<(AiRejection, &'static str)> {
},
"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",
@@ -460,7 +395,7 @@ mod tests {
);
assert_eq!(
listed.len(),
- 35,
+ 29,
"variant count changed — add the new variant to all_variants_with_messages \
and update this expected count"
);
@@ -476,12 +411,10 @@ mod tests {
#[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();
diff --git a/rust/capture/src/ai_s3.rs b/rust/capture/src/ai_s3.rs
deleted file mode 100644
index 17fd6b9bf153..000000000000
--- a/rust/capture/src/ai_s3.rs
+++ /dev/null
@@ -1,605 +0,0 @@
-use async_trait::async_trait;
-use bytes::{BufMut, Bytes, BytesMut};
-use rand::Rng;
-use sha2::{Digest, Sha256};
-
-use crate::s3_client::{S3Client, S3Error};
-
-/// Hash a token for use in S3 keys.
-/// This prevents path traversal attacks from malicious tokens containing "../" or "/".
-/// Returns first 16 hex characters (64 bits) which is sufficient for this use case.
-fn hash_token(token: &str) -> String {
- let mut hasher = Sha256::new();
- hasher.update(token.as_bytes());
- format!("{:x}", hasher.finalize())[..16].to_string()
-}
-
-/// A blob to upload with its metadata.
-pub struct BlobData {
- pub property_name: String,
- pub content_type: Option<String>,
- pub content_encoding: Option<String>,
- pub data: Bytes,
-}
-
-/// Result of uploading blobs, containing the base URL and part metadata for generating URLs.
-pub struct UploadedBlobs {
- /// Base S3 URL without range parameter (e.g., "s3://bucket/prefix/team/uuid")
- pub base_url: String,
- /// Boundary string used in the multipart document
- pub boundary: String,
- /// Blob parts in order, with their byte ranges
- pub parts: Vec<BlobPartRange>,
-}
-
-/// A blob part with its byte range in the multipart file.
-/// The range includes the boundary, headers, and body - a complete single-part multipart document.
-pub struct BlobPartRange {
- pub property_name: String,
- pub range_start: usize,
- pub range_end: usize,
-}
-
-/// Trait for blob storage implementations.
-/// Allows mocking in tests via dynamic dispatch.
-#[async_trait]
-pub trait BlobStorage: Send + Sync {
- /// Upload multiple blobs as a multipart/mixed document.
- /// Returns metadata for generating S3 URLs with byte ranges.
- /// Each range extracts a complete single-part multipart document.
- async fn upload_blobs(
- &self,
- token: &str,
- event_uuid: &str,
- blobs: Vec<BlobData>,
- ) -> Result<UploadedBlobs, S3Error>;
-}
-
-/// AI-specific blob storage that handles multipart/mixed format and URL generation.
-pub struct AiBlobStorage {
- s3_client: S3Client,
- prefix: String,
-}
-
-impl AiBlobStorage {
- pub fn new(s3_client: S3Client, prefix: String) -> Self {
- Self { s3_client, prefix }
- }
-}
-
-/// Generate a unique boundary for multipart document.
-/// Includes event UUID and random suffix to prevent collisions with content.
-fn generate_boundary(event_uuid: &str) -> String {
- let suffix: String = rand::thread_rng()
- .sample_iter(&rand::distributions::Alphanumeric)
- .take(8)
- .map(char::from)
- .collect();
- format!("----posthog-ai-{event_uuid}-{suffix}")
-}
-
-/// Write multipart part headers and body directly into the buffer.
-/// Does NOT write boundaries - those are handled by build_multipart_document.
-/// Returns the number of bytes written.
-///
-/// Format:
-/// Content-Disposition: form-data; name="property_name"\r\n
-/// Content-Type: content_type\r\n
-/// [Content-Encoding: encoding\r\n]
-/// \r\n
-/// <body>\r\n
-fn write_multipart_part(
- buffer: &mut BytesMut,
- property_name: &str,
- content_type: &str,
- content_encoding: Option<&str>,
- body: &[u8],
-) -> usize {
- let start_len = buffer.len();
-
- // Content-Disposition header
- buffer.put_slice(b"Content-Disposition: form-data; name=\"");
- buffer.put_slice(property_name.as_bytes());
- buffer.put_slice(b"\"\r\n");
-
- // Content-Type header (always present)
- buffer.put_slice(b"Content-Type: ");
- buffer.put_slice(content_type.as_bytes());
- buffer.put_slice(b"\r\n");
-
- // Optional Content-Encoding header
- if let Some(encoding) = content_encoding {
- buffer.put_slice(b"Content-Encoding: ");
- buffer.put_slice(encoding.as_bytes());
- buffer.put_slice(b"\r\n");
- }
-
- // End of headers
- buffer.put_slice(b"\r\n");
-
- // Body
- buffer.put_slice(body);
- buffer.put_slice(b"\r\n");
-
- buffer.len() - start_len
-}
-
-/// Write an opening boundary to the buffer.
-fn write_opening_boundary(buffer: &mut BytesMut, boundary: &str) {
- buffer.put_slice(b"--");
- buffer.put_slice(boundary.as_bytes());
- buffer.put_slice(b"\r\n");
-}
-
-/// Write the closing boundary to the buffer.
-fn write_closing_boundary(buffer: &mut BytesMut, boundary: &str) {
- buffer.put_slice(b"--");
- buffer.put_slice(boundary.as_bytes());
- buffer.put_slice(b"--\r\n");
-}
-
-/// Result of building a complete multipart document.
-struct BuiltDocument {
- /// The complete multipart document bytes
- data: Bytes,
- /// Boundary used in the document
- boundary: String,
- /// Byte ranges for each part (property_name, start, end inclusive)
- parts: Vec<BlobPartRange>,
-}
-
-/// Build a complete multipart document from multiple blobs.
-///
-/// The document format is:
-/// --boundary\r\n<part1_headers_and_body>\r\n--boundary\r\n<part2_headers_and_body>\r\n--boundary--\r\n
-///
-/// Each part's byte range includes headers and body but excludes boundaries.
-/// Clients can parse the extracted range as HTTP-style headers + body.
-fn build_multipart_document(event_uuid: &str, blobs: Vec<BlobData>) -> BuiltDocument {
- let boundary = generate_boundary(event_uuid);
-
- // Pre-allocate capacity to avoid reallocations.
- // Per-blob overhead (~200 bytes): boundary, headers, CRLF sequences.
- // Plus ~100 bytes for closing boundary.
- let blob_data_size: usize = blobs.iter().map(|b| b.data.len()).sum();
- let estimated_capacity = blob_data_size + (blobs.len() * 200) + 100;
- let mut document = BytesMut::with_capacity(estimated_capacity);
- let mut parts = Vec::with_capacity(blobs.len());
-
- for blob in &blobs {
- // Write opening boundary
- write_opening_boundary(&mut document, &boundary);
-
- // Record start position (after boundary, at headers)
- let range_start = document.len();
-
- let content_type = blob
- .content_type
- .as_deref()
- .unwrap_or("application/octet-stream");
-
- // Write headers and body (no boundaries)
- write_multipart_part(
- &mut document,
- &blob.property_name,
- content_type,
- blob.content_encoding.as_deref(),
- &blob.data,
- );
-
- // Range ends before the trailing \r\n that precedes the next boundary
- // write_multipart_part ends with body + \r\n, we want to exclude that \r\n
- let range_end = document.len() - 3; // -1 for inclusive, -2 for \r\n
-
- parts.push(BlobPartRange {
- property_name: blob.property_name.clone(),
- range_start,
- range_end,
- });
- }
-
- // Write closing boundary at the end
- write_closing_boundary(&mut document, &boundary);
-
- BuiltDocument {
- data: document.freeze(),
- boundary,
- parts,
- }
-}
-
-#[async_trait]
-impl BlobStorage for AiBlobStorage {
- /// Upload multiple blobs as a multipart/mixed document.
- /// Each blob becomes a standalone part that can be extracted via byte range.
- ///
- /// `token` is used as the partition key in the S3 path.
- /// TODO: Replace with team_id once secret key signing is implemented.
- async fn upload_blobs(
- &self,
- token: &str,
- event_uuid: &str,
- blobs: Vec<BlobData>,
- ) -> Result<UploadedBlobs, S3Error> {
- if blobs.is_empty() {
- return Ok(UploadedBlobs {
- base_url: String::new(),
- boundary: String::new(),
- parts: vec![],
- });
- }
-
- let doc = build_multipart_document(event_uuid, blobs);
-
- // Upload with multipart/mixed content type
- // Hash the token to prevent path traversal attacks from malicious input
- let token_hash = hash_token(token);
- let key = format!("{}{}/{}", self.prefix, token_hash, event_uuid);
- let content_type = format!("multipart/mixed; boundary={}", doc.boundary);
- self.s3_client
- .put_object(&key, doc.data, &content_type)
- .await?;
-
- let base_url = format!("s3://{}/{}", self.s3_client.bucket(), key);
-
- Ok(UploadedBlobs {
- base_url,
- boundary: doc.boundary,
- parts: doc.parts,
- })
- }
-}
-
-/// Mock blob storage for testing.
-/// Returns predictable S3 URLs without actually uploading.
-pub struct MockBlobStorage {
- bucket: String,
- prefix: String,
-}
-
-impl MockBlobStorage {
- pub fn new(bucket: String, prefix: String) -> Self {
- Self { bucket, prefix }
- }
-}
-
-#[async_trait]
-impl BlobStorage for MockBlobStorage {
- async fn upload_blobs(
- &self,
- token: &str,
- event_uuid: &str,
- blobs: Vec<BlobData>,
- ) -> Result<UploadedBlobs, S3Error> {
- if blobs.is_empty() {
- return Ok(UploadedBlobs {
- base_url: String::new(),
- boundary: String::new(),
- parts: vec![],
- });
- }
-
- // Build document to get correct byte ranges (data is discarded for mock)
- let doc = build_multipart_document(event_uuid, blobs);
-
- let token_hash = hash_token(token);
- let key = format!("{}{}/{}", self.prefix, token_hash, event_uuid);
- let base_url = format!("s3://{}/{}", self.bucket, key);
-
- Ok(UploadedBlobs {
- base_url,
- boundary: doc.boundary,
- parts: doc.parts,
- })
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn test_multipart_part_format() {
- let mut buffer = BytesMut::new();
- let bytes_written = write_multipart_part(
- &mut buffer,
- "$ai_input",
- "application/json",
- None,
- b"{\"test\": true}",
- );
-
- let expected = concat!(
- "Content-Disposition: form-data; name=\"$ai_input\"\r\n",
- "Content-Type: application/json\r\n",
- "\r\n",
- "{\"test\": true}\r\n",
- );
-
- assert_eq!(String::from_utf8_lossy(&buffer), expected);
- assert_eq!(bytes_written, buffer.len());
- }
-
- #[test]
- fn test_multipart_part_with_encoding() {
- let mut buffer = BytesMut::new();
- let bytes_written = write_multipart_part(
- &mut buffer,
- "$ai_output",
- "text/plain",
- Some("gzip"),
- b"compressed data",
- );
-
- let expected = concat!(
- "Content-Disposition: form-data; name=\"$ai_output\"\r\n",
- "Content-Type: text/plain\r\n",
- "Content-Encoding: gzip\r\n",
- "\r\n",
- "compressed data\r\n",
- );
-
- assert_eq!(String::from_utf8_lossy(&buffer), expected);
- assert_eq!(bytes_written, buffer.len());
- }
-
- #[test]
- fn test_write_returns_correct_size() {
- let mut buffer = BytesMut::new();
-
- let bytes_written = write_multipart_part(
- &mut buffer,
- "$ai_input",
- "application/json",
- Some("gzip"),
- b"test body content",
- );
-
- assert_eq!(bytes_written, buffer.len());
- }
-
- #[test]
- fn test_s3_url_format() {
- let bucket = "capture";
- let prefix = "llma/";
- let token = "phc_test_token";
- let event_uuid = "550e8400-e29b-41d4-a716-446655440000";
-
- let token_hash = hash_token(token);
- let key = format!("{prefix}{token_hash}/{event_uuid}");
- let url = format!("s3://{bucket}/{key}");
-
- // Token is hashed (first 16 chars) to prevent path traversal attacks
- assert_eq!(token_hash, "0f25663a3e84ea94");
- assert_eq!(
- url,
- "s3://capture/llma/0f25663a3e84ea94/550e8400-e29b-41d4-a716-446655440000"
- );
- }
-
- #[test]
- fn test_hash_token_prevents_path_traversal() {
- // Malicious tokens with path traversal attempts should be safely hashed
- let malicious_tokens = [
- "../../../etc/passwd",
- "phc_test/../other_customer",
- "token/with/slashes",
- "token\0with\0nulls",
- ];
-
- for token in malicious_tokens {
- let hashed = hash_token(token);
- // Hash should be 16 hex characters (first 64 bits of SHA-256)
- assert_eq!(hashed.len(), 16);
- // Hash should only contain hex characters (safe for S3 keys)
- assert!(hashed.chars().all(|c| c.is_ascii_hexdigit()));
- }
- }
-
- #[test]
- fn test_boundary_generation() {
- let uuid = "550e8400-e29b-41d4-a716-446655440000";
- let boundary = generate_boundary(uuid);
-
- // Should start with prefix and contain event UUID
- assert!(boundary.starts_with("----posthog-ai-550e8400-e29b-41d4-a716-446655440000-"));
- // Should have 8-char random suffix
- let expected_prefix = "----posthog-ai-550e8400-e29b-41d4-a716-446655440000-";
- assert_eq!(boundary.len(), expected_prefix.len() + 8);
-
- // Each call should generate different boundary
- let boundary2 = generate_boundary(uuid);
- assert_ne!(boundary, boundary2);
- }
-
- /// Helper to parse all parts from bytes using multer
- async fn parse_all_parts(data: Bytes, boundary: &str) -> Vec<(String, String, Bytes)> {
- use multer::Multipart;
-
- let stream = futures::stream::once(async move { Ok::<_, std::io::Error>(data) });
- let mut multipart = Multipart::new(stream, boundary);
-
- let mut parts = Vec::new();
- while let Some(field) = multipart.next_field().await.unwrap() {
- let name = field.name().unwrap().to_string();
- let content_type = field.content_type().map(|m| m.to_string()).unwrap();
- let body = field.bytes().await.unwrap();
- parts.push((name, content_type, body));
- }
-
- parts
- }
-
- /// Helper to parse MIME part (headers + body) using httparse
- fn parse_mime_part(data: &[u8]) -> (std::collections::HashMap<String, String>, &[u8]) {
- // httparse requires a mutable array of Header structs
- let mut header_buf = [httparse::EMPTY_HEADER; 16];
-
- // Parse headers (httparse expects request/response format, so we parse as headers only)
- let status =
- httparse::parse_headers(data, &mut header_buf).expect("Failed to parse headers");
-
- let (header_len, parsed_headers) = match status {
- httparse::Status::Complete((len, headers)) => (len, headers),
- httparse::Status::Partial => panic!("Incomplete headers in MIME part"),
- };
-
- // Build headers map
- let mut headers = std::collections::HashMap::new();
- for header in parsed_headers {
- let name = header.name.to_lowercase();
- let value = std::str::from_utf8(header.value)
- .expect("Invalid UTF-8 in header value")
- .to_string();
- headers.insert(name, value);
- }
-
- // Body starts after headers
- let body = &data[header_len..];
-
- (headers, body)
- }
-
- #[tokio::test]
- async fn test_single_part_document() {
- let event_uuid = "test-event-uuid";
- let body_content = b"{\"messages\": [{\"role\": \"user\", \"content\": \"Hello\"}]}";
-
- let doc = build_multipart_document(
- event_uuid,
- vec![BlobData {
- property_name: "$ai_input".to_string(),
- content_type: Some("application/json".to_string()),
- content_encoding: None,
- data: Bytes::from_static(body_content),
- }],
- );
-
- // Should have one part
- assert_eq!(doc.parts.len(), 1);
- assert_eq!(doc.parts[0].property_name, "$ai_input");
-
- // Full document should parse as valid multipart
- let parts = parse_all_parts(doc.data.clone(), &doc.boundary).await;
- assert_eq!(parts.len(), 1);
- assert_eq!(parts[0].0, "$ai_input");
- assert_eq!(parts[0].1, "application/json");
- assert_eq!(parts[0].2.as_ref(), body_content);
-
- // Extract by range - should get headers + body (no boundaries)
- let range = doc.parts[0].range_start..=doc.parts[0].range_end;
- let extracted = doc.data.slice(range);
-
- let (headers, body) = parse_mime_part(&extracted);
- assert_eq!(
- headers.get("content-disposition").unwrap(),
- "form-data; name=\"$ai_input\""
- );
- assert_eq!(headers.get("content-type").unwrap(), "application/json");
- assert_eq!(body, body_content);
- }
-
- #[tokio::test]
- async fn test_multiple_parts_document_extract_each_by_range() {
- let event_uuid = "test-event-uuid";
-
- let doc = build_multipart_document(
- event_uuid,
- vec![
- BlobData {
- property_name: "$ai_input".to_string(),
- content_type: Some("application/json".to_string()),
- content_encoding: None,
- data: Bytes::from_static(b"{\"q\": 1}"),
- },
- BlobData {
- property_name: "$ai_output".to_string(),
- content_type: Some("text/plain".to_string()),
- content_encoding: None,
- data: Bytes::from_static(b"response text"),
- },
- BlobData {
- property_name: "$ai_metadata".to_string(),
- content_type: Some("application/json".to_string()),
- content_encoding: None,
- data: Bytes::from_static(b"{\"tokens\": 100}"),
- },
- ],
- );
-
- // Should have three parts with non-overlapping ranges
- assert_eq!(doc.parts.len(), 3);
- assert_eq!(doc.parts[0].property_name, "$ai_input");
- assert_eq!(doc.parts[1].property_name, "$ai_output");
- assert_eq!(doc.parts[2].property_name, "$ai_metadata");
-
- // Ranges should not overlap
- assert!(doc.parts[0].range_end < doc.parts[1].range_start);
- assert!(doc.parts[1].range_end < doc.parts[2].range_start);
-
- // Full document should parse as valid multipart
- let parts = parse_all_parts(doc.data.clone(), &doc.boundary).await;
- assert_eq!(parts.len(), 3);
- assert_eq!(parts[0].2.as_ref(), b"{\"q\": 1}");
- assert_eq!(parts[1].2.as_ref(), b"response text");
- assert_eq!(parts[2].2.as_ref(), b"{\"tokens\": 100}");
-
- // Extract each part by range - should get headers + body (no boundaries)
- let extracted1 = doc
- .data
- .slice(doc.parts[0].range_start..=doc.parts[0].range_end);
- let (headers, body) = parse_mime_part(&extracted1);
- assert!(headers
- .get("content-disposition")
- .unwrap()
- .contains("$ai_input"));
- assert_eq!(headers.get("content-type").unwrap(), "application/json");
- assert_eq!(body, b"{\"q\": 1}");
-
- let extracted2 = doc
- .data
- .slice(doc.parts[1].range_start..=doc.parts[1].range_end);
- let (headers, body) = parse_mime_part(&extracted2);
- assert!(headers
- .get("content-disposition")
- .unwrap()
- .contains("$ai_output"));
- assert_eq!(headers.get("content-type").unwrap(), "text/plain");
- assert_eq!(body, b"response text");
-
- let extracted3 = doc
- .data
- .slice(doc.parts[2].range_start..=doc.parts[2].range_end);
- let (headers, body) = parse_mime_part(&extracted3);
- assert!(headers
- .get("content-disposition")
- .unwrap()
- .contains("$ai_metadata"));
- assert_eq!(headers.get("content-type").unwrap(), "application/json");
- assert_eq!(body, b"{\"tokens\": 100}");
- }
-
- #[tokio::test]
- async fn test_content_type_defaults_to_octet_stream() {
- let event_uuid = "test-event-uuid";
-
- let doc = build_multipart_document(
- event_uuid,
- vec![BlobData {
- property_name: "$ai_data".to_string(),
- content_type: None, // No content type specified
- content_encoding: None,
- data: Bytes::from_static(b"binary data"),
- }],
- );
-
- let extracted = doc
- .data
- .slice(doc.parts[0].range_start..=doc.parts[0].range_end);
- let (headers, _) = parse_mime_part(&extracted);
- assert_eq!(
- headers.get("content-type").unwrap(),
- "application/octet-stream"
- );
- }
-}
diff --git a/rust/capture/src/config.rs b/rust/capture/src/config.rs
index 43d5b360cfac..a03a2a8817ec 100644
--- a/rust/capture/src/config.rs
+++ b/rust/capture/src/config.rs
@@ -270,16 +270,6 @@ pub struct Config {
#[envconfig(default = "26214400")] // 25MB in bytes
pub ai_max_sum_of_parts_bytes: usize,
- // AI endpoint S3 blob storage configuration
- pub ai_s3_bucket: Option<String>,
- #[envconfig(default = "llma/")]
- pub ai_s3_prefix: String,
- pub ai_s3_endpoint: Option<String>,
- #[envconfig(default = "us-east-1")]
- pub ai_s3_region: String,
- pub ai_s3_access_key_id: Option<String>,
- pub ai_s3_secret_access_key: Option<String>,
-
// HMAC-SHA256 key shared with the AI gateway. When set, $ai_generation events
// carrying a valid PostHog-Ai-Gateway-* signature are stamped verified and
// exempted from the llm_events quota limiter. Unset disables verification
diff --git a/rust/capture/src/ingestion_warnings/ai.rs b/rust/capture/src/ingestion_warnings/ai.rs
index 7eec6d92a742..a58cf64ede45 100644
--- a/rust/capture/src/ingestion_warnings/ai.rs
+++ b/rust/capture/src/ingestion_warnings/ai.rs
@@ -47,9 +47,9 @@ pub fn warning_for_ai_rejection(rejection: &AiRejection) -> Option<WarningType>
| AiRejection::DistinctIdEmpty => Some(WarningType::MissingDistinctId),
AiRejection::EventUuidRequired => Some(WarningType::MissingEventUuid),
AiRejection::EventUuidInvalid(_) => Some(WarningType::InvalidEventUuid),
- AiRejection::EventPartTooBig { .. }
- | AiRejection::EventAndPropertiesTooBig { .. }
- | AiRejection::SumOfPartsTooBig { .. } => Some(WarningType::MessageSizeTooLarge),
+ AiRejection::EventPartTooBig { .. } | AiRejection::EventAndPropertiesTooBig { .. } => {
+ Some(WarningType::MessageSizeTooLarge)
+ }
// The properties object specifically is missing or unreadable.
AiRejection::EventMissingProperties
@@ -66,12 +66,7 @@ pub fn warning_for_ai_rejection(rejection: &AiRejection) -> Option<WarningType>
| AiRejection::EventPartNotUtf8
| AiRejection::EventPartNotJson
| AiRejection::EventNotObject
- | AiRejection::ConflictingProperties
- | AiRejection::BlobContentTypeMissing(_)
- | AiRejection::BlobContentTypeUnsupported { .. }
- | AiRejection::BlobEmpty(_)
- | AiRejection::BlobPropertyNested(_)
- | AiRejection::BlobPropertyDuplicate(_) => Some(WarningType::InvalidAiPayload),
+ | AiRejection::ConflictingProperties => 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
@@ -123,8 +118,8 @@ fn warning_for_ai_failure(
}
// 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.
+ // billing, and Kafka and serialization failures are not the customer's
+ // to fix.
AiFailure::Other(_) => None,
}
}
@@ -150,27 +145,11 @@ fn details_for(rejection: &AiRejection) -> Map<String, serde_json::Value> {
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,
- } => {
+ AiRejection::FirstPartNotEvent(field) | AiRejection::UnknownField(field) => {
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 } => {
+ | AiRejection::EventAndPropertiesTooBig { size, max } => {
details.insert("size".to_string(), json!(size));
details.insert("limit".to_string(), json!(max));
}
@@ -208,7 +187,7 @@ mod tests {
Some(WarningType::InvalidEventUuid)
)]
#[case::oversize(
- AiRejection::SumOfPartsTooBig { size: 1, max: 0 },
+ AiRejection::EventAndPropertiesTooBig { size: 1, max: 0 },
Some(WarningType::MessageSizeTooLarge)
)]
#[case::bad_properties(
@@ -219,8 +198,8 @@ mod tests {
// 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()),
+ #[case::blob_style_part(
+ AiRejection::UnknownField("event.properties.x".to_string()),
Some(WarningType::InvalidAiPayload)
)]
fn rejections_map_to_their_warning(
@@ -303,15 +282,14 @@ mod tests {
}
#[test]
- fn blob_rejection_names_the_part_but_not_the_error_message() {
+ fn unknown_field_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(),
- }),
+ &AiFailure::Rejected(AiRejection::UnknownField(
+ "event.properties.image".to_string(),
+ )),
);
let emitted = emitter.emitted();
@@ -320,10 +298,6 @@ mod tests {
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"));
}
@@ -333,9 +307,9 @@ mod tests {
emit_ai_failure_warning(
Some(&emitter),
&request(),
- &AiFailure::Rejected(AiRejection::SumOfPartsTooBig {
- size: 30_000_000,
- max: 26_214_400,
+ &AiFailure::Rejected(AiRejection::EventAndPropertiesTooBig {
+ size: 1_000_000,
+ max: 983_040,
}),
);
@@ -343,12 +317,9 @@ mod tests {
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))
+ Some(&json!(1_000_000))
);
+ assert_eq!(emitted[0].extra_details.get("limit"), Some(&json!(983_040)));
}
// The gzip decompressor is the one shared helper the handler calls after
@@ -374,8 +345,8 @@ mod tests {
#[rstest]
#[case::quota(CaptureError::BillingLimit)]
- #[case::blob_storage(CaptureError::ServiceUnavailable("no s3".to_string()))]
- #[case::s3_upload(CaptureError::NonRetryableSinkError)]
+ #[case::service_unavailable(CaptureError::ServiceUnavailable("down".to_string()))]
+ #[case::serialization(CaptureError::NonRetryableSinkError)]
#[case::kafka(CaptureError::RetryableSinkError)]
#[case::internal(CaptureError::InternalError("boom".to_string()))]
fn our_failures_never_warn(#[case] err: CaptureError) {
diff --git a/rust/capture/src/lib.rs b/rust/capture/src/lib.rs
index b0ae59d8af90..ecf44577a4c2 100644
--- a/rust/capture/src/lib.rs
+++ b/rust/capture/src/lib.rs
@@ -1,6 +1,5 @@
pub mod ai_endpoint;
pub mod ai_rejection;
-pub mod ai_s3;
pub mod api;
pub mod config;
pub mod event_restrictions;
diff --git a/rust/capture/src/prometheus.rs b/rust/capture/src/prometheus.rs
index 73afb2daac62..31b763532425 100644
--- a/rust/capture/src/prometheus.rs
+++ b/rust/capture/src/prometheus.rs
@@ -80,8 +80,6 @@ pub fn setup_metrics_recorder(role: String, capture_mode: &'static str) -> Prome
16777216.0, // 16MB
33554432.0, // 32MB
];
- // Blob count per event (2x increments)
- const BLOB_COUNTS: &[f64] = &[1.0, 2.0, 4.0, 8.0, 16.0, 32.0];
// Redis read/write pipeline round-trip (milliseconds). Dense around the
// 100ms read/write timeout so p99 is readable below it.
const GLOBAL_RATE_LIMITER_PIPELINE_MS: &[f64] = &[
@@ -162,21 +160,6 @@ pub fn setup_metrics_recorder(role: String, capture_mode: &'static str) -> Prome
BATCH_SIZES,
)
.unwrap()
- .set_buckets_for_metric(
- Matcher::Full("capture_ai_blob_count_per_event".to_string()),
- BLOB_COUNTS,
- )
- .unwrap()
- .set_buckets_for_metric(
- Matcher::Full("capture_ai_blob_size_bytes".to_string()),
- S3_BODY_SIZES, // Reuse same buckets as S3 body sizes
- )
- .unwrap()
- .set_buckets_for_metric(
- Matcher::Full("capture_ai_blob_total_bytes_per_event".to_string()),
- S3_BODY_SIZES, // Reuse same buckets as S3 body sizes
- )
- .unwrap()
.set_buckets_for_metric(
Matcher::Full("global_rate_limiter_pipeline_ms".to_string()),
GLOBAL_RATE_LIMITER_PIPELINE_MS,
diff --git a/rust/capture/src/router.rs b/rust/capture/src/router.rs
index 1336c5700cdd..f5da6cb0b9e5 100644
--- a/rust/capture/src/router.rs
+++ b/rust/capture/src/router.rs
@@ -14,7 +14,6 @@ use tower::limit::ConcurrencyLimitLayer;
use tower_http::cors::{AllowHeaders, AllowOrigin, CorsLayer};
use tower_http::trace::TraceLayer;
-use crate::ai_s3::BlobStorage;
use crate::event_restrictions::EventRestrictionService;
use crate::global_rate_limiter::GlobalRateLimiter;
use crate::otel;
@@ -54,7 +53,6 @@ pub struct State {
pub is_mirror_deploy: bool,
pub verbose_sample_percent: f32,
pub ai_max_sum_of_parts_bytes: usize,
- pub ai_blob_storage: Option<Arc<dyn BlobStorage>>,
pub body_chunk_read_timeout: Option<Duration>,
pub body_read_chunk_size_kb: usize,
pub capture_v1_max_compressed_body_bytes: usize,
@@ -165,7 +163,6 @@ pub fn router<TZ: TimeSource + Send + Sync + 'static, R: Client + Send + Sync +
is_mirror_deploy: bool,
verbose_sample_percent: f32,
ai_max_sum_of_parts_bytes: usize,
- ai_blob_storage: Option<Arc<dyn BlobStorage>>,
body_chunk_read_timeout_ms: Option<u64>,
body_read_chunk_size_kb: usize,
capture_v1_max_compressed_body_bytes: usize,
@@ -195,7 +192,6 @@ pub fn router<TZ: TimeSource + Send + Sync + 'static, R: Client + Send + Sync +
is_mirror_deploy,
verbose_sample_percent,
ai_max_sum_of_parts_bytes,
- ai_blob_storage,
body_chunk_read_timeout: body_chunk_read_timeout_ms.map(Duration::from_millis),
body_read_chunk_size_kb,
capture_v1_max_compressed_body_bytes,
diff --git a/rust/capture/src/setup.rs b/rust/capture/src/setup.rs
index 1748121400bf..ede2994f3806 100644
--- a/rust/capture/src/setup.rs
+++ b/rust/capture/src/setup.rs
@@ -13,7 +13,6 @@ use common_redis::RedisClient;
use metrics::gauge;
use tracing::{info, warn};
-use crate::ai_s3::AiBlobStorage;
use crate::config::{CaptureMode, Config};
use crate::event_restrictions::{EventRestrictionService, Pipeline, RedisRestrictionsRepository};
use crate::global_rate_limiter::GlobalRateLimiter;
@@ -23,7 +22,6 @@ use crate::quota_limiters::{
};
use crate::router;
use crate::router::BATCH_BODY_SIZE;
-use crate::s3_client::{S3Client, S3Config};
use crate::sinks::fallback::FallbackSink;
use crate::sinks::kafka::KafkaSink;
use crate::sinks::noop::NoOpSink;
@@ -274,49 +272,6 @@ pub async fn build_components(
);
let sink_for_flush = sink.clone();
- // Create AI blob storage if S3 is configured
- let ai_blob_storage: Option<Arc<dyn crate::ai_s3::BlobStorage>> =
- if let Some(bucket) = &config.ai_s3_bucket {
- let s3_config = S3Config {
- bucket: bucket.clone(),
- region: config.ai_s3_region.clone(),
- endpoint: config.ai_s3_endpoint.clone(),
- access_key_id: config.ai_s3_access_key_id.clone(),
- secret_access_key: config.ai_s3_secret_access_key.clone(),
- };
- let s3_client = S3Client::new(s3_config).await;
-
- if s3_client.check_health().await {
- tracing::info!(bucket = bucket, "AI S3 bucket verified");
- } else {
- tracing::error!(bucket = bucket, "AI S3 bucket not accessible");
- }
-
- // Spawn background health check task (shutdown-aware via server handle)
- let s3_client_clone = s3_client.clone();
- let ai_shutdown = server.clone();
- tokio::spawn(async move {
- let mut interval = tokio::time::interval(Duration::from_secs(30));
- loop {
- tokio::select! {
- _ = interval.tick() => {
- s3_client_clone.check_health().await;
- }
- _ = ai_shutdown.shutdown_recv() => {
- break;
- }
- }
- }
- });
-
- Some(Arc::new(AiBlobStorage::new(
- s3_client,
- config.ai_s3_prefix.clone(),
- )))
- } else {
- None
- };
-
let event_restriction_service = if let Some(handle) = event_restrictions_handle {
create_event_restriction_service(
&config,
@@ -403,7 +358,6 @@ pub async fn build_components(
config.is_mirror_deploy,
config.verbose_sample_percent,
config.ai_max_sum_of_parts_bytes,
- ai_blob_storage,
config.body_chunk_read_timeout_ms,
config.body_read_chunk_size_kb,
config.capture_v1_max_compressed_body_bytes,
diff --git a/rust/capture/src/v1/quota_limiter_shim.rs b/rust/capture/src/v1/quota_limiter_shim.rs
index 7ae9c42c0e3c..61ae959aa6b5 100644
--- a/rust/capture/src/v1/quota_limiter_shim.rs
+++ b/rust/capture/src/v1/quota_limiter_shim.rs
@@ -232,12 +232,6 @@ mod tests {
s3_fallback_endpoint: None,
s3_fallback_prefix: String::new(),
ai_max_sum_of_parts_bytes: 26_214_400,
- ai_s3_bucket: None,
- ai_s3_prefix: "llma/".to_string(),
- ai_s3_endpoint: None,
- ai_s3_region: "us-east-1".to_string(),
- ai_s3_access_key_id: None,
- ai_s3_secret_access_key: None,
ai_gateway_signing_secret: None,
http1_header_read_timeout_ms: Some(5000),
body_chunk_read_timeout_ms: None,
diff --git a/rust/capture/src/v1/test_utils.rs b/rust/capture/src/v1/test_utils.rs
index 63bda6c7420f..012b89c58da8 100644
--- a/rust/capture/src/v1/test_utils.rs
+++ b/rust/capture/src/v1/test_utils.rs
@@ -925,7 +925,6 @@ impl TestStateBuilder {
is_mirror_deploy: false,
verbose_sample_percent: 0.0,
ai_max_sum_of_parts_bytes: 100 * 1024 * 1024,
- ai_blob_storage: None,
body_chunk_read_timeout: None,
body_read_chunk_size_kb: 64,
capture_v1_max_compressed_body_bytes: 2 * 1024 * 1024,
diff --git a/rust/capture/tests/common/integration_utils.rs b/rust/capture/tests/common/integration_utils.rs
index 4091314e2033..1a8164f210f2 100644
--- a/rust/capture/tests/common/integration_utils.rs
+++ b/rust/capture/tests/common/integration_utils.rs
@@ -1110,7 +1110,6 @@ fn build_router_for_mode_at(mode: CaptureMode, fixed_time: &str) -> (Router, Mem
is_mirror_deploy,
verbose_sample_percent,
26_214_400, // 25MB default for AI endpoint
- None, // ai_blob_storage
None, // body_chunk_read_timeout_ms
256, // body_read_chunk_size_kb
10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
diff --git a/rust/capture/tests/common/utils.rs b/rust/capture/tests/common/utils.rs
index b224e1fbf821..b759184c49f7 100644
--- a/rust/capture/tests/common/utils.rs
+++ b/rust/capture/tests/common/utils.rs
@@ -148,12 +148,6 @@ pub static DEFAULT_CONFIG: Lazy<Config> = Lazy::new(|| Config {
s3_fallback_endpoint: None,
s3_fallback_prefix: String::new(),
ai_max_sum_of_parts_bytes: 26_214_400, // 25MB default
- ai_s3_bucket: None,
- ai_s3_prefix: "llma/".to_string(),
- ai_s3_endpoint: None,
- ai_s3_region: "us-east-1".to_string(),
- ai_s3_access_key_id: None,
- ai_s3_secret_access_key: None,
ai_gateway_signing_secret: None,
http1_header_read_timeout_ms: Some(5000), // 5 seconds default
body_chunk_read_timeout_ms: None, // disabled by default in tests
diff --git a/rust/capture/tests/integration_ai_endpoint.rs b/rust/capture/tests/integration_ai_endpoint.rs
index 7ec983f4d2ed..465c96f1103f 100644
--- a/rust/capture/tests/integration_ai_endpoint.rs
+++ b/rust/capture/tests/integration_ai_endpoint.rs
@@ -5,7 +5,6 @@ use async_trait::async_trait;
use axum::http::StatusCode;
use axum::Router;
use axum_test_helper::TestClient;
-use capture::ai_s3::{BlobStorage, MockBlobStorage};
use capture::api::CaptureError;
use capture::config::CaptureMode;
use capture::quota_limiters::CaptureQuotaLimiter;
@@ -28,17 +27,6 @@ use std::num::NonZeroU32;
use std::sync::Arc;
use std::time::Duration;
-// Test constants for mock blob storage
-const TEST_BLOB_BUCKET: &str = "test-bucket";
-const TEST_BLOB_PREFIX: &str = "llma/";
-
-fn create_mock_blob_storage() -> Arc<dyn BlobStorage> {
- Arc::new(MockBlobStorage::new(
- TEST_BLOB_BUCKET.to_string(),
- TEST_BLOB_PREFIX.to_string(),
- ))
-}
-
// Fixed time source for tests
struct FixedTime {
pub time: DateTime<Utc>,
@@ -187,20 +175,19 @@ fn setup_ai_test_router() -> Router {
1_i64,
false,
0.0_f32,
- 26_214_400, // 25MB default for AI endpoint
- Some(create_mock_blob_storage()), // ai_blob_storage
- None, // body_chunk_read_timeout_ms
- 256, // body_read_chunk_size_kb
- 10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
- 50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytes
- None, // overflow_limiter
- None, // ai_events_overflow_limiter
- None, // replay_overflow_limiter
- None, // v1_sink_router
- 8, // capture_v1_scatter_gather_min_batch
- None, // ai_gateway_signing_secret
- false, // ai_events_overflow_enabled
- None, // ingestion_warning_emitter
+ 26_214_400, // 25MB default for AI endpoint
+ None, // body_chunk_read_timeout_ms
+ 256, // body_read_chunk_size_kb
+ 10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
+ 50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytes
+ None, // overflow_limiter
+ None, // ai_events_overflow_limiter
+ None, // replay_overflow_limiter
+ None, // v1_sink_router
+ 8, // capture_v1_scatter_gather_min_batch
+ None, // ai_gateway_signing_secret
+ false, // ai_events_overflow_enabled
+ None, // ingestion_warning_emitter
)
}
@@ -244,7 +231,6 @@ fn setup_ai_router_collecting_warnings() -> (Router, Arc<CollectingEmitter>) {
false,
0.0_f32,
26_214_400,
- Some(create_mock_blob_storage()),
None,
256,
10 * 1024 * 1024,
@@ -332,6 +318,40 @@ async fn test_ai_endpoint_no_auth_returns_401() {
assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
}
+#[tokio::test]
+async fn test_blob_part_is_rejected_as_unknown_field() {
+ let router = setup_ai_test_router();
+ let test_client = TestClient::new(router);
+
+ let event_data = json!({
+ "uuid": uuid::Uuid::now_v7().to_string(),
+ "event": "$ai_generation",
+ "distinct_id": "test_user",
+ "properties": {"$ai_model": "test"}
+ });
+ let form = Form::new()
+ .part(
+ "event",
+ Part::text(event_data.to_string())
+ .mime_str("application/json")
+ .unwrap(),
+ )
+ .part(
+ "event.properties.$ai_input",
+ Part::bytes(b"payload".to_vec())
+ .mime_str("application/octet-stream")
+ .unwrap(),
+ );
+
+ let response = send_multipart_request(&test_client, form, Some("phc_test_token")).await;
+ assert_eq!(response.status(), StatusCode::BAD_REQUEST);
+ let body = response.text().await;
+ assert!(
+ body.contains("Unknown multipart field"),
+ "unexpected body: {body}"
+ );
+}
+
// ----------------------------------------------------------------------------
// Scenario 1.1: Content Type Validation
// ----------------------------------------------------------------------------
@@ -382,261 +402,6 @@ async fn test_ai_endpoint_empty_body_returns_400() {
// Scenario 1.2: Multipart Parsing
// ----------------------------------------------------------------------------
-#[tokio::test]
-async fn test_multipart_parsing_with_multiple_blobs() {
- use uuid::Uuid;
-
- let router = setup_ai_test_router();
- let test_client = TestClient::new(router);
-
- let event_data = json!({
- "uuid": Uuid::now_v7().to_string(),
- "event": "$ai_generation",
- "distinct_id": "test_user"
- });
-
- let properties = json!({
- "$ai_model": "test-multi-blob"
- });
-
- let input_blob = json!({"messages": [{"role": "user", "content": "Hello"}]});
- let output_blob = json!({"choices": [{"message": {"content": "Hi there"}}]});
- let metadata_blob = json!({"model_version": "1.0", "temperature": 0.7});
-
- let form = Form::new()
- .part(
- "event",
- Part::bytes(serde_json::to_vec(&event_data).unwrap())
- .mime_str("application/json")
- .unwrap(),
- )
- .part(
- "event.properties",
- Part::bytes(serde_json::to_vec(&properties).unwrap())
- .mime_str("application/json")
- .unwrap(),
- )
- .part(
- "event.properties.$ai_input",
- Part::bytes(serde_json::to_vec(&input_blob).unwrap())
- .mime_str("application/json")
- .unwrap(),
- )
- .part(
- "event.properties.$ai_output",
- Part::bytes(serde_json::to_vec(&output_blob).unwrap())
- .mime_str("application/json")
- .unwrap(),
- )
- .part(
- "event.properties.$ai_metadata",
- Part::bytes(serde_json::to_vec(&metadata_blob).unwrap())
- .mime_str("application/json")
- .unwrap(),
- );
-
- let response = send_multipart_request(
- &test_client,
- form,
- Some("phc_VXRzc3poSG9GZm1JenRianJ6TTJFZGh4OWY2QXzx9f3"),
- )
- .await;
- assert_eq!(response.status(), StatusCode::OK);
-
- let response_json: serde_json::Value = response.json::<serde_json::Value>().await;
- let accepted_parts = response_json["accepted_parts"].as_array().unwrap();
- assert_eq!(accepted_parts.len(), 5);
- assert_eq!(accepted_parts[0]["name"], "event");
- assert_eq!(accepted_parts[0]["length"].as_u64().unwrap(), 98); // UUID adds ~46 bytes
- assert_eq!(accepted_parts[1]["name"], "event.properties");
- assert_eq!(accepted_parts[1]["length"].as_u64().unwrap(), 31);
- assert_eq!(accepted_parts[2]["name"], "event.properties.$ai_input");
- assert_eq!(accepted_parts[2]["length"].as_u64().unwrap(), 48);
- assert_eq!(accepted_parts[3]["name"], "event.properties.$ai_output");
- assert_eq!(accepted_parts[3]["length"].as_u64().unwrap(), 48);
- assert_eq!(accepted_parts[4]["name"], "event.properties.$ai_metadata");
- assert_eq!(accepted_parts[4]["length"].as_u64().unwrap(), 41);
-}
-
-#[tokio::test]
-async fn test_multipart_parsing_with_mixed_content_types() {
- use uuid::Uuid;
-
- let router = setup_ai_test_router();
- let test_client = TestClient::new(router);
-
- let event_data = json!({
- "uuid": Uuid::now_v7().to_string(),
- "event": "$ai_generation",
- "distinct_id": "test_user"
- });
-
- let properties = json!({
- "$ai_model": "test-mixed-types"
- });
-
- let form = Form::new()
- .part(
- "event",
- Part::bytes(serde_json::to_vec(&event_data).unwrap())
- .mime_str("application/json")
- .unwrap(),
- )
- .part(
- "event.properties",
- Part::bytes(serde_json::to_vec(&properties).unwrap())
- .mime_str("application/json")
- .unwrap(),
- )
- .part(
- "event.properties.$ai_json_blob",
- Part::bytes(serde_json::to_vec(&json!({"type": "json"})).unwrap())
- .mime_str("application/json")
- .unwrap(),
- )
- .part(
- "event.properties.$ai_text_blob",
- Part::bytes(b"This is plain text content".to_vec())
- .mime_str("text/plain")
- .unwrap(),
- )
- .part(
- "event.properties.$ai_binary_blob",
- Part::bytes(vec![0x00, 0x01, 0x02, 0x03, 0x04, 0x05])
- .mime_str("application/octet-stream")
- .unwrap(),
- );
-
- let response = send_multipart_request(
- &test_client,
- form,
- Some("phc_VXRzc3poSG9GZm1JenRianJ6TTJFZGh4OWY2QXzx9f3"),
- )
- .await;
- assert_eq!(response.status(), StatusCode::OK);
-
- let response_json: serde_json::Value = response.json::<serde_json::Value>().await;
- let accepted_parts = response_json["accepted_parts"].as_array().unwrap();
- assert_eq!(accepted_parts.len(), 5);
- assert_eq!(accepted_parts[0]["length"].as_u64().unwrap(), 98); // UUID adds ~46 bytes
- assert_eq!(accepted_parts[1]["length"].as_u64().unwrap(), 32);
- assert_eq!(accepted_parts[2]["content-type"], "application/json");
- assert_eq!(accepted_parts[2]["length"].as_u64().unwrap(), 15);
- assert_eq!(accepted_parts[3]["content-type"], "text/plain");
- assert_eq!(accepted_parts[3]["length"].as_u64().unwrap(), 26);
- assert_eq!(
- accepted_parts[4]["content-type"],
- "application/octet-stream"
- );
- assert_eq!(accepted_parts[4]["length"].as_u64().unwrap(), 6);
-}
-
-#[tokio::test]
-async fn test_multipart_parsing_with_large_blob() {
- use uuid::Uuid;
-
- let router = setup_ai_test_router();
- let test_client = TestClient::new(router);
-
- let event_data = json!({
- "uuid": Uuid::now_v7().to_string(),
- "event": "$ai_generation",
- "distinct_id": "test_user"
- });
-
- let properties = json!({
- "$ai_model": "test-large"
- });
-
- // Create a large JSON blob (100KB)
- let large_blob = json!({
- "messages": (0..100).map(|_| json!({"role": "user", "content": "x".repeat(1000)})).collect::<Vec<_>>()
- });
-
- let form = Form::new()
- .part(
- "event",
- Part::bytes(serde_json::to_vec(&event_data).unwrap())
- .mime_str("application/json")
- .unwrap(),
- )
- .part(
- "event.properties",
- Part::bytes(serde_json::to_vec(&properties).unwrap())
- .mime_str("application/json")
- .unwrap(),
- )
- .part(
- "event.properties.$ai_large_input",
- Part::bytes(serde_json::to_vec(&large_blob).unwrap())
- .mime_str("application/json")
- .unwrap(),
- );
-
- let response = send_multipart_request(
- &test_client,
- form,
- Some("phc_VXRzc3poSG9GZm1JenRianJ6TTJFZGh4OWY2QXzx9f3"),
- )
- .await;
- assert_eq!(response.status(), StatusCode::OK);
-
- let response_json: serde_json::Value = response.json::<serde_json::Value>().await;
- let accepted_parts = response_json["accepted_parts"].as_array().unwrap();
- assert_eq!(accepted_parts.len(), 3);
- assert_eq!(accepted_parts[0]["length"].as_u64().unwrap(), 98); // UUID adds ~46 bytes
- assert_eq!(accepted_parts[1]["length"].as_u64().unwrap(), 26);
- assert_eq!(accepted_parts[2]["length"].as_u64().unwrap(), 102914);
-}
-
-#[tokio::test]
-async fn test_multipart_parsing_with_empty_blob() {
- use uuid::Uuid;
-
- let router = setup_ai_test_router();
- let test_client = TestClient::new(router);
-
- let event_data = json!({
- "uuid": Uuid::now_v7().to_string(),
- "event": "$ai_generation",
- "distinct_id": "test_user"
- });
-
- let properties = json!({
- "$ai_model": "test-empty"
- });
-
- let form = Form::new()
- .part(
- "event",
- Part::bytes(serde_json::to_vec(&event_data).unwrap())
- .mime_str("application/json")
- .unwrap(),
- )
- .part(
- "event.properties",
- Part::bytes(serde_json::to_vec(&properties).unwrap())
- .mime_str("application/json")
- .unwrap(),
- )
- .part(
- "event.properties.$ai_empty",
- Part::bytes(Vec::new())
- .mime_str("application/json")
- .unwrap(),
- );
-
- let response = send_multipart_request(
- &test_client,
- form,
- Some("phc_VXRzc3poSG9GZm1JenRianJ6TTJFZGh4OWY2QXzx9f3"),
- )
- .await;
-
- // Empty blobs should be rejected with 400 Bad Request
- assert_eq!(response.status(), StatusCode::BAD_REQUEST);
-}
-
// ----------------------------------------------------------------------------
// Scenario 1.3: Boundary Validation
// ----------------------------------------------------------------------------
@@ -1383,7 +1148,7 @@ async fn test_combined_event_properties_exceeds_960kb_returns_413() {
}
#[tokio::test]
-async fn test_sum_of_all_parts_exceeds_25mb_returns_413() {
+async fn test_request_body_exceeds_110_percent_limit_returns_413() {
let router = setup_ai_test_router();
let test_client = TestClient::new(router);
@@ -1396,9 +1161,10 @@ async fn test_sum_of_all_parts_exceeds_25mb_returns_413() {
"$ai_model": "test"
});
- // Create a blob that, combined with event and properties, exceeds 25MB
- // Event ~52 bytes + properties ~24 bytes + blob ~25MB = exceeds limit
- let large_blob = vec![0u8; 25 * 1024 * 1024];
+ // Create a blob that's just barely over 25MB
+ // This will result in a request body that exceeds 27.5MB (110% limit)
+ // once multipart overhead is added
+ let large_blob = vec![0u8; (25 * 1024 * 1024) + (3 * 1024 * 1024)]; // 28MB
let form = Form::new()
.part(
@@ -1426,199 +1192,21 @@ async fn test_sum_of_all_parts_exceeds_25mb_returns_413() {
Some("phc_VXRzc3poSG9GZm1JenRianJ6TTJFZGh4OWY2QXzx9f3"),
)
.await;
+
+ // Axum's DefaultBodyLimit returns 413 Payload Too Large when the body exceeds the limit
assert_eq!(response.status(), StatusCode::PAYLOAD_TOO_LARGE);
}
+// ----------------------------------------------------------------------------
+// Content Type Validation Tests
+// ----------------------------------------------------------------------------
+
+// ----------------------------------------------------------------------------
+// Compression Tests
+// ----------------------------------------------------------------------------
+
#[tokio::test]
-async fn test_request_body_exceeds_110_percent_limit_returns_413() {
- let router = setup_ai_test_router();
- let test_client = TestClient::new(router);
-
- let event_data = json!({
- "event": "$ai_generation",
- "distinct_id": "test_user"
- });
-
- let properties = json!({
- "$ai_model": "test"
- });
-
- // Create a blob that's just barely over 25MB
- // This will result in a request body that exceeds 27.5MB (110% limit)
- // once multipart overhead is added
- let large_blob = vec![0u8; (25 * 1024 * 1024) + (3 * 1024 * 1024)]; // 28MB
-
- let form = Form::new()
- .part(
- "event",
- Part::bytes(serde_json::to_vec(&event_data).unwrap())
- .mime_str("application/json")
- .unwrap(),
- )
- .part(
- "event.properties",
- Part::bytes(serde_json::to_vec(&properties).unwrap())
- .mime_str("application/json")
- .unwrap(),
- )
- .part(
- "event.properties.$ai_input",
- Part::bytes(large_blob)
- .mime_str("application/octet-stream")
- .unwrap(),
- );
-
- let response = send_multipart_request(
- &test_client,
- form,
- Some("phc_VXRzc3poSG9GZm1JenRianJ6TTJFZGh4OWY2QXzx9f3"),
- )
- .await;
-
- // Axum's DefaultBodyLimit returns 413 Payload Too Large when the body exceeds the limit
- assert_eq!(response.status(), StatusCode::PAYLOAD_TOO_LARGE);
-}
-
-// ----------------------------------------------------------------------------
-// Content Type Validation Tests
-// ----------------------------------------------------------------------------
-
-#[tokio::test]
-async fn test_blob_with_application_octet_stream_content_type() {
- let router = setup_ai_test_router();
- let test_client = TestClient::new(router);
-
- let properties = json!({
- "$ai_model": "test"
- });
-
- let blob_data = vec![0u8, 1u8, 2u8, 3u8];
-
- let form = create_ai_event_form("$ai_generation", "test_user", properties).part(
- "event.properties.$ai_binary_data",
- Part::bytes(blob_data)
- .mime_str("application/octet-stream")
- .unwrap(),
- );
-
- let response = send_multipart_request(
- &test_client,
- form,
- Some("phc_VXRzc3poSG9GZm1JenRianJ6TTJFZGh4OWY2QXzx9f3"),
- )
- .await;
- assert_eq!(response.status(), StatusCode::OK);
-}
-
-#[tokio::test]
-async fn test_blob_with_application_json_content_type() {
- let router = setup_ai_test_router();
- let test_client = TestClient::new(router);
-
- let properties = json!({
- "$ai_model": "test"
- });
-
- let blob_data = json!({"key": "value"}).to_string();
-
- let form = create_ai_event_form("$ai_generation", "test_user", properties).part(
- "event.properties.$ai_input",
- Part::bytes(blob_data.into_bytes())
- .mime_str("application/json")
- .unwrap(),
- );
-
- let response = send_multipart_request(
- &test_client,
- form,
- Some("phc_VXRzc3poSG9GZm1JenRianJ6TTJFZGh4OWY2QXzx9f3"),
- )
- .await;
- assert_eq!(response.status(), StatusCode::OK);
-}
-
-#[tokio::test]
-async fn test_blob_with_text_plain_content_type() {
- let router = setup_ai_test_router();
- let test_client = TestClient::new(router);
-
- let properties = json!({
- "$ai_model": "test"
- });
-
- let blob_data = "This is plain text data";
-
- let form = create_ai_event_form("$ai_generation", "test_user", properties).part(
- "event.properties.$ai_output",
- Part::bytes(blob_data.as_bytes().to_vec())
- .mime_str("text/plain")
- .unwrap(),
- );
-
- let response = send_multipart_request(
- &test_client,
- form,
- Some("phc_VXRzc3poSG9GZm1JenRianJ6TTJFZGh4OWY2QXzx9f3"),
- )
- .await;
- assert_eq!(response.status(), StatusCode::OK);
-}
-
-#[tokio::test]
-async fn test_blob_with_invalid_content_type_returns_400() {
- let router = setup_ai_test_router();
- let test_client = TestClient::new(router);
-
- let properties = json!({
- "$ai_model": "test"
- });
-
- let blob_data = vec![0u8, 1u8, 2u8, 3u8];
-
- let form = create_ai_event_form("$ai_generation", "test_user", properties).part(
- "event.properties.$ai_data",
- Part::bytes(blob_data).mime_str("application/xml").unwrap(),
- );
-
- let response = send_multipart_request(
- &test_client,
- form,
- Some("phc_VXRzc3poSG9GZm1JenRianJ6TTJFZGh4OWY2QXzx9f3"),
- )
- .await;
- assert_eq!(response.status(), StatusCode::BAD_REQUEST);
-}
-
-#[tokio::test]
-async fn test_blob_without_content_type_returns_400() {
- let router = setup_ai_test_router();
- let test_client = TestClient::new(router);
-
- let properties = json!({
- "$ai_model": "test"
- });
-
- let blob_data = vec![0u8, 1u8, 2u8, 3u8];
-
- // Create a part without Content-Type (reqwest doesn't set it if we don't call mime_str)
- let form = create_ai_event_form("$ai_generation", "test_user", properties)
- .part("event.properties.$ai_data", Part::bytes(blob_data));
-
- let response = send_multipart_request(
- &test_client,
- form,
- Some("phc_VXRzc3poSG9GZm1JenRianJ6TTJFZGh4OWY2QXzx9f3"),
- )
- .await;
- assert_eq!(response.status(), StatusCode::BAD_REQUEST);
-}
-
-// ----------------------------------------------------------------------------
-// Compression Tests
-// ----------------------------------------------------------------------------
-
-#[tokio::test]
-async fn test_gzip_compressed_request() {
+async fn test_gzip_compressed_request() {
let router = setup_ai_test_router();
let test_client = TestClient::new(router);
@@ -1710,20 +1298,19 @@ fn setup_ai_test_router_with_capturing_sink() -> (Router, CapturingSink) {
1_i64,
false,
0.0_f32,
- 26_214_400, // 25MB default for AI endpoint
- Some(create_mock_blob_storage()), // ai_blob_storage
- None, // body_chunk_read_timeout_ms
- 256, // body_read_chunk_size_kb
- 10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
- 50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytes
- None, // overflow_limiter
- None, // ai_events_overflow_limiter
- None, // replay_overflow_limiter
- None, // v1_sink_router
- 8, // capture_v1_scatter_gather_min_batch
- None, // ai_gateway_signing_secret
- false, // ai_events_overflow_enabled
- None, // ingestion_warning_emitter
+ 26_214_400, // 25MB default for AI endpoint
+ None, // body_chunk_read_timeout_ms
+ 256, // body_read_chunk_size_kb
+ 10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
+ 50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytes
+ None, // overflow_limiter
+ None, // ai_events_overflow_limiter
+ None, // replay_overflow_limiter
+ None, // v1_sink_router
+ 8, // capture_v1_scatter_gather_min_batch
+ None, // ai_gateway_signing_secret
+ false, // ai_events_overflow_enabled
+ None, // ingestion_warning_emitter
);
(router, sink_clone)
@@ -1788,254 +1375,6 @@ async fn test_ai_event_published_to_kafka() {
assert_eq!(props["$ai_model"], "gpt-4");
}
-#[tokio::test]
-async fn test_ai_event_with_blobs_published_with_s3_placeholders() {
- let (router, sink) = setup_ai_test_router_with_capturing_sink();
- let test_client = TestClient::new(router);
-
- let event_uuid = "650e8400-e29b-41d4-a716-446655440001";
- let event_data = json!({
- "uuid": event_uuid,
- "event": "$ai_generation",
- "distinct_id": "test_user"
- });
-
- let properties = json!({
- "$ai_model": "gpt-4"
- });
-
- let input_blob = json!({"messages": [{"role": "user", "content": "Hello"}]});
- let output_blob = json!({"choices": [{"message": {"content": "Hi there"}}]});
-
- let form = Form::new()
- .part(
- "event",
- Part::bytes(serde_json::to_vec(&event_data).unwrap())
- .mime_str("application/json")
- .unwrap(),
- )
- .part(
- "event.properties",
- Part::bytes(serde_json::to_vec(&properties).unwrap())
- .mime_str("application/json")
- .unwrap(),
- )
- .part(
- "event.properties.$ai_input",
- Part::bytes(serde_json::to_vec(&input_blob).unwrap())
- .mime_str("application/json")
- .unwrap(),
- )
- .part(
- "event.properties.$ai_output",
- Part::bytes(serde_json::to_vec(&output_blob).unwrap())
- .mime_str("application/json")
- .unwrap(),
- );
-
- let response = send_multipart_request(
- &test_client,
- form,
- Some("phc_VXRzc3poSG9GZm1JenRianJ6TTJFZGh4OWY2QXzx9f3"),
- )
- .await;
- assert_eq!(response.status(), StatusCode::OK);
-
- // Verify event was published to Kafka
- let events = sink.get_events().await;
- assert_eq!(
- events.len(),
- 1,
- "Expected exactly one event to be published"
- );
-
- let event = &events[0];
- let event_json: serde_json::Value = serde_json::from_str(&event.event.data).unwrap();
-
- // Verify properties contain S3 URLs from mock blob storage
- let props = event_json["properties"].as_object().unwrap();
-
- // Both blobs should have S3 URLs
- let input_url = props["$ai_input"].as_str().unwrap();
- let output_url = props["$ai_output"].as_str().unwrap();
-
- // Verify S3 URLs point to same file with different ranges
- // URL format: s3://test-bucket/llma/<token_hash>/<uuid>?range=...
- // Token is hashed (first 16 chars of SHA-256) to prevent path traversal attacks
- let token_hash = "896566b02a7f7462"; // SHA-256 of "phc_VXRzc3poSG9GZm1JenRianJ6TTJFZGh4OWY2QXzx9f3"
- let expected_prefix = format!("s3://{TEST_BLOB_BUCKET}/{TEST_BLOB_PREFIX}{token_hash}/");
- assert!(
- input_url.starts_with(&expected_prefix),
- "Input URL should start with {expected_prefix}, got {input_url}"
- );
- assert!(
- output_url.starts_with(&expected_prefix),
- "Output URL should start with {expected_prefix}, got {output_url}"
- );
-
- // Extract UUIDs from both URLs (should be the same)
- // URL format: s3://test-bucket/llma/<token_hash>/<uuid>?range=...
- let input_uuid = input_url
- .split('/')
- .nth(5)
- .unwrap()
- .split('?')
- .next()
- .unwrap();
- let output_uuid = output_url
- .split('/')
- .nth(5)
- .unwrap()
- .split('?')
- .next()
- .unwrap();
- assert_eq!(
- input_uuid, output_uuid,
- "Both blobs should point to same file"
- );
- assert_eq!(input_uuid, event_uuid, "UUID should match event UUID");
-
- // Verify ranges are sequential
- assert!(
- input_url.contains("range="),
- "Input URL should have range parameter"
- );
- assert!(
- output_url.contains("range="),
- "Output URL should have range parameter"
- );
-
- // Extract range values and verify they are non-overlapping and sequential
- let input_range = input_url.split("range=").nth(1).unwrap();
- let output_range = output_url.split("range=").nth(1).unwrap();
-
- // Parse ranges: format is "start-end"
- let input_parts: Vec<usize> = input_range.split('-').map(|s| s.parse().unwrap()).collect();
- let output_parts: Vec<usize> = output_range
- .split('-')
- .map(|s| s.parse().unwrap())
- .collect();
-
- let (input_start, input_end) = (input_parts[0], input_parts[1]);
- let (output_start, output_end) = (output_parts[0], output_parts[1]);
-
- // Verify ranges are valid (end > start)
- assert!(input_end > input_start, "Input range should be valid");
- assert!(output_end > output_start, "Output range should be valid");
-
- // Verify ranges don't overlap (output starts after input ends)
- assert!(
- output_start > input_end,
- "Output blob range should start after input blob range ends"
- );
-}
-
-#[tokio::test]
-async fn test_ai_event_with_multiple_blobs_sequential_ranges() {
- let (router, sink) = setup_ai_test_router_with_capturing_sink();
- let test_client = TestClient::new(router);
-
- let event_uuid = "750e8400-e29b-41d4-a716-446655440002";
- let event_data = json!({
- "uuid": event_uuid,
- "event": "$ai_generation",
- "distinct_id": "test_user"
- });
-
- let properties = json!({
- "$ai_model": "claude-3"
- });
-
- // Create blobs of different sizes
- let blob1 = "A".repeat(100); // 100 bytes
- let blob2 = "B".repeat(200); // 200 bytes
- let blob3 = "C".repeat(150); // 150 bytes
-
- let form = Form::new()
- .part(
- "event",
- Part::bytes(serde_json::to_vec(&event_data).unwrap())
- .mime_str("application/json")
- .unwrap(),
- )
- .part(
- "event.properties",
- Part::bytes(serde_json::to_vec(&properties).unwrap())
- .mime_str("application/json")
- .unwrap(),
- )
- .part(
- "event.properties.$ai_blob1",
- Part::bytes(blob1.into_bytes())
- .mime_str("text/plain")
- .unwrap(),
- )
- .part(
- "event.properties.$ai_blob2",
- Part::bytes(blob2.into_bytes())
- .mime_str("text/plain")
- .unwrap(),
- )
- .part(
- "event.properties.$ai_blob3",
- Part::bytes(blob3.into_bytes())
- .mime_str("text/plain")
- .unwrap(),
- );
-
- let response = send_multipart_request(
- &test_client,
- form,
- Some("phc_VXRzc3poSG9GZm1JenRianJ6TTJFZGh4OWY2QXzx9f3"),
- )
- .await;
- assert_eq!(response.status(), StatusCode::OK);
-
- // Verify event was published to Kafka
- let events = sink.get_events().await;
- assert_eq!(events.len(), 1);
-
- let event = &events[0];
- let event_json: serde_json::Value = serde_json::from_str(&event.event.data).unwrap();
- let props = event_json["properties"].as_object().unwrap();
-
- // Extract all URLs
- let url1 = props["$ai_blob1"].as_str().unwrap();
- let url2 = props["$ai_blob2"].as_str().unwrap();
- let url3 = props["$ai_blob3"].as_str().unwrap();
-
- // Verify all point to same file
- // URL format: s3://test-bucket/llma/<token>/<uuid>?range=...
- let uuid1 = url1.split('/').nth(5).unwrap().split('?').next().unwrap();
- let uuid2 = url2.split('/').nth(5).unwrap().split('?').next().unwrap();
- let uuid3 = url3.split('/').nth(5).unwrap().split('?').next().unwrap();
- assert_eq!(uuid1, uuid2);
- assert_eq!(uuid2, uuid3);
- assert_eq!(uuid1, event_uuid);
-
- // Extract and parse ranges
- let range1 = url1.split("range=").nth(1).unwrap();
- let range2 = url2.split("range=").nth(1).unwrap();
- let range3 = url3.split("range=").nth(1).unwrap();
-
- let parts1: Vec<usize> = range1.split('-').map(|s| s.parse().unwrap()).collect();
- let parts2: Vec<usize> = range2.split('-').map(|s| s.parse().unwrap()).collect();
- let parts3: Vec<usize> = range3.split('-').map(|s| s.parse().unwrap()).collect();
-
- let (start1, end1) = (parts1[0], parts1[1]);
- let (start2, end2) = (parts2[0], parts2[1]);
- let (start3, end3) = (parts3[0], parts3[1]);
-
- // Verify ranges are valid
- assert!(end1 > start1, "First range should be valid");
- assert!(end2 > start2, "Second range should be valid");
- assert!(end3 > start3, "Third range should be valid");
-
- // Verify ranges are sequential (non-overlapping)
- assert!(start2 > end1, "Second blob should start after first ends");
- assert!(start3 > end2, "Third blob should start after second ends");
-}
-
#[tokio::test]
async fn test_ai_event_metadata_preserved_in_kafka() {
let (router, sink) = setup_ai_test_router_with_capturing_sink();
@@ -2621,26 +1960,25 @@ fn setup_ai_test_router_with_token_dropper(token_dropper: TokenDropper) -> (Rout
None, // event_restriction_service
None, // recorder_handle
CaptureMode::Events,
- None, // concurrency_limit
- 25 * 1024 * 1024, // event_size_limit
- false, // enable_historical_rerouting
- 1, // historical_rerouting_threshold_days
- false, // is_mirror_deploy
- 0.0, // verbose_sample_percent
- 26_214_400, // ai_max_sum_of_parts_bytes
- Some(create_mock_blob_storage()), // ai_blob_storage
- None, // body_chunk_read_timeout_ms
- 256, // body_read_chunk_size_kb
- 10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
- 50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytes
- None, // overflow_limiter
- None, // ai_events_overflow_limiter
- None, // replay_overflow_limiter
- None, // v1_sink_router
- 8, // capture_v1_scatter_gather_min_batch
- None, // ai_gateway_signing_secret
- false, // ai_events_overflow_enabled
- None, // ingestion_warning_emitter
+ None, // concurrency_limit
+ 25 * 1024 * 1024, // event_size_limit
+ false, // enable_historical_rerouting
+ 1, // historical_rerouting_threshold_days
+ false, // is_mirror_deploy
+ 0.0, // verbose_sample_percent
+ 26_214_400, // ai_max_sum_of_parts_bytes
+ None, // body_chunk_read_timeout_ms
+ 256, // body_read_chunk_size_kb
+ 10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
+ 50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytes
+ None, // overflow_limiter
+ None, // ai_events_overflow_limiter
+ None, // replay_overflow_limiter
+ None, // v1_sink_router
+ 8, // capture_v1_scatter_gather_min_batch
+ None, // ai_gateway_signing_secret
+ false, // ai_events_overflow_enabled
+ None, // ingestion_warning_emitter
);
(router, sink_clone)
@@ -2840,19 +2178,18 @@ fn setup_ai_test_router_with_llm_quota_limited(token: &str) -> (Router, Capturin
false,
0.0_f32,
26_214_400,
- Some(create_mock_blob_storage()), // ai_blob_storage
- None, // body_chunk_read_timeout_ms
- 256, // body_read_chunk_size_kb
- 10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
- 50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytes
- None, // overflow_limiter
- None, // ai_events_overflow_limiter
- None, // replay_overflow_limiter
- None, // v1_sink_router
- 8, // capture_v1_scatter_gather_min_batch
- None, // ai_gateway_signing_secret
- false, // ai_events_overflow_enabled
- None, // ingestion_warning_emitter
+ None, // body_chunk_read_timeout_ms
+ 256, // body_read_chunk_size_kb
+ 10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
+ 50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytes
+ None, // overflow_limiter
+ None, // ai_events_overflow_limiter
+ None, // replay_overflow_limiter
+ None, // v1_sink_router
+ 8, // capture_v1_scatter_gather_min_batch
+ None, // ai_gateway_signing_secret
+ false, // ai_events_overflow_enabled
+ None, // ingestion_warning_emitter
);
(router, sink_clone)
@@ -2997,7 +2334,6 @@ fn setup_ai_test_router_with_overflow_limiter(
false,
0.0_f32,
26_214_400,
- Some(create_mock_blob_storage()),
None,
256,
10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
@@ -3138,7 +2474,6 @@ fn ai_router(
false,
0.0_f32,
26_214_400,
- Some(create_mock_blob_storage()),
None,
256,
10 * 1024 * 1024,
diff --git a/rust/capture/tests/integration_ai_restrictions.rs b/rust/capture/tests/integration_ai_restrictions.rs
index 5d6a0f07561c..7af68e047b5f 100644
--- a/rust/capture/tests/integration_ai_restrictions.rs
+++ b/rust/capture/tests/integration_ai_restrictions.rs
@@ -5,7 +5,6 @@ use async_trait::async_trait;
use axum::http::StatusCode;
use axum::Router;
use axum_test_helper::TestClient;
-use capture::ai_s3::{BlobStorage, MockBlobStorage};
use capture::api::CaptureError;
use capture::config::CaptureMode;
use capture::event_restrictions::{
@@ -29,16 +28,6 @@ use std::num::NonZeroU32;
use std::sync::Arc;
use std::time::Duration;
-const TEST_BLOB_BUCKET: &str = "test-bucket";
-const TEST_BLOB_PREFIX: &str = "llma/";
-
-fn create_mock_blob_storage() -> Arc<dyn BlobStorage> {
- Arc::new(MockBlobStorage::new(
- TEST_BLOB_BUCKET.to_string(),
- TEST_BLOB_PREFIX.to_string(),
- ))
-}
-
struct FixedTime {
pub time: DateTime<Utc>,
}
@@ -184,7 +173,6 @@ async fn setup_ai_router_with_restriction(
false,
0.0_f32,
26_214_400,
- Some(create_mock_blob_storage()),
None,
256, // body_read_chunk_size_kb
10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
@@ -505,7 +493,6 @@ async fn setup_ai_router_with_redirect_to_topic(
false,
0.0_f32,
26_214_400,
- Some(create_mock_blob_storage()),
None,
256, // body_read_chunk_size_kb
10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
@@ -584,7 +571,6 @@ async fn setup_ai_router_with_force_overflow_and_limiter(
false,
0.0_f32,
26_214_400,
- Some(create_mock_blob_storage()),
None,
256,
10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
diff --git a/rust/capture/tests/integration_analytics_ai_routing.rs b/rust/capture/tests/integration_analytics_ai_routing.rs
index 9d1facfc5b9c..d09734773b0a 100644
--- a/rust/capture/tests/integration_analytics_ai_routing.rs
+++ b/rust/capture/tests/integration_analytics_ai_routing.rs
@@ -128,7 +128,6 @@ fn setup_router_for_mode(
false,
0.0_f32,
26_214_400,
- None, // no blob storage for analytics
None,
256, // body_read_chunk_size_kb
10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
diff --git a/rust/capture/tests/integration_analytics_restrictions.rs b/rust/capture/tests/integration_analytics_restrictions.rs
index 962329311e92..71a0c3c1d38a 100644
--- a/rust/capture/tests/integration_analytics_restrictions.rs
+++ b/rust/capture/tests/integration_analytics_restrictions.rs
@@ -123,7 +123,6 @@ async fn setup_analytics_router_with_restriction(
false,
0.0_f32,
26_214_400,
- None, // no blob storage for analytics
None,
256, // body_read_chunk_size_kb
10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
@@ -550,7 +549,6 @@ async fn setup_analytics_router_with_redirect_to_topic(
0.0_f32,
26_214_400,
None,
- None,
256, // body_read_chunk_size_kb
10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytes
diff --git a/rust/capture/tests/integration_otel_endpoint.rs b/rust/capture/tests/integration_otel_endpoint.rs
index c0782e2eea8e..d5b5c8217693 100644
--- a/rust/capture/tests/integration_otel_endpoint.rs
+++ b/rust/capture/tests/integration_otel_endpoint.rs
@@ -3,7 +3,6 @@ mod integration_utils;
use async_trait::async_trait;
use axum_test_helper::TestClient;
-use capture::ai_s3::MockBlobStorage;
use capture::api::CaptureError;
use capture::config::CaptureMode;
use capture::event_restrictions::{
@@ -178,26 +177,22 @@ fn make_test_client_with_options(sink: &CapturingSink, options: TestClientOption
options.event_restriction_service,
None, // recorder_handle
CaptureMode::Events,
- None, // concurrency_limit
- 25 * 1024 * 1024, // event_payload_size_limit
- false, // enable_historical_rerouting
- 1_i64, // historical_rerouting_threshold_days
- false, // is_mirror_deploy
- 0.0_f32, // verbose_sample_percent
- 26_214_400, // ai_max_sum_of_parts_bytes
- Some(Arc::new(MockBlobStorage::new(
- "test-bucket".to_string(),
- "llma/".to_string(),
- ))), // ai_blob_storage
- None, // body_chunk_read_timeout_ms
- 256, // body_read_chunk_size_kb
- 10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
- 50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytes
+ None, // concurrency_limit
+ 25 * 1024 * 1024, // event_payload_size_limit
+ false, // enable_historical_rerouting
+ 1_i64, // historical_rerouting_threshold_days
+ false, // is_mirror_deploy
+ 0.0_f32, // verbose_sample_percent
+ 26_214_400, // ai_max_sum_of_parts_bytes
+ None, // body_chunk_read_timeout_ms
+ 256, // body_read_chunk_size_kb
+ 10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
+ 50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytes
options.overflow_limiter, // overflow_limiter
- None, // ai_events_overflow_limiter
- None, // replay_overflow_limiter
- None, // v1_sink_router
- 8, // capture_v1_scatter_gather_min_batch
+ None, // ai_events_overflow_limiter
+ None, // replay_overflow_limiter
+ None, // v1_sink_router
+ 8, // capture_v1_scatter_gather_min_batch
options.ai_gateway_signing_secret,
false, // ai_events_overflow_enabled
options.ingestion_warning_emitter, // ingestion_warning_emitter
diff --git a/rust/capture/tests/integration_replay_restrictions.rs b/rust/capture/tests/integration_replay_restrictions.rs
index dd2094721f6e..8a919d6b9089 100644
--- a/rust/capture/tests/integration_replay_restrictions.rs
+++ b/rust/capture/tests/integration_replay_restrictions.rs
@@ -120,7 +120,6 @@ async fn setup_recordings_router_with_restriction(
false,
0.0_f32,
26_214_400,
- None, // no blob storage for recordings
None,
256, // body_read_chunk_size_kb
10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
@@ -492,7 +491,6 @@ async fn setup_recordings_router_with_redirect_to_topic(
false,
0.0_f32,
26_214_400,
- None, // no blob storage for recordings
None,
256, // body_read_chunk_size_kb
10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
diff --git a/rust/capture/tests/quota_limiters.rs b/rust/capture/tests/quota_limiters.rs
index fa86979792df..fe45243a07db 100644
--- a/rust/capture/tests/quota_limiters.rs
+++ b/rust/capture/tests/quota_limiters.rs
@@ -142,7 +142,6 @@ async fn setup_router_with_limits(
false, // is_mirror_deploy
0.0, // verbose_sample_percent
26_214_400, // ai_max_sum_of_parts_bytes (25MB)
- None, // ai_blob_storage
None, // body_chunk_read_timeout_ms
256, // body_read_chunk_size_kb
10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
@@ -1196,7 +1195,6 @@ async fn test_survey_quota_cross_batch_first_submission_allowed() {
false,
0.0,
26_214_400,
- None, // ai_blob_storage
None, // body_chunk_read_timeout_ms
256, // body_read_chunk_size_kb
10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
@@ -1288,7 +1286,6 @@ async fn test_survey_quota_cross_batch_duplicate_submission_dropped() {
false,
0.0,
26_214_400,
- None, // ai_blob_storage
None, // body_chunk_read_timeout_ms
256, // body_read_chunk_size_kb
10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
@@ -1384,7 +1381,6 @@ async fn test_survey_quota_cross_batch_redis_error_fail_open() {
false,
0.0,
26_214_400,
- None, // ai_blob_storage
None, // body_chunk_read_timeout_ms
256, // body_read_chunk_size_kb
10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
@@ -1817,7 +1813,6 @@ async fn test_ai_quota_cross_batch_redis_error_fail_open() {
false,
0.0,
26_214_400,
- None, // ai_blob_storage
None, // body_chunk_read_timeout_ms
256, // body_read_chunk_size_kb
10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes