:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(capture): implement v1 BatchResponse and sink result merging (#59757)
Eli Reismana49854dda706
diff --git a/rust/capture/src/router.rs b/rust/capture/src/router.rsindex e2d1d471ed1b..6ec31f4a7ddb 100644--- a/rust/capture/src/router.rs+++ b/rust/capture/src/router.rs@@ -79,6 +79,9 @@ pub struct State {/// the kafka sink can route to the replay overflow topic. Same rationale/// as `overflow_limiter` above.pub replay_overflow_limiter: Option<Arc<RedisLimiter>>,+ /// V1 sink router for the new capture analytics pipeline.+ /// When present, the v1 analytics handler publishes events through this.+ pub v1_sink_router: Option<Arc<crate::v1::sinks::Router>>,}#[derive(Clone, Copy)]@@ -146,6 +149,7 @@ pub fn router<TZ: TimeSource + Send + Sync + 'static, R: Client + Send + Sync +capture_v1_max_decompressed_body_bytes: usize,overflow_limiter: Option<Arc<OverflowLimiter>>,replay_overflow_limiter: Option<Arc<RedisLimiter>>,+ v1_sink_router: Option<Arc<crate::v1::sinks::Router>>,) -> Router {let state = State {sink,@@ -170,6 +174,7 @@ pub fn router<TZ: TimeSource + Send + Sync + 'static, R: Client + Send + Sync +capture_v1_max_decompressed_body_bytes,overflow_limiter,replay_overflow_limiter,+ v1_sink_router,};// Very permissive CORS policy, as old SDK versionsdiff --git a/rust/capture/src/server.rs b/rust/capture/src/server.rsindex 9efe7a1b2936..621631fef077 100644--- a/rust/capture/src/server.rs+++ b/rust/capture/src/server.rs@@ -93,6 +93,7 @@ pub async fn serve(listener: TcpListener, components: CaptureComponents) {app,server_handle,sink,+ v1_sink_router,http1_header_read_timeout_ms,} = components;@@ -227,13 +228,17 @@ pub async fn serve(listener: TcpListener, components: CaptureComponents) {graceful.shutdown().await;info!("Hyper accept loop (shutdown): graceful shutdown completed");- // Flush the Kafka producer queue. Events from in-flight handlers may still- // be in rdkafka's internal buffer. flush() blocks until the queue drains or- // times out (default 30s from rdkafka config).- info!("Flushing sink...");+ // Legacy sink flush is synchronous (rdkafka); v1 sinks use spawn_blocking+ // internally (see KafkaSink::flush). Sequential here until legacy is retired.+ info!("Flushing sinks...");if let Err(e) = sink.flush() {error!("Sink flush failed: {e:#}");}+ if let Some(ref v1_router) = v1_sink_router {+ if let Err(e) = v1_router.flush().await {+ error!("V1 sink router flush failed: {e:#}");+ }+ }info!("Sink flush complete");// _scope drops here -> ProcessScopeGuard signals WorkCompleteddiff --git a/rust/capture/src/setup.rs b/rust/capture/src/setup.rsindex 9dd4fcbc6e93..e185549ba961 100644--- a/rust/capture/src/setup.rs+++ b/rust/capture/src/setup.rs@@ -1,6 +1,8 @@+use std::collections::HashMap;use std::sync::Arc;use std::time::Duration;+use anyhow::Context;use axum::Router;use common_redis::RedisClient;use tracing::{info, warn};@@ -30,6 +32,7 @@ pub struct LifecycleHandles {pub sink: Option<lifecycle::Handle>,pub advisory: Option<lifecycle::Handle>,pub event_restrictions: Option<lifecycle::Handle>,+ pub v1_sinks: HashMap<crate::v1::sinks::SinkName, lifecycle::Handle>,pub readiness: lifecycle::ReadinessHandler,pub liveness: lifecycle::LivenessHandler,}@@ -47,10 +50,13 @@ pub fn register_components(manager: &mut lifecycle::Manager, config: &Config) ->(None, None)} else if config.s3_fallback_enabled {let kafka = manager.register("kafka-sink", sink_opts.clone().is_advisory(true));- let s3 = manager.register("s3-sink", sink_opts);+ let s3 = manager.register("s3-sink", sink_opts.clone());(Some(s3), Some(kafka))} else {- (Some(manager.register("kafka-sink", sink_opts)), None)+ (+ Some(manager.register("kafka-sink", sink_opts.clone())),+ None,+ )};let event_restrictions =@@ -60,6 +66,27 @@ pub fn register_components(manager: &mut lifecycle::Manager, config: &Config) ->None};+ let v1_sinks: HashMap<crate::v1::sinks::SinkName, lifecycle::Handle> =+ if !config.capture_v1_sinks.is_empty() {+ crate::v1::sinks::parse_sink_names(&config.capture_v1_sinks)+ .unwrap_or_else(|e| {+ panic!(+ "fatal: failed to parse CAPTURE_V1_SINKS='{}': {e:#}",+ config.capture_v1_sinks+ )+ })+ .into_iter()+ .map(|name| {+ (+ name,+ manager.register(name.lifecycle_tag(), sink_opts.clone()),+ )+ })+ .collect()+ } else {+ HashMap::new()+ };+let readiness = manager.readiness_handler();let liveness = manager.liveness_handler();@@ -68,6 +95,7 @@ pub fn register_components(manager: &mut lifecycle::Manager, config: &Config) ->sink,advisory,event_restrictions,+ v1_sinks,readiness,liveness,}@@ -77,6 +105,7 @@ pub struct CaptureComponents {pub app: Router,pub server_handle: lifecycle::Handle,pub sink: Arc<dyn Event + Send + Sync>,+ pub v1_sink_router: Option<Arc<crate::v1::sinks::Router>>,pub http1_header_read_timeout_ms: Option<u64>,}@@ -86,6 +115,7 @@ pub async fn build_components(config: Config, handles: LifecycleHandles) -> Captsink: sink_handle,advisory: advisory_handle,event_restrictions: event_restrictions_handle,+ v1_sinks: v1_sink_handles,readiness,liveness,} = handles;@@ -255,6 +285,15 @@ pub async fn build_components(config: Config, handles: LifecycleHandles) -> CaptNone};+ let v1_sink_router = if !config.capture_v1_sinks.is_empty() {+ Some(+ create_v1_sink_router(&config, v1_sink_handles)+ .unwrap_or_else(|e| panic!("fatal: v1 sink router creation failed: {e:#}")),+ )+ } else {+ None+ };+let app = router::router(crate::time::SystemTime {},readiness,@@ -283,6 +322,7 @@ pub async fn build_components(config: Config, handles: LifecycleHandles) -> Captconfig.capture_v1_max_decompressed_body_bytes,overflow_limiter,replay_overflow_limiter,+ v1_sink_router.clone(),);info!(@@ -294,10 +334,56 @@ pub async fn build_components(config: Config, handles: LifecycleHandles) -> Captapp,server_handle: server,sink: sink_for_flush,+ v1_sink_router,http1_header_read_timeout_ms: config.http1_header_read_timeout_ms,}}+fn create_v1_sink_router(+ config: &Config,+ handles: HashMap<crate::v1::sinks::SinkName, lifecycle::Handle>,+) -> anyhow::Result<Arc<crate::v1::sinks::Router>> {+ let sinks_cfg = crate::v1::sinks::load_sinks(&config.capture_v1_sinks)+ .context("failed to parse CAPTURE_V1_SINKS")?;+ sinks_cfg+ .validate()+ .context("v1 sink config validation failed")?;++ let mut sink_map: HashMap<crate::v1::sinks::SinkName, Box<dyn crate::v1::sinks::sink::Sink>> =+ HashMap::new();++ for (name, cfg) in sinks_cfg.configs {+ let handle = handles+ .get(&name)+ .cloned()+ .with_context(|| format!("missing lifecycle handle for v1 sink '{name}'"))?;++ let producer = crate::v1::sinks::kafka::producer::KafkaProducer::new(+ name,+ &cfg.kafka,+ handle.clone(),+ config.capture_mode.as_tag(),+ )+ .with_context(|| format!("failed to create v1 kafka producer for sink '{name}'"))?;++ let kafka_sink = crate::v1::sinks::kafka::sink::KafkaSink::new(+ name,+ Arc::new(producer),+ cfg,+ config.capture_mode,+ handle,+ );+ sink_map.insert(name, Box::new(kafka_sink));+ }++ let router = crate::v1::sinks::Router::new(sinks_cfg.default, sink_map);+ info!(+ sinks = config.capture_v1_sinks.as_str(),+ "V1 sink router initialized"+ );+ Ok(Arc::new(router))+}+async fn create_sink(config: &Config,sink_handle: Option<lifecycle::Handle>,@@ -415,3 +501,50 @@ fn create_event_restriction_service(Some(service)}++#[cfg(test)]+mod tests {+ use super::*;+ use std::collections::HashMap;++ #[test]+ fn create_v1_sink_router_fails_on_invalid_config() {+ let cfg_env: HashMap<String, String> = [+ ("REDIS_URL", "redis://localhost:6379/"),+ ("CAPTURE_MODE", "events"),+ ("KAFKA_HOSTS", "localhost:9092"),+ ("KAFKA_TOPIC", "events_plugin_ingestion"),+ ("CAPTURE_V1_SINKS", "msk"),+ ]+ .into_iter()+ .map(|(k, v)| (k.to_string(), v.to_string()))+ .collect();+ let config: Config =+ envconfig::Envconfig::init_from_hashmap(&cfg_env).expect("test config");++ let mut manager = lifecycle::Manager::builder("test")+ .with_trap_signals(false)+ .with_prestop_check(false)+ .build();+ let handles: HashMap<crate::v1::sinks::SinkName, lifecycle::Handle> =+ crate::v1::sinks::parse_sink_names(&config.capture_v1_sinks)+ .unwrap()+ .into_iter()+ .map(|name| {+ (+ name,+ manager.register(name.lifecycle_tag(), lifecycle::ComponentOptions::new()),+ )+ })+ .collect();++ let err = create_v1_sink_router(&config, handles)+ .err()+ .expect("should fail with invalid config");+ let msg = format!("{err:#}");+ assert!(+ msg.contains("msk"),+ "error should name the failing sink: {msg}"+ );+ }+}diff --git a/rust/capture/src/v1/analytics/constants.rs b/rust/capture/src/v1/analytics/constants.rsindex 322e6182d14c..bbcfe0f8d084 100644--- a/rust/capture/src/v1/analytics/constants.rs+++ b/rust/capture/src/v1/analytics/constants.rs@@ -4,12 +4,6 @@ use axum::http::HeaderValue;// HTTP response header values// ----------------------------------------------------------------------------/// JSON Accept header value for analytics responses.-pub const ACCEPT_JSON: HeaderValue = HeaderValue::from_static("application/json");--/// Accepted compression encodings advertised in Accept-Encoding response header.-pub const ACCEPT_ENCODING_ALL: HeaderValue = HeaderValue::from_static("gzip, deflate, br, zstd");-/// Retry-After value (seconds) sent on retryable error responses (408, 5xx)./// SDKs are expected to layer their own jittered exponential backoff on top of this floor.pub const DEFAULT_RETRY_AFTER_SECS: HeaderValue = HeaderValue::from_static("1");diff --git a/rust/capture/src/v1/analytics/handler.rs b/rust/capture/src/v1/analytics/handler.rsindex 94e7dcf3f0ca..8401f5ee2911 100644--- a/rust/capture/src/v1/analytics/handler.rs+++ b/rust/capture/src/v1/analytics/handler.rs@@ -1,10 +1,11 @@use axum::body::Body;use axum::extract::{MatchedPath, Query as AxumQuery, State};use axum::http::{header, HeaderMap, Method};+use axum::response::IntoResponse;use axum_client_ip::InsecureClientIp;+use super::constants::{CAPTURE_V1_PATH, CAPTURE_V1_PATH_TRAILING};use super::query::Query;-use super::response::Response;use super::types::Batch;use tracing::Level;@@ -20,8 +21,16 @@ pub async fn handle_request(method: Method,path: MatchedPath,body: Body,-) -> Result<Response, v1::Error> {- let mut context = Context::new(&headers, &ip, &query, method.clone(), path.as_str())+) -> Result<axum::response::Response, v1::Error> {+ let static_path: &'static str = match path.as_str() {+ CAPTURE_V1_PATH => CAPTURE_V1_PATH,+ CAPTURE_V1_PATH_TRAILING => CAPTURE_V1_PATH_TRAILING,+ other => {+ tracing::warn!(path = other, "unexpected matched path");+ CAPTURE_V1_PATH+ }+ };+ let mut context = Context::new(&headers, &ip, &query, method.clone(), static_path).map_err(|err| log_and_return_header_error(err, &headers, &ip, &query, &method, &path))?;// TODO: purposely chatty, for now@@ -32,7 +41,7 @@ pub async fn handle_request(state.capture_v1_max_compressed_body_bytes,state.body_chunk_read_timeout,state.body_read_chunk_size_kb,- &context.path,+ context.path,).await.map_err(|err| {@@ -59,7 +68,7 @@ pub async fn handle_request(})?;match super::process::process_batch(&state, &mut context, batch).await {- Ok(resp) => Ok(resp),+ Ok(resp) => Ok(resp.into_response()),Err(err) => {log_stat_error!(err, &context);Err(err)@@ -130,3 +139,278 @@ fn raw_header_str<'a>(headers: &'a HeaderMap, name: &str) -> &'a str {.and_then(|v| v.to_str().ok()).unwrap_or("absent")}++#[cfg(test)]+mod tests {+ use axum::body::Body;+ use axum::http::{Request, StatusCode};+ use axum::Router;+ use tower::ServiceExt;+ use uuid::Uuid;++ use crate::router;+ use crate::v1::constants::*;+ use crate::v1::test_utils::{batch_payload, compressed_payload, valid_event, TestStateBuilder};++ fn test_app(state: router::State) -> Router {+ Router::new()+ .route(+ "/i/v1/general/events",+ axum::routing::post(super::handle_request),+ )+ .layer(axum::middleware::from_fn(+ super::super::router::v1_common_headers,+ ))+ .with_state(state)+ }++ fn valid_request() -> axum::http::request::Builder {+ Request::builder()+ .method("POST")+ .uri("/i/v1/general/events")+ .header("Authorization", "Bearer phc_test_token")+ .header("Content-Type", "application/json")+ .header("X-Forwarded-For", "127.0.0.1")+ .header(POSTHOG_SDK_INFO, "posthog-rust/1.0.0")+ .header(POSTHOG_ATTEMPT, "1")+ .header(POSTHOG_REQUEST_ID, Uuid::new_v4().to_string())+ .header(POSTHOG_REQUEST_TIMESTAMP, "2026-03-19T14:30:00Z")+ .header("User-Agent", "test-agent/1.0")+ }++ async fn response_json(resp: axum::response::Response) -> serde_json::Value {+ let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)+ .await+ .unwrap();+ serde_json::from_slice(&bytes).unwrap()+ }++ #[tokio::test]+ async fn happy_path_single_event() {+ let ts = TestStateBuilder::new().build();+ let app = test_app(ts.state);++ let event = valid_event();+ let uuid = event.uuid.clone();+ let payload = batch_payload(&[event]);++ let resp = app+ .oneshot(valid_request().body(Body::from(payload)).unwrap())+ .await+ .unwrap();++ assert_eq!(resp.status(), StatusCode::OK);+ let body = response_json(resp).await;+ let results = body["results"].as_object().unwrap();+ assert_eq!(results[&uuid]["result"], "ok");+ }++ #[tokio::test]+ async fn happy_path_batch() {+ let ts = TestStateBuilder::new().build();+ let app = test_app(ts.state);++ let events = vec![valid_event(), valid_event(), valid_event()];+ let uuids: Vec<String> = events.iter().map(|e| e.uuid.clone()).collect();+ let payload = batch_payload(&events);++ let resp = app+ .oneshot(valid_request().body(Body::from(payload)).unwrap())+ .await+ .unwrap();++ assert_eq!(resp.status(), StatusCode::OK);+ let body = response_json(resp).await;+ let results = body["results"].as_object().unwrap();+ for uuid in &uuids {+ assert_eq!(results[uuid]["result"], "ok");+ }+ }++ #[tokio::test]+ async fn missing_authorization() {+ let ts = TestStateBuilder::new().build();+ let app = test_app(ts.state);++ let payload = batch_payload(&[valid_event()]);+ let req = Request::builder()+ .method("POST")+ .uri("/i/v1/general/events")+ .header("Content-Type", "application/json")+ .header("X-Forwarded-For", "127.0.0.1")+ .header(POSTHOG_SDK_INFO, "posthog-rust/1.0.0")+ .header(POSTHOG_ATTEMPT, "1")+ .header(POSTHOG_REQUEST_ID, Uuid::new_v4().to_string())+ .header(POSTHOG_REQUEST_TIMESTAMP, "2026-03-19T14:30:00Z")+ .header("User-Agent", "test-agent/1.0")+ .body(Body::from(payload))+ .unwrap();++ let resp = app.oneshot(req).await.unwrap();+ assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);+ }++ #[tokio::test]+ async fn missing_required_headers() {+ let ts = TestStateBuilder::new().build();+ let app = test_app(ts.state);++ let payload = batch_payload(&[valid_event()]);+ // Only Authorization and Content-Type — missing SDK-Info, Attempt, etc.+ let req = Request::builder()+ .method("POST")+ .uri("/i/v1/general/events")+ .header("Authorization", "Bearer phc_test_token")+ .header("Content-Type", "application/json")+ .header("X-Forwarded-For", "127.0.0.1")+ .header("User-Agent", "test-agent/1.0")+ .body(Body::from(payload))+ .unwrap();++ let resp = app.oneshot(req).await.unwrap();+ assert_eq!(resp.status(), StatusCode::BAD_REQUEST);+ }++ #[tokio::test]+ async fn empty_body() {+ let ts = TestStateBuilder::new().build();+ let app = test_app(ts.state);++ let resp = app+ .oneshot(valid_request().body(Body::empty()).unwrap())+ .await+ .unwrap();++ assert_eq!(resp.status(), StatusCode::BAD_REQUEST);+ }++ #[tokio::test]+ async fn malformed_json() {+ let ts = TestStateBuilder::new().build();+ let app = test_app(ts.state);++ let garbage = b"not json at all {{{".to_vec();+ let resp = app+ .oneshot(valid_request().body(Body::from(garbage)).unwrap())+ .await+ .unwrap();++ assert_eq!(resp.status(), StatusCode::BAD_REQUEST);+ }++ #[tokio::test]+ async fn empty_batch() {+ let ts = TestStateBuilder::new().build();+ let app = test_app(ts.state);++ let payload = br#"{"created_at":"2026-03-19T14:30:00Z","batch":[]}"#.to_vec();+ let resp = app+ .oneshot(valid_request().body(Body::from(payload)).unwrap())+ .await+ .unwrap();++ assert_eq!(resp.status(), StatusCode::BAD_REQUEST);+ }++ #[tokio::test]+ async fn gzip_compressed_payload() {+ let ts = TestStateBuilder::new().build();+ let app = test_app(ts.state);++ let event = valid_event();+ let uuid = event.uuid.clone();+ let raw = batch_payload(&[event]);+ let compressed = compressed_payload(&raw, "gzip");++ let req = Request::builder()+ .method("POST")+ .uri("/i/v1/general/events")+ .header("Authorization", "Bearer phc_test_token")+ .header("Content-Type", "application/json")+ .header("Content-Encoding", "gzip")+ .header("X-Forwarded-For", "127.0.0.1")+ .header(POSTHOG_SDK_INFO, "posthog-rust/1.0.0")+ .header(POSTHOG_ATTEMPT, "1")+ .header(POSTHOG_REQUEST_ID, Uuid::new_v4().to_string())+ .header(POSTHOG_REQUEST_TIMESTAMP, "2026-03-19T14:30:00Z")+ .header("User-Agent", "test-agent/1.0")+ .body(Body::from(compressed))+ .unwrap();++ let resp = app.oneshot(req).await.unwrap();+ assert_eq!(resp.status(), StatusCode::OK);+ let body = response_json(resp).await;+ assert_eq!(body["results"][&uuid]["result"], "ok");+ }++ #[tokio::test]+ async fn zstd_compressed_payload() {+ let ts = TestStateBuilder::new().build();+ let app = test_app(ts.state);++ let event = valid_event();+ let uuid = event.uuid.clone();+ let raw = batch_payload(&[event]);+ let compressed = compressed_payload(&raw, "zstd");++ let req = Request::builder()+ .method("POST")+ .uri("/i/v1/general/events")+ .header("Authorization", "Bearer phc_test_token")+ .header("Content-Type", "application/json")+ .header("Content-Encoding", "zstd")+ .header("X-Forwarded-For", "127.0.0.1")+ .header(POSTHOG_SDK_INFO, "posthog-rust/1.0.0")+ .header(POSTHOG_ATTEMPT, "1")+ .header(POSTHOG_REQUEST_ID, Uuid::new_v4().to_string())+ .header(POSTHOG_REQUEST_TIMESTAMP, "2026-03-19T14:30:00Z")+ .header("User-Agent", "test-agent/1.0")+ .body(Body::from(compressed))+ .unwrap();++ let resp = app.oneshot(req).await.unwrap();+ assert_eq!(resp.status(), StatusCode::OK);+ let body = response_json(resp).await;+ assert_eq!(body["results"][&uuid]["result"], "ok");+ }++ #[tokio::test]+ async fn unsupported_encoding() {+ let ts = TestStateBuilder::new().build();+ let app = test_app(ts.state);++ let payload = batch_payload(&[valid_event()]);+ let req = Request::builder()+ .method("POST")+ .uri("/i/v1/general/events")+ .header("Authorization", "Bearer phc_test_token")+ .header("Content-Type", "application/json")+ .header("Content-Encoding", "lz4")+ .header("X-Forwarded-For", "127.0.0.1")+ .header(POSTHOG_SDK_INFO, "posthog-rust/1.0.0")+ .header(POSTHOG_ATTEMPT, "1")+ .header(POSTHOG_REQUEST_ID, Uuid::new_v4().to_string())+ .header(POSTHOG_REQUEST_TIMESTAMP, "2026-03-19T14:30:00Z")+ .header("User-Agent", "test-agent/1.0")+ .body(Body::from(payload))+ .unwrap();++ let resp = app.oneshot(req).await.unwrap();+ assert_eq!(resp.status(), StatusCode::UNSUPPORTED_MEDIA_TYPE);+ }++ #[tokio::test]+ async fn service_unavailable_no_sink() {+ let mut ts = TestStateBuilder::new().build();+ ts.state.v1_sink_router = None;+ let app = test_app(ts.state);++ let payload = batch_payload(&[valid_event()]);+ let resp = app+ .oneshot(valid_request().body(Body::from(payload)).unwrap())+ .await+ .unwrap();++ assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE);+ }+}diff --git a/rust/capture/src/v1/analytics/process.rs b/rust/capture/src/v1/analytics/process.rsindex 79e2f1864c44..a5828b2cf9f9 100644--- a/rust/capture/src/v1/analytics/process.rs+++ b/rust/capture/src/v1/analytics/process.rs@@ -10,7 +10,7 @@ use super::constants::{DETAIL_EVENT_RESTRICTION_DROP, DETAIL_PERSON_PROCESSING_DISABLED, FUTURE_EVENT_HOURS_CUTOFF_MS,ILLEGAL_DISTINCT_IDS,};-use super::response::Response;+use super::response::BatchResponse;use super::types::{Batch, Event, EventResult, WrappedEvent};use crate::event_restrictions::{EventContext, EventRestrictionService};use crate::global_rate_limiter::{GlobalRateLimitKey, GlobalRateLimiter};@@ -21,10 +21,17 @@ use tracing::Level;use crate::router;use crate::v1::context::Context;use crate::v1::sinks::event::Event as SinkEvent;+use crate::v1::sinks::types::SinkResult;use crate::v1::sinks::Destination;use crate::v1::Error;/// Maps event name to its Kafka destination, mirroring legacy DataType assignment.+///+/// Unlike legacy capture, v1 does NOT split heatmap/scroll-depth properties out of+/// non-$$heatmap events (e.g. $pageview) into a synthetic redirect. We keep properties+/// as opaque RawValue to avoid deserialization. The Node.js events subpipeline+/// (extractHeatmapDataStep) handles extraction when `skip_heatmap_processing` is unset+/// in Kafka headers — removing that fallback would break scroll-depth heatmaps for v1.fn destination_for_event_name(name: &str) -> Destination {match name {"$exception" => Destination::ExceptionErrorTracking,@@ -38,7 +45,7 @@ pub async fn process_batch(state: &router::State,context: &mut Context,batch: Batch,-) -> Result<Response, Error> {+) -> Result<BatchResponse, Error> {crate::ctx_log!(Level::INFO, context, "process_batch called");validate_batch(&batch)?;@@ -75,8 +82,75 @@ pub async fn process_batch(apply_token_distinct_id_limits(limiter, context, &mut events).await;}- // TODO: publish to v1::Sink, collect results, format + return response- Err(Error::ServiceUnavailable("not yet implemented".into()))+ // Publish to v1 sink, merge results, build response+ let sink_router = state+ .v1_sink_router+ .as_ref()+ .ok_or_else(|| Error::ServiceUnavailable("v1 sink router not configured".into()))?;++ let event_refs: Vec<&(dyn SinkEvent + Send + Sync)> = events+ .iter()+ .filter(|e| SinkEvent::should_publish(*e))+ .map(|e| {+ let r: &(dyn SinkEvent + Send + Sync) = e;+ r+ })+ .collect();++ let sink_results = sink_router+ .publish_batch(sink_router.default_sink(), context, &event_refs)+ .await+ .map_err(|e| Error::InternalError(e.to_string()))?;++ merge_sink_results(&mut events, &sink_results);++ Ok(BatchResponse::build(context, &events))+}++// ---------------------------------------------------------------------------+// SinkResult → WrappedEvent merge+// ---------------------------------------------------------------------------++/// Correlate per-event `SinkResult`s back to the batch of `WrappedEvent`s by UUID.+///+/// Events that were not published (`should_publish() == false`) are untouched.+/// Published events receive updated `result` and `details` based on the sink outcome:+/// - `Outcome::Success` → keep existing result (Ok or Limited)+/// - `Outcome::RetriableError` | `Outcome::Timeout` → `EventResult::Retry`+/// - `Outcome::FatalError` → `EventResult::Drop`+pub fn merge_sink_results(events: &mut [WrappedEvent], sink_results: &[Box<dyn SinkResult>]) {+ use crate::v1::sinks::types::Outcome;++ let results_by_uuid: HashMap<Uuid, &dyn SinkResult> =+ sink_results.iter().map(|r| (r.key(), r.as_ref())).collect();++ for event in events.iter_mut() {+ if !event.should_publish() {+ continue;+ }++ let Some(result) = results_by_uuid.get(&event.uuid) else {+ continue;+ };++ match result.outcome() {+ Outcome::Success => {+ // Leave event.result as-is (Ok or Limited from upstream processing)+ }+ Outcome::RetriableError | Outcome::Timeout => {+ event.result = EventResult::Retry;+ event.details = Some("not_persisted");+ }+ Outcome::FatalError => {+ event.result = EventResult::Drop;+ let cause = result.cause().unwrap_or("rejected");+ event.details = Some(match cause {+ "serialization_failed" | "event_too_big" => cause,+ _ => "rejected",+ });+ }+ }+ }}fn validate_batch(batch: &Batch) -> Result<(), Error> {@@ -733,6 +807,25 @@ mod tests {assert!(matches!(err, Error::MissingEventUuid));}+ #[test]+ fn validate_events_uuid_with_whitespace_trimmed_successfully() {+ let ctx = test_utils::test_context();+ let inner_uuid = Uuid::new_v4();+ let padded_uuid = format!(" {} ", inner_uuid);+ let batch = Batch {+ created_at: "2026-03-19T14:30:00.000Z".to_string(),+ historical_migration: false,+ capture_internal: None,+ batch: vec![Event {+ uuid: padded_uuid,+ ..valid_event()+ }],+ };+ let events = validate_events(&ctx, batch).unwrap();+ assert_eq!(events.len(), 1);+ assert_eq!(events[0].uuid, inner_uuid);+ }+#[test]fn validate_events_malformed_properties() {let ctx = test_utils::test_context();@@ -774,7 +867,7 @@ mod tests {client_ip: std::net::IpAddr::V4(std::net::Ipv4Addr::LOCALHOST),query: crate::v1::analytics::query::Query::default(),method: axum::http::Method::POST,- path: "/i/v1/general/events".to_string(),+ path: "/i/v1/general/events",server_received_at,created_at: None,capture_internal: false,@@ -1830,4 +1923,469 @@ mod tests {assert_eq!(events[0].destination, Destination::AnalyticsMain);}+ // =========================================================================+ // merge_sink_results tests+ // =========================================================================++ use crate::v1::test_utils::MockSinkResult;++ fn mock_result(uuid: Uuid, outcome: &str, cause: &'static str) -> Box<dyn SinkResult> {+ match outcome {+ "success" => MockSinkResult::success(uuid),+ "retriable" => MockSinkResult::retriable(uuid, cause),+ "timeout" => MockSinkResult::timeout(uuid),+ "fatal" => MockSinkResult::fatal(uuid, cause),+ "fatal_no_cause" => MockSinkResult::fatal_no_cause(uuid),+ _ => panic!("unknown outcome: {outcome}"),+ }+ }++ #[rstest::rstest]+ #[case::success("success", "", EventResult::Ok, None)]+ #[case::retriable("retriable", "queue_full", EventResult::Retry, Some("not_persisted"))]+ #[case::timeout("timeout", "", EventResult::Retry, Some("not_persisted"))]+ #[case::fatal_serialization(+ "fatal",+ "serialization_failed",+ EventResult::Drop,+ Some("serialization_failed")+ )]+ #[case::fatal_event_too_big("fatal", "event_too_big", EventResult::Drop, Some("event_too_big"))]+ #[case::fatal_generic("fatal", "rdkafka_other", EventResult::Drop, Some("rejected"))]+ #[case::fatal_no_cause("fatal_no_cause", "", EventResult::Drop, Some("rejected"))]+ fn merge_single_outcome(+ #[case] outcome: &str,+ #[case] cause: &'static str,+ #[case] expected_result: EventResult,+ #[case] expected_details: Option<&'static str>,+ ) {+ let mut events = vec![wrapped_event("$pageview", "user-1")];+ let results: Vec<Box<dyn SinkResult>> = vec![mock_result(events[0].uuid, outcome, cause)];++ merge_sink_results(&mut events, &results);++ assert_eq!(+ events[0].result, expected_result,+ "result for {outcome}:{cause}"+ );+ assert_eq!(+ events[0].details, expected_details,+ "details for {outcome}:{cause}"+ );+ }++ #[test]+ fn merge_preserves_limited_result_on_success() {+ let mut events = vec![wrapped_event("$pageview", "user-1")];+ events[0].result = EventResult::Limited;+ events[0].details = Some("person_processing_disabled");++ let results: Vec<Box<dyn SinkResult>> = vec![MockSinkResult::success(events[0].uuid)];+ merge_sink_results(&mut events, &results);++ assert_eq!(events[0].result, EventResult::Limited);+ assert_eq!(events[0].details, Some("person_processing_disabled"));+ }++ #[test]+ fn merge_skips_events_not_published() {+ let mut events = vec![+ wrapped_event("$pageview", "user-1"),+ wrapped_event("$pageview", "user-2"),+ ];+ events[0].result = EventResult::Drop;+ events[0].details = Some("billing_limit_exceeded");+ events[0].destination = Destination::Drop;++ // Only one sink result (for the published event)+ let results: Vec<Box<dyn SinkResult>> = vec![MockSinkResult::success(events[1].uuid)];++ merge_sink_results(&mut events, &results);++ // Dropped event unchanged+ assert_eq!(events[0].result, EventResult::Drop);+ assert_eq!(events[0].details, Some("billing_limit_exceeded"));+ // Published event left alone+ assert_eq!(events[1].result, EventResult::Ok);+ assert!(events[1].details.is_none());+ }++ #[test]+ fn merge_mixed_outcomes() {+ let mut events = vec![+ wrapped_event("$pageview", "user-1"),+ wrapped_event("$identify", "user-2"),+ wrapped_event("custom", "user-3"),+ ];++ let results: Vec<Box<dyn SinkResult>> = vec![+ MockSinkResult::success(events[0].uuid),+ MockSinkResult::retriable(events[1].uuid, "queue_full"),+ MockSinkResult::fatal(events[2].uuid, "serialization_error"),+ ];++ merge_sink_results(&mut events, &results);++ assert_eq!(events[0].result, EventResult::Ok);+ assert!(events[0].details.is_none());+ assert_eq!(events[1].result, EventResult::Retry);+ assert_eq!(events[1].details, Some("not_persisted"));+ assert_eq!(events[2].result, EventResult::Drop);+ assert_eq!(events[2].details, Some("rejected"));+ }++ #[test]+ fn merge_uuid_correlation_no_crosstalk() {+ let mut events = vec![+ wrapped_event("$pageview", "user-1"),+ wrapped_event("$pageview", "user-2"),+ ];++ // Deliberately swap: result for event[1] is retriable, event[0] is success+ let results: Vec<Box<dyn SinkResult>> = vec![+ MockSinkResult::retriable(events[1].uuid, "queue_full"),+ MockSinkResult::success(events[0].uuid),+ ];++ merge_sink_results(&mut events, &results);++ assert_eq!(events[0].result, EventResult::Ok);+ assert!(events[0].details.is_none());+ assert_eq!(events[1].result, EventResult::Retry);+ assert_eq!(events[1].details, Some("not_persisted"));+ }++ #[test]+ fn merge_empty_sink_results_leaves_all_intact() {+ let mut events = vec![+ wrapped_event("$pageview", "user-1"),+ wrapped_event("$pageview", "user-2"),+ ];+ // All events published but no sink results (edge case - shouldn't+ // happen in practice but should be safe)+ let results: Vec<Box<dyn SinkResult>> = vec![];++ merge_sink_results(&mut events, &results);++ assert_eq!(events[0].result, EventResult::Ok);+ assert_eq!(events[1].result, EventResult::Ok);+ }++ #[test]+ fn merge_pre_drop_not_mutated_even_if_result_present() {+ let mut events = vec![wrapped_event("$pageview", "user-1")];+ events[0].result = EventResult::Drop;+ events[0].details = Some("invalid_distinct_id");++ // Should be unreachable in practice (dropped events aren't published+ // so they won't have a SinkResult), but even if a result exists for+ // this UUID, the event shouldn't be touched because should_publish is false+ let results: Vec<Box<dyn SinkResult>> =+ vec![MockSinkResult::retriable(events[0].uuid, "queue_full")];++ merge_sink_results(&mut events, &results);++ assert_eq!(events[0].result, EventResult::Drop);+ assert_eq!(events[0].details, Some("invalid_distinct_id"));+ }++ #[tokio::test]+ async fn process_batch_returns_service_unavailable_when_no_sink_router() {+ let test_state = crate::v1::test_utils::TestStateBuilder::new().build();+ let mut state = test_state.state;+ state.v1_sink_router = None;++ let mut ctx = test_utils::test_context();+ let batch = valid_batch(vec![valid_event()]);++ let err = process_batch(&state, &mut ctx, batch).await.unwrap_err();+ assert!(+ matches!(err, Error::ServiceUnavailable(_)),+ "expected ServiceUnavailable, got: {err:?}"+ );+ }++ // =========================================================================+ // Integration-style tests: publish → merge → response flow+ // =========================================================================+ // These tests exercise the same code path as the wired process_batch, but+ // call the sink router directly rather than constructing a full State.++ use std::collections::HashMap as StdHashMap;+ use std::sync::Arc;++ use crate::config::CaptureMode;+ use crate::v1::sinks::kafka::mock::MockProducer;+ use crate::v1::sinks::kafka::sink::KafkaSink;+ use crate::v1::sinks::router::Router as SinkRouter;+ use crate::v1::sinks::sink::Sink;+ use crate::v1::sinks::{Config as SinkConfig, SinkName};++ use super::BatchResponse;+ use crate::v1::test_utils::{+ batch_payload, event_with_all_options, event_with_empty_options, WrappedEventMut,+ };++ fn test_sink_router() -> (SinkRouter, lifecycle::Handle, lifecycle::MonitorGuard) {+ let mut manager = lifecycle::Manager::builder("test")+ .with_trap_signals(false)+ .with_prestop_check(false)+ .build();+ let handle = manager.register("process_integ", lifecycle::ComponentOptions::new());+ handle.report_healthy();+ let monitor = manager.monitor_background();++ let producer = Arc::new(MockProducer::new(SinkName::Msk, handle.clone()));+ let config = SinkConfig {+ produce_timeout: StdDuration::from_secs(30),+ kafka: test_utils::test_kafka_config(),+ };+ let sink: Box<dyn Sink> = Box::new(KafkaSink::new(+ SinkName::Msk,+ producer,+ config,+ CaptureMode::Events,+ handle.clone(),+ ));+ let sinks: StdHashMap<SinkName, Box<dyn Sink>> =+ [(SinkName::Msk, sink)].into_iter().collect();+ let router = SinkRouter::new(SinkName::Msk, sinks);+ (router, handle, monitor)+ }++ #[tokio::test]+ async fn integration_happy_path_all_ok() {+ let (router, _handle, _monitor) = test_sink_router();+ let mut ctx = test_utils::test_context();+ ctx.created_at = None;++ let mut events = vec![+ wrapped_event("$pageview", "user-1"),+ wrapped_event("$identify", "user-2"),+ wrapped_event("button_clicked", "user-3"),+ ];++ let event_refs: Vec<&(dyn crate::v1::sinks::event::Event + Send + Sync)> = events+ .iter()+ .filter(|e| SinkEvent::should_publish(*e))+ .map(|e| {+ let r: &(dyn crate::v1::sinks::event::Event + Send + Sync) = e;+ r+ })+ .collect();++ let sink_results = router+ .publish_batch(router.default_sink(), &ctx, &event_refs)+ .await+ .unwrap();++ merge_sink_results(&mut events, &sink_results);+ let resp = BatchResponse::build(&ctx, &events);++ assert!(!resp.has_retry);+ assert_eq!(resp.entries().len(), 3);+ for (_, status) in resp.entries() {+ assert_eq!(status.result, EventResult::Ok);+ assert!(status.details.is_none());+ }+ }++ #[tokio::test]+ async fn integration_mixed_pre_drop_and_publish() {+ let (router, _handle, _monitor) = test_sink_router();+ let mut ctx = test_utils::test_context();+ ctx.created_at = None;++ let mut events = vec![+ wrapped_event("$pageview", "user-1"),+ wrapped_event("$pageview", "user-2")+ .with_result(EventResult::Drop, Some("billing_limit_exceeded")),+ wrapped_event("$pageview", "user-3")+ .with_result(EventResult::Limited, Some("person_processing_disabled")),+ ];++ let event_refs: Vec<&(dyn crate::v1::sinks::event::Event + Send + Sync)> = events+ .iter()+ .filter(|e| SinkEvent::should_publish(*e))+ .map(|e| {+ let r: &(dyn crate::v1::sinks::event::Event + Send + Sync) = e;+ r+ })+ .collect();++ assert_eq!(event_refs.len(), 2); // only Ok + Limited are published++ let sink_results = router+ .publish_batch(router.default_sink(), &ctx, &event_refs)+ .await+ .unwrap();++ merge_sink_results(&mut events, &sink_results);+ let resp = BatchResponse::build(&ctx, &events);++ assert!(!resp.has_retry);+ assert_eq!(resp.entries().len(), 3);+ assert_eq!(resp.entries()[0].1.result, EventResult::Ok);+ assert_eq!(resp.entries()[1].1.result, EventResult::Drop);+ assert_eq!(resp.entries()[1].1.details, Some("billing_limit_exceeded"));+ assert_eq!(resp.entries()[2].1.result, EventResult::Limited);+ assert_eq!(+ resp.entries()[2].1.details,+ Some("person_processing_disabled")+ );+ }++ #[tokio::test]+ async fn integration_all_events_pre_dropped_empty_publish() {+ let (router, _handle, _monitor) = test_sink_router();+ let mut ctx = test_utils::test_context();+ ctx.created_at = None;++ let mut events = vec![+ wrapped_event("$pageview", "user-1")+ .with_result(EventResult::Drop, Some("billing_limit_exceeded")),+ wrapped_event("$pageview", "user-2")+ .with_result(EventResult::Drop, Some("billing_limit_exceeded")),+ ];++ let event_refs: Vec<&(dyn crate::v1::sinks::event::Event + Send + Sync)> = events+ .iter()+ .filter(|e| SinkEvent::should_publish(*e))+ .map(|e| {+ let r: &(dyn crate::v1::sinks::event::Event + Send + Sync) = e;+ r+ })+ .collect();++ assert!(event_refs.is_empty());++ let sink_results = router+ .publish_batch(router.default_sink(), &ctx, &event_refs)+ .await+ .unwrap();++ merge_sink_results(&mut events, &sink_results);+ let resp = BatchResponse::build(&ctx, &events);++ assert!(!resp.has_retry);+ assert_eq!(resp.entries().len(), 2);+ assert_eq!(resp.entries()[0].1.result, EventResult::Drop);+ assert_eq!(resp.entries()[1].1.result, EventResult::Drop);+ }++ #[tokio::test]+ async fn integration_overflow_destination_published_ok() {+ let (router, _handle, _monitor) = test_sink_router();+ let mut ctx = test_utils::test_context();+ ctx.created_at = None;++ let mut events =+ vec![wrapped_event("$pageview", "user-1").with_destination(Destination::Overflow)];++ let event_refs: Vec<&(dyn crate::v1::sinks::event::Event + Send + Sync)> = events+ .iter()+ .filter(|e| SinkEvent::should_publish(*e))+ .map(|e| {+ let r: &(dyn crate::v1::sinks::event::Event + Send + Sync) = e;+ r+ })+ .collect();++ let sink_results = router+ .publish_batch(router.default_sink(), &ctx, &event_refs)+ .await+ .unwrap();++ merge_sink_results(&mut events, &sink_results);+ let resp = BatchResponse::build(&ctx, &events);++ assert!(!resp.has_retry);+ assert_eq!(resp.entries()[0].1.result, EventResult::Ok);+ }++ #[test]+ fn integration_payload_round_trip_empty_options() {+ let events = vec![event_with_empty_options()];+ let payload = batch_payload(&events);+ let batch: Batch = serde_json::from_slice(&payload).unwrap();+ assert_eq!(batch.batch.len(), 1);+ assert_eq!(batch.batch[0].options.cookieless_mode, None);+ assert_eq!(batch.batch[0].options.disable_skew_correction, None);+ assert_eq!(batch.batch[0].options.product_tour_id, None);+ assert_eq!(batch.batch[0].options.process_person_profile, None);+ }++ #[test]+ fn integration_payload_round_trip_all_options() {+ let events = vec![event_with_all_options()];+ let payload = batch_payload(&events);+ let batch: Batch = serde_json::from_slice(&payload).unwrap();+ assert_eq!(batch.batch.len(), 1);+ assert_eq!(batch.batch[0].options.cookieless_mode, Some(true));+ assert_eq!(batch.batch[0].options.disable_skew_correction, Some(true));+ assert_eq!(+ batch.batch[0].options.product_tour_id.as_deref(),+ Some("tour-v2")+ );+ assert_eq!(batch.batch[0].options.process_person_profile, Some(false));+ }++ #[cfg(test)]+ #[test]+ fn integration_compressed_payload_gzip() {+ use crate::v1::test_utils::compressed_payload;+ let events = vec![valid_event()];+ let raw = batch_payload(&events);+ let compressed = compressed_payload(&raw, "gzip");+ assert!(compressed.len() < raw.len());+ // Decompress and verify+ use flate2::read::GzDecoder;+ use std::io::Read;+ let mut decoder = GzDecoder::new(compressed.as_slice());+ let mut decompressed = Vec::new();+ decoder.read_to_end(&mut decompressed).unwrap();+ assert_eq!(decompressed, raw);+ }++ #[cfg(test)]+ #[test]+ fn integration_compressed_payload_zstd() {+ use crate::v1::test_utils::compressed_payload;+ let events = vec![valid_event()];+ let raw = batch_payload(&events);+ let compressed = compressed_payload(&raw, "zstd");+ assert!(compressed.len() < raw.len());+ let decompressed = zstd::decode_all(std::io::Cursor::new(&compressed)).unwrap();+ assert_eq!(decompressed, raw);+ }++ #[cfg(test)]+ #[test]+ fn integration_compressed_payload_deflate() {+ use crate::v1::test_utils::compressed_payload;+ let events = vec![valid_event()];+ let raw = batch_payload(&events);+ let compressed = compressed_payload(&raw, "deflate");+ assert!(compressed.len() < raw.len());+ use flate2::read::DeflateDecoder;+ use std::io::Read;+ let mut decoder = DeflateDecoder::new(compressed.as_slice());+ let mut decompressed = Vec::new();+ decoder.read_to_end(&mut decompressed).unwrap();+ assert_eq!(decompressed, raw);+ }++ #[cfg(test)]+ #[test]+ fn integration_compressed_payload_brotli() {+ use crate::v1::test_utils::compressed_payload;+ let events = vec![valid_event()];+ let raw = batch_payload(&events);+ let compressed = compressed_payload(&raw, "br");+ assert!(!compressed.is_empty());+ let mut decompressed = Vec::new();+ brotli::BrotliDecompress(&mut std::io::Cursor::new(&compressed), &mut decompressed)+ .unwrap();+ assert_eq!(decompressed, raw);+ }}diff --git a/rust/capture/src/v1/analytics/response.rs b/rust/capture/src/v1/analytics/response.rsindex ad4c2e6d8166..d91c3c58e4c8 100644--- a/rust/capture/src/v1/analytics/response.rs+++ b/rust/capture/src/v1/analytics/response.rs@@ -1 +1,335 @@-pub type Response = axum::http::Response<axum::body::Body>;+use axum::http::{header, HeaderValue, StatusCode};+use axum::response::IntoResponse;+use serde::ser::{SerializeMap, SerializeStruct};+use serde::Serialize;+use uuid::Uuid;++use super::constants::DEFAULT_RETRY_AFTER_SECS;+use super::types::{EventResult, WrappedEvent};+use crate::v1::context::Context;++// ---------------------------------------------------------------------------+// BatchEntryStatus+// ---------------------------------------------------------------------------++/// Per-event outcome communicated to the SDK in the 200 response body.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct BatchEntryStatus {+ pub result: EventResult,+ pub details: Option<&'static str>,+}++impl Serialize for BatchEntryStatus {+ fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {+ let field_count = if self.details.is_some() { 2 } else { 1 };+ let mut state = serializer.serialize_struct("BatchEntryStatus", field_count)?;+ state.serialize_field("result", &self.result)?;+ if let Some(detail) = self.details {+ state.serialize_field("details", detail)?;+ }+ state.end()+ }+}++// ---------------------------------------------------------------------------+// BatchResponse+// ---------------------------------------------------------------------------++/// 200 OK response for the V1 analytics batch endpoint.+///+/// Preserves event insertion order via a Vec (events arrive in batch-index+/// order and are never reordered during processing).+#[derive(Debug)]+pub struct BatchResponse {+ pub has_retry: bool,+ entries: Vec<(Uuid, BatchEntryStatus)>,+}++impl BatchResponse {+ /// Build the response from a processed batch of WrappedEvents.+ /// Call this after sink publishing and result merging are complete.+ pub fn build(ctx: &Context, events: &[WrappedEvent]) -> Self {+ let _ = ctx; // Context reserved for future per-response metadata+ let mut has_retry = false;+ let entries: Vec<(Uuid, BatchEntryStatus)> = events+ .iter()+ .map(|ev| {+ if ev.result == EventResult::Retry {+ has_retry = true;+ }+ (+ ev.uuid,+ BatchEntryStatus {+ result: ev.result,+ details: ev.details,+ },+ )+ })+ .collect();++ Self { has_retry, entries }+ }++ pub fn entries(&self) -> &[(Uuid, BatchEntryStatus)] {+ &self.entries+ }+}++/// Wrapper for serializing the response body as `{"results": {uuid: status, ...}}`.+struct ResponseBody<'a>(&'a [(Uuid, BatchEntryStatus)]);++impl Serialize for ResponseBody<'_> {+ fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {+ let mut outer = serializer.serialize_struct("ResponseBody", 1)?;+ outer.serialize_field("results", &ResultsMap(self.0))?;+ outer.end()+ }+}++struct ResultsMap<'a>(&'a [(Uuid, BatchEntryStatus)]);++impl Serialize for ResultsMap<'_> {+ fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {+ let mut map = serializer.serialize_map(Some(self.0.len()))?;+ for (uuid, status) in self.0 {+ map.serialize_entry(&uuid.to_string(), status)?;+ }+ map.end()+ }+}++impl IntoResponse for BatchResponse {+ fn into_response(self) -> axum::response::Response {+ let body = serde_json::to_vec(&ResponseBody(&self.entries))+ .expect("BatchResponse serialization cannot fail");++ let mut response = (StatusCode::OK, body).into_response();+ let headers = response.headers_mut();++ headers.insert(+ header::CONTENT_TYPE,+ HeaderValue::from_static("application/json"),+ );++ if self.has_retry {+ headers.insert(header::RETRY_AFTER, DEFAULT_RETRY_AFTER_SECS);+ }++ response+ }+}++// ---------------------------------------------------------------------------+// Tests+// ---------------------------------------------------------------------------++#[cfg(test)]+mod tests {+ use axum::body::to_bytes;+ use axum::response::IntoResponse;+ use chrono::Utc;+ use serde_json::Value;+ use uuid::Uuid;++ use super::*;+ use crate::v1::analytics::types::{Event, EventResult, Options, WrappedEvent};+ use crate::v1::sinks::Destination;+ use crate::v1::test_utils;++ fn make_wrapped(result: EventResult, details: Option<&'static str>) -> WrappedEvent {+ let uuid = Uuid::new_v4();+ WrappedEvent {+ event: Event {+ event: "$pageview".to_string(),+ uuid: uuid.to_string(),+ distinct_id: "user-1".to_string(),+ timestamp: "2026-03-19T14:29:58.123Z".to_string(),+ session_id: None,+ window_id: None,+ options: Options {+ cookieless_mode: None,+ disable_skew_correction: None,+ product_tour_id: None,+ process_person_profile: None,+ },+ properties: serde_json::value::RawValue::from_string("{}".to_owned()).unwrap(),+ },+ uuid,+ adjusted_timestamp: Some(Utc::now()),+ result,+ details,+ destination: Destination::AnalyticsMain,+ force_disable_person_processing: false,+ }+ }++ #[test]+ fn batch_entry_status_serialize_ok() {+ let status = BatchEntryStatus {+ result: EventResult::Ok,+ details: None,+ };+ let json = serde_json::to_string(&status).unwrap();+ assert_eq!(json, r#"{"result":"ok"}"#);+ }++ #[test]+ fn batch_entry_status_serialize_with_details() {+ let status = BatchEntryStatus {+ result: EventResult::Retry,+ details: Some("not_persisted"),+ };+ let json = serde_json::to_string(&status).unwrap();+ assert_eq!(json, r#"{"result":"retry","details":"not_persisted"}"#);+ }++ #[test]+ fn batch_entry_status_serialize_drop_with_details() {+ let status = BatchEntryStatus {+ result: EventResult::Drop,+ details: Some("billing_limit_exceeded"),+ };+ let json = serde_json::to_string(&status).unwrap();+ assert_eq!(+ json,+ r#"{"result":"drop","details":"billing_limit_exceeded"}"#+ );+ }++ #[test]+ fn batch_entry_status_serialize_limited_with_details() {+ let status = BatchEntryStatus {+ result: EventResult::Limited,+ details: Some("person_processing_disabled"),+ };+ let json = serde_json::to_string(&status).unwrap();+ assert_eq!(+ json,+ r#"{"result":"limited","details":"person_processing_disabled"}"#+ );+ }++ #[test]+ fn batch_response_build_all_ok() {+ let ctx = test_utils::test_context();+ let events = vec![+ make_wrapped(EventResult::Ok, None),+ make_wrapped(EventResult::Ok, None),+ ];+ let resp = BatchResponse::build(&ctx, &events);+ assert!(!resp.has_retry);+ assert_eq!(resp.entries().len(), 2);+ for (uuid, status) in resp.entries() {+ assert_eq!(status.result, EventResult::Ok);+ assert!(status.details.is_none());+ assert_ne!(*uuid, Uuid::nil());+ }+ }++ #[test]+ fn batch_response_build_mixed() {+ let ctx = test_utils::test_context();+ let events = vec![+ make_wrapped(EventResult::Ok, None),+ make_wrapped(EventResult::Drop, Some("billing_limit_exceeded")),+ make_wrapped(EventResult::Limited, Some("person_processing_disabled")),+ make_wrapped(EventResult::Retry, Some("not_persisted")),+ ];+ let resp = BatchResponse::build(&ctx, &events);+ assert!(resp.has_retry);+ assert_eq!(resp.entries().len(), 4);+ assert_eq!(resp.entries()[0].1.result, EventResult::Ok);+ assert_eq!(resp.entries()[1].1.result, EventResult::Drop);+ assert_eq!(resp.entries()[2].1.result, EventResult::Limited);+ assert_eq!(resp.entries()[3].1.result, EventResult::Retry);+ }++ #[test]+ fn batch_response_has_retry_false_when_no_retry() {+ let ctx = test_utils::test_context();+ let events = vec![+ make_wrapped(EventResult::Ok, None),+ make_wrapped(EventResult::Drop, Some("billing")),+ make_wrapped(EventResult::Limited, Some("pp_disabled")),+ ];+ let resp = BatchResponse::build(&ctx, &events);+ assert!(!resp.has_retry);+ }++ #[test]+ fn batch_response_preserves_insertion_order() {+ let ctx = test_utils::test_context();+ let events = vec![+ make_wrapped(EventResult::Ok, None),+ make_wrapped(EventResult::Retry, Some("not_persisted")),+ make_wrapped(EventResult::Ok, None),+ ];+ let uuids: Vec<Uuid> = events.iter().map(|e| e.uuid).collect();+ let resp = BatchResponse::build(&ctx, &events);+ let resp_uuids: Vec<Uuid> = resp.entries().iter().map(|(u, _)| *u).collect();+ assert_eq!(resp_uuids, uuids);+ }++ #[tokio::test]+ async fn into_response_status_200() {+ let ctx = test_utils::test_context();+ let events = vec![make_wrapped(EventResult::Ok, None)];+ let resp = BatchResponse::build(&ctx, &events).into_response();+ assert_eq!(resp.status(), StatusCode::OK);+ }++ #[tokio::test]+ async fn into_response_content_type_json() {+ let ctx = test_utils::test_context();+ let events = vec![make_wrapped(EventResult::Ok, None)];+ let resp = BatchResponse::build(&ctx, &events).into_response();+ assert_eq!(+ resp.headers().get(header::CONTENT_TYPE).unwrap(),+ "application/json"+ );+ }++ #[tokio::test]+ async fn into_response_retry_after_present_when_retry() {+ let ctx = test_utils::test_context();+ let events = vec![make_wrapped(EventResult::Retry, Some("not_persisted"))];+ let resp = BatchResponse::build(&ctx, &events).into_response();+ let hdr = resp+ .headers()+ .get(header::RETRY_AFTER)+ .expect("Retry-After header should be present");+ assert_eq!(hdr.to_str().unwrap(), "1");+ }++ #[tokio::test]+ async fn into_response_retry_after_absent_when_no_retry() {+ let ctx = test_utils::test_context();+ let events = vec![make_wrapped(EventResult::Ok, None)];+ let resp = BatchResponse::build(&ctx, &events).into_response();+ assert!(resp.headers().get(header::RETRY_AFTER).is_none());+ }++ #[tokio::test]+ async fn into_response_body_json_shape() {+ let ctx = test_utils::test_context();+ let events = vec![+ make_wrapped(EventResult::Ok, None),+ make_wrapped(EventResult::Drop, Some("billing_limit_exceeded")),+ ];+ let uuids: Vec<String> = events.iter().map(|e| e.uuid.to_string()).collect();+ let resp = BatchResponse::build(&ctx, &events).into_response();+ let body_bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();+ let body: Value = serde_json::from_slice(&body_bytes).unwrap();++ let results = body.get("results").expect("results key must exist");+ assert!(results.is_object());++ let first = results.get(&uuids[0]).unwrap();+ assert_eq!(first["result"], "ok");+ assert!(!first.as_object().unwrap().contains_key("details"));++ let second = results.get(&uuids[1]).unwrap();+ assert_eq!(second["result"], "drop");+ assert_eq!(second["details"], "billing_limit_exceeded");+ }+}diff --git a/rust/capture/src/v1/analytics/router.rs b/rust/capture/src/v1/analytics/router.rsindex de47bc47736d..34dcf9c92ce6 100644--- a/rust/capture/src/v1/analytics/router.rs+++ b/rust/capture/src/v1/analytics/router.rs@@ -38,7 +38,6 @@ pub(super) async fn v1_common_headers(req: Request, next: Next) -> Response {if let Some(id) = request_id {headers.insert(POSTHOG_REQUEST_ID, id);}-response}@@ -115,6 +114,24 @@ mod tests {);}+ #[tokio::test]+ async fn common_headers_does_not_set_accept_or_accept_encoding() {+ let resp = test_router()+ .oneshot(Request::builder().uri("/test").body(Body::empty()).unwrap())+ .await+ .unwrap();++ assert_eq!(resp.status(), StatusCode::OK);+ assert!(+ resp.headers().get(header::ACCEPT).is_none(),+ "Accept is a request-semantics header and should not be on responses"+ );+ assert!(+ resp.headers().get(header::ACCEPT_ENCODING).is_none(),+ "Accept-Encoding is a request-semantics header and should not be on responses"+ );+ }+#[tokio::test]async fn common_headers_passes_through_request_id() {let id = Uuid::new_v4().to_string();diff --git a/rust/capture/src/v1/analytics/types.rs b/rust/capture/src/v1/analytics/types.rsindex b887923205b0..7566eabe9b69 100644--- a/rust/capture/src/v1/analytics/types.rs+++ b/rust/capture/src/v1/analytics/types.rs@@ -1023,6 +1023,19 @@ mod tests {(captured, data)}+ #[test]+ fn serialize_into_fails_without_adjusted_timestamp() {+ let mut ev = pageview_event();+ ev.adjusted_timestamp = None;+ let ctx = serialize_ctx();+ let mut buf = String::new();+ let err = ev.serialize_into(&ctx, &mut buf).unwrap_err();+ assert!(+ err.to_string().contains("adjusted_timestamp"),+ "error should mention adjusted_timestamp: {err}"+ );+ }+#[test]fn serialize_round_trip_basic() {let wrapped = pageview_event();@@ -1482,4 +1495,158 @@ mod tests {assert_eq!(data.properties["$session_id"], "sess-abc");assert_eq!(data.properties.len(), 1);}++ // --- CapturedEvent round-trip parity using realistic fixtures ---++ use crate::v1::test_utils::{+ assert_round_trip, realistic_batch, realistic_custom, realistic_identify,+ realistic_pageview, realistic_spread_destinations, WrappedEventMut,+ };++ #[test]+ fn round_trip_realistic_pageview() {+ let ctx = serialize_ctx();+ let ev = realistic_pageview("user-42");+ let (captured, data) = assert_round_trip(&ev, &ctx);+ assert_eq!(captured.event, "$pageview");+ assert_eq!(captured.distinct_id, "user-42");+ assert_eq!(+ data.properties["$current_url"],+ "https://app.example.com/dashboard"+ );+ assert_eq!(+ data.properties["$session_id"],+ "01jq9abc-def0-1234-5678-9abcdef01234"+ );+ assert_eq!(+ data.properties["$window_id"],+ "01jq9xyz-0000-4321-8765-fedcba987654"+ );+ assert_eq!(data.properties["$cookieless_mode"], false);+ assert_eq!(data.properties["$process_person_profile"], true);+ }++ #[test]+ fn round_trip_realistic_identify() {+ let ctx = serialize_ctx();+ let ev = realistic_identify("user-99");+ let (captured, data) = assert_round_trip(&ev, &ctx);+ assert_eq!(captured.event, "$identify");+ assert_eq!(captured.distinct_id, "user-99");+ assert_eq!(data.properties["$set"]["email"], "[email protected]");+ assert_eq!(data.properties["$process_person_profile"], true);+ }++ #[test]+ fn round_trip_realistic_custom() {+ let ctx = serialize_ctx();+ let ev = realistic_custom("user-7", "button_clicked");+ let (captured, data) = assert_round_trip(&ev, &ctx);+ assert_eq!(captured.event, "button_clicked");+ assert_eq!(data.properties["button_id"], "cta-signup");+ assert_eq!(data.properties["$process_person_profile"], true);+ }++ #[test]+ fn round_trip_realistic_batch_all_events() {+ let ctx = serialize_ctx();+ for ev in &realistic_batch() {+ assert_round_trip(ev, &ctx);+ }+ }++ #[test]+ fn round_trip_spread_destinations() {+ let ctx = serialize_ctx();+ for ev in &realistic_spread_destinations() {+ if (ev.result == EventResult::Ok || ev.result == EventResult::Limited)+ && ev.adjusted_timestamp.is_some()+ {+ assert_round_trip(ev, &ctx);+ }+ }+ }++ // --- Kafka header parity checks ---++ #[test]+ fn headers_parity_pageview() {+ let ctx = serialize_ctx();+ let ev = realistic_pageview("user-42");+ let h = ev.headers(&ctx);+ assert_eq!(h.token, Some(ctx.api_token.clone()));+ assert_eq!(h.distinct_id.as_deref(), Some("user-42"));+ assert_eq!(h.event.as_deref(), Some("$pageview"));+ assert_eq!(+ h.session_id.as_deref(),+ Some("01jq9abc-def0-1234-5678-9abcdef01234")+ );+ assert!(h.uuid.is_some());+ assert!(h.timestamp.is_some());+ assert!(h.force_disable_person_processing.is_none());+ assert!(h.historical_migration.is_none());+ }++ #[test]+ fn headers_parity_historical_migration() {+ let mut ctx = serialize_ctx();+ ctx.historical_migration = true;+ let ev = realistic_pageview("user-42");+ let h = ev.headers(&ctx);+ assert_eq!(h.historical_migration, Some(true));+ }++ #[test]+ fn headers_parity_force_disable_person_processing() {+ let ctx = serialize_ctx();+ let ev = realistic_pageview("user-42").with_force_disable_person_processing(true);+ let h = ev.headers(&ctx);+ assert_eq!(h.force_disable_person_processing, Some(true));+ }++ #[test]+ fn headers_parity_dlq_destination() {+ let ctx = serialize_ctx();+ let ev = realistic_pageview("user-42").with_destination(Destination::Dlq);+ let h = ev.headers(&ctx);+ assert_eq!(h.dlq_reason.as_deref(), Some("event_restriction"));+ assert_eq!(h.dlq_step.as_deref(), Some("capture"));+ assert!(h.dlq_timestamp.is_some());+ }++ // --- Partition key parity ---++ #[test]+ fn partition_key_parity_normal() {+ let ctx = serialize_ctx();+ let ev = realistic_pageview("user-42");+ let mut buf = String::new();+ ev.partition_key(&ctx, &mut buf);+ assert_eq!(buf, format!("{}:user-42", ctx.api_token));+ }++ #[test]+ fn partition_key_parity_cookieless() {+ let ctx = serialize_ctx();+ let mut ev = realistic_pageview("user-42");+ ev.event.options.cookieless_mode = Some(true);+ let mut buf = String::new();+ ev.partition_key(&ctx, &mut buf);+ assert_eq!(buf, format!("{}:{}", ctx.api_token, ctx.client_ip));+ }++ #[test]+ fn partition_key_parity_force_disable_main() {+ let ctx = serialize_ctx();+ let ev = realistic_pageview("user-42")+ .with_force_disable_person_processing(true)+ .with_destination(Destination::AnalyticsMain);+ let mut buf = String::new();+ ev.partition_key(&ctx, &mut buf);+ assert_eq!(+ buf,+ format!("{}:user-42", ctx.api_token),+ "partition_key() is unconditional; sink applies null-key policy"+ );+ }}diff --git a/rust/capture/src/v1/context.rs b/rust/capture/src/v1/context.rsindex b22e5f7f1b3f..e5ef16328028 100644--- a/rust/capture/src/v1/context.rs+++ b/rust/capture/src/v1/context.rs@@ -25,7 +25,7 @@ pub struct Context {pub client_ip: IpAddr,pub query: Query,pub method: Method,- pub path: String,+ pub path: &'static str,pub server_received_at: DateTime<Utc>,pub created_at: Option<String>,pub capture_internal: bool,@@ -53,7 +53,7 @@ impl Context {ip: &InsecureClientIp,query: &AxumQuery<Query>,method: Method,- path: &str,+ path: &'static str,) -> Result<Self, Error> {// Authorization checked first — missing auth is 401, not 400if headers.get(header::AUTHORIZATION).is_none() {@@ -154,7 +154,7 @@ impl Context {client_ip: ip.0,query: query.0.clone(),method,- path: path.to_string(),+ path,server_received_at: Utc::now(),created_at: None,capture_internal: false,diff --git a/rust/capture/src/v1/error.rs b/rust/capture/src/v1/error.rsindex 3d3aa8ae95cd..2ebdf1b32ffc 100644--- a/rust/capture/src/v1/error.rs+++ b/rust/capture/src/v1/error.rs@@ -6,7 +6,7 @@ use serde::Serialize;use thiserror::Error;use tracing::Level;-use crate::v1::analytics::constants::{ACCEPT_ENCODING_ALL, ACCEPT_JSON, DEFAULT_RETRY_AFTER_SECS};+use crate::v1::analytics::constants::DEFAULT_RETRY_AFTER_SECS;use crate::v1::constants::{CAPTURE_V1_ERROR_METRIC, CAPTURE_V1_UNKNOWN_PATH};use crate::v1::context::Context;@@ -211,9 +211,7 @@ impl Error {}pub(crate) fn stat_error(&self, ctx: Option<&Context>) {- let path = ctx- .map(|c| c.path.clone())- .unwrap_or_else(|| CAPTURE_V1_UNKNOWN_PATH.to_owned());+ let path = ctx.map(|c| c.path).unwrap_or(CAPTURE_V1_UNKNOWN_PATH);let status = self.status_code().as_str().to_owned();counter!(CAPTURE_V1_ERROR_METRIC,@@ -268,8 +266,6 @@ impl Error {pub fn response_headers(&self) -> HeaderMap {let mut headers = HeaderMap::new();- headers.insert(header::ACCEPT, ACCEPT_JSON);- headers.insert(header::ACCEPT_ENCODING, ACCEPT_ENCODING_ALL);// 402 (BillingLimitExceeded) is intentionally non-retryable per RFC, so no Retry-After.if matches!(diff --git a/rust/capture/src/v1/sinks/kafka/sink.rs b/rust/capture/src/v1/sinks/kafka/sink.rsindex 808a78438fae..3d5caa769727 100644--- a/rust/capture/src/v1/sinks/kafka/sink.rs+++ b/rust/capture/src/v1/sinks/kafka/sink.rs@@ -44,12 +44,10 @@ fn effective_partition_key<'a>(}/// Shared label values for metrics emitted within a single `publish_batch` call.-/// All fields are `&'static str` (zero-cost) or `SharedString` (Arc-based, so-/// `.clone()` is a refcount bump rather than a heap allocation).struct MetricLabels {sink: &'static str,mode: &'static str,- path: metrics::SharedString,+ path: &'static str,attempt: metrics::SharedString,}@@ -92,7 +90,7 @@ fn reject_publishable("mode" => labels.mode,"cluster" => labels.sink,"outcome" => Outcome::RetriableError.as_tag(),- "path" => labels.path.clone(),+ "path" => labels.path,"attempt" => labels.attempt.clone(),).increment(publishable.len() as u64);@@ -166,7 +164,7 @@ impl<P: KafkaProducerTrait + 'static> KafkaSink<P> {"mode" => labels.mode,"cluster" => labels.sink,"outcome" => Outcome::FatalError.as_tag(),- "path" => labels.path.clone(),+ "path" => labels.path,"attempt" => labels.attempt.clone(),).increment(1);@@ -250,7 +248,7 @@ impl<P: KafkaProducerTrait + 'static> KafkaSink<P> {"mode" => labels.mode,"cluster" => labels.sink,"outcome" => outcome.as_tag(),- "path" => labels.path.clone(),+ "path" => labels.path,"attempt" => labels.attempt.clone(),).increment(1);@@ -298,7 +296,7 @@ impl<P: KafkaProducerTrait + 'static> KafkaSink<P> {"mode" => labels.mode,"cluster" => labels.sink,"outcome" => outcome_tag,- "path" => labels.path.clone(),+ "path" => labels.path,"attempt" => labels.attempt.clone(),).increment(1);@@ -310,7 +308,7 @@ impl<P: KafkaProducerTrait + 'static> KafkaSink<P> {"mode" => labels.mode,"cluster" => labels.sink,"outcome" => outcome_tag,- "path" => labels.path.clone(),+ "path" => labels.path,"attempt" => labels.attempt.clone(),).record(secs.as_secs_f64());@@ -354,7 +352,7 @@ impl<P: KafkaProducerTrait + 'static> KafkaSink<P> {"mode" => labels.mode,"cluster" => labels.sink,"outcome" => Outcome::Timeout.as_tag(),- "path" => labels.path.clone(),+ "path" => labels.path,"attempt" => labels.attempt.clone(),).increment(timed_out_keys.len() as u64);@@ -382,7 +380,7 @@ impl<P: KafkaProducerTrait + 'static> Sink for KafkaSink<P> {let labels = MetricLabels {sink: self.name.as_str(),mode: self.capture_mode.as_tag(),- path: ctx.path.clone().into(),+ path: ctx.path,attempt: ctx.attempt.to_string().into(),};diff --git a/rust/capture/src/v1/sinks/kafka/sink_tests.rs b/rust/capture/src/v1/sinks/kafka/sink_tests.rsindex a4f8ff4fd77a..df4a2b8cb011 100644--- a/rust/capture/src/v1/sinks/kafka/sink_tests.rs+++ b/rust/capture/src/v1/sinks/kafka/sink_tests.rs@@ -1152,3 +1152,148 @@ async fn partial_timeout_with_serialization_error() {assert_eq!(by_key[&e2.parsed_uuid].outcome(), Outcome::Timeout);assert_eq!(by_key[&e2.parsed_uuid].cause(), Some("timeout"));}++// ===========================================================================+// Realistic WrappedEvent — destination routing, property injection, options+// ===========================================================================++#[tokio::test]+async fn realistic_exception_routes_to_exception_topic() {+ let h = TestHarness::new();+ let wrapped = test_utils::wrapped_event("$exception", "user-1")+ .with_destination(Destination::ExceptionErrorTracking);+ let events: Vec<&(dyn Event + Send + Sync)> = vec![&wrapped];++ let results = h.sink.publish_batch(&h.ctx, &events).await;++ assert_eq!(results.len(), 1);+ assert_eq!(results[0].outcome(), Outcome::Success);+ h.producer.with_records(|records| {+ assert_eq!(records[0].topic, "error_tracking_events");+ });+}++#[tokio::test]+async fn realistic_heatmap_routes_to_heatmap_topic() {+ let h = TestHarness::new();+ let wrapped =+ test_utils::wrapped_event("$$heatmap", "user-1").with_destination(Destination::HeatmapMain);+ let events: Vec<&(dyn Event + Send + Sync)> = vec![&wrapped];++ let results = h.sink.publish_batch(&h.ctx, &events).await;++ assert_eq!(results.len(), 1);+ assert_eq!(results[0].outcome(), Outcome::Success);+ h.producer.with_records(|records| {+ assert_eq!(records[0].topic, "heatmaps_ingestion");+ });+}++#[tokio::test]+async fn realistic_session_id_injected_into_properties() {+ let h = TestHarness::new();+ let mut wrapped = test_utils::wrapped_event("$pageview", "user-1");+ wrapped.event.session_id = Some("sess-123".to_string());+ let events: Vec<&(dyn Event + Send + Sync)> = vec![&wrapped];++ let results = h.sink.publish_batch(&h.ctx, &events).await;++ assert_eq!(results.len(), 1);+ assert_eq!(results[0].outcome(), Outcome::Success);+ h.producer.with_records(|records| {+ let captured: CapturedEvent =+ serde_json::from_str(&records[0].payload).expect("must deserialize as CapturedEvent");+ let data: RawEvent =+ serde_json::from_str(&captured.data).expect("data must deserialize as RawEvent");+ assert_eq!(data.properties["$session_id"], "sess-123");+ });+}++#[tokio::test]+async fn realistic_window_id_injected_into_properties() {+ let h = TestHarness::new();+ let mut wrapped = test_utils::wrapped_event("$pageview", "user-1");+ wrapped.event.window_id = Some("win-456".to_string());+ let events: Vec<&(dyn Event + Send + Sync)> = vec![&wrapped];++ let results = h.sink.publish_batch(&h.ctx, &events).await;++ assert_eq!(results.len(), 1);+ assert_eq!(results[0].outcome(), Outcome::Success);+ h.producer.with_records(|records| {+ let captured: CapturedEvent =+ serde_json::from_str(&records[0].payload).expect("must deserialize as CapturedEvent");+ let data: RawEvent =+ serde_json::from_str(&captured.data).expect("data must deserialize as RawEvent");+ assert_eq!(data.properties["$window_id"], "win-456");+ });+}++#[tokio::test]+async fn realistic_cookieless_partition_key() {+ let h = TestHarness::new();+ let mut wrapped = test_utils::wrapped_event("$pageview", "user-1");+ wrapped.event.options.cookieless_mode = Some(true);+ let events: Vec<&(dyn Event + Send + Sync)> = vec![&wrapped];++ let results = h.sink.publish_batch(&h.ctx, &events).await;++ assert_eq!(results.len(), 1);+ assert_eq!(results[0].outcome(), Outcome::Success);+ let expected_key = format!("{}:{}", h.ctx.api_token, h.ctx.client_ip);+ h.producer.with_records(|records| {+ let key = records[0].key.as_deref().expect("key should be present");+ assert_eq!(key, expected_key);+ });+}++#[rstest]+#[case::main(0, Some("events_main"))]+#[case::historical(1, Some("events_hist"))]+#[case::overflow(2, Some("events_overflow"))]+#[case::dlq(3, Some("events_dlq"))]+#[case::custom(4, Some("custom_topic"))]+#[case::drop(5, None)]+#[tokio::test]+async fn realistic_spread_destinations_routes_correctly(+ #[case] idx: usize,+ #[case] expected_topic: Option<&str>,+) {+ let h = TestHarness::new();+ let all = test_utils::realistic_spread_destinations();+ let ev = &all[idx];+ let events: Vec<&(dyn Event + Send + Sync)> = vec![ev];++ let results = h.sink.publish_batch(&h.ctx, &events).await;++ match expected_topic {+ Some(topic) => {+ assert_eq!(results.len(), 1);+ assert_eq!(results[0].outcome(), Outcome::Success);+ h.producer.with_records(|records| {+ assert_eq!(records[0].topic, topic);+ });+ }+ None => {+ assert!(results.is_empty());+ assert_eq!(h.producer.record_count(), 0);+ }+ }+}++#[tokio::test]+async fn realistic_force_disable_pp_null_partition_key() {+ let h = TestHarness::new();+ let wrapped = test_utils::wrapped_event("$pageview", "user-1")+ .with_force_disable_person_processing(true)+ .with_destination(Destination::AnalyticsMain);+ let events: Vec<&(dyn Event + Send + Sync)> = vec![&wrapped];++ let results = h.sink.publish_batch(&h.ctx, &events).await;++ assert_eq!(results.len(), 1);+ assert_eq!(results[0].outcome(), Outcome::Success);+ h.producer.with_records(|records| {+ assert!(records[0].key.is_none());+ });+}diff --git a/rust/capture/src/v1/sinks/mod.rs b/rust/capture/src/v1/sinks/mod.rsindex c9d71de92702..802d484c04a7 100644--- a/rust/capture/src/v1/sinks/mod.rs+++ b/rust/capture/src/v1/sinks/mod.rs@@ -42,6 +42,14 @@ impl SinkName {}}+ pub fn lifecycle_tag(&self) -> &'static str {+ match self {+ Self::Msk => "v1-sink-msk",+ Self::MskAlt => "v1-sink-msk_alt",+ Self::Ws => "v1-sink-ws",+ }+ }+pub fn env_prefix(&self) -> &'static str {match self {Self::Msk => "CAPTURE_V1_SINK_MSK_",@@ -134,8 +142,10 @@ pub fn load_sinks(sinks_csv: &str) -> anyhow::Result<Sinks> {load_sinks_from(sinks_csv, &env)}-/// Testable core: loads sink configs from a provided env snapshot.-pub fn load_sinks_from(sinks_csv: &str, env: &HashMap<String, String>) -> anyhow::Result<Sinks> {+/// Parse the comma-separated sink names without loading per-sink configs.+/// Used by `register_components` to register lifecycle handles before the+/// full config is available.+pub fn parse_sink_names(sinks_csv: &str) -> anyhow::Result<Vec<SinkName>> {let names: Vec<SinkName> = sinks_csv.split(',').filter(|s| !s.trim().is_empty())@@ -144,6 +154,12 @@ pub fn load_sinks_from(sinks_csv: &str, env: &HashMap<String, String>) -> anyhow.map_err(|e| anyhow::anyhow!("bad CAPTURE_V1_SINKS: {e}"))?;anyhow::ensure!(!names.is_empty(), "CAPTURE_V1_SINKS is empty");+ Ok(names)+}++/// Testable core: loads sink configs from a provided env snapshot.+pub fn load_sinks_from(sinks_csv: &str, env: &HashMap<String, String>) -> anyhow::Result<Sinks> {+ let names = parse_sink_names(sinks_csv)?;let default = names[0];let mut configs = HashMap::new();diff --git a/rust/capture/src/v1/test_utils.rs b/rust/capture/src/v1/test_utils.rsindex eb8cb8666c92..5080836b2d3c 100644--- a/rust/capture/src/v1/test_utils.rs+++ b/rust/capture/src/v1/test_utils.rs@@ -38,7 +38,7 @@ pub fn test_context() -> Context {client_ip: IpAddr::V4(Ipv4Addr::LOCALHOST),query: Query::default(),method: Method::POST,- path: "/i/v1/general/events".to_string(),+ path: "/i/v1/general/events",server_received_at: Utc::now(),created_at: Some("2026-03-19T14:30:00.000Z".to_string()),capture_internal: false,@@ -404,3 +404,408 @@ pub fn assert_round_trip((captured, data)}++// ---------------------------------------------------------------------------+// Payload generators for batch-level tests+// ---------------------------------------------------------------------------++/// Serialize a list of Events into a valid V1 batch JSON payload.+pub fn batch_payload(events: &[Event]) -> Vec<u8> {+ let batch_json = serde_json::json!({+ "created_at": "2026-03-19T14:30:00.000Z",+ "batch": events.iter().map(|e| {+ let mut obj = serde_json::json!({+ "event": e.event,+ "uuid": e.uuid,+ "distinct_id": e.distinct_id,+ "timestamp": e.timestamp,+ "options": e.options,+ });+ obj.as_object_mut().unwrap().insert(+ "properties".to_string(),+ serde_json::from_str(e.properties.get()).unwrap(),+ );+ if let Some(ref sid) = e.session_id {+ obj.as_object_mut().unwrap().insert(+ "session_id".to_string(),+ serde_json::Value::String(sid.clone()),+ );+ }+ if let Some(ref wid) = e.window_id {+ obj.as_object_mut().unwrap().insert(+ "window_id".to_string(),+ serde_json::Value::String(wid.clone()),+ );+ }+ obj+ }).collect::<Vec<_>>(),+ });+ serde_json::to_vec(&batch_json).unwrap()+}++/// Compress raw bytes using the given encoding.+/// Supported: "gzip", "deflate", "br", "zstd"+#[cfg(test)]+pub fn compressed_payload(data: &[u8], encoding: &str) -> Vec<u8> {+ match encoding {+ "gzip" => {+ use flate2::write::GzEncoder;+ use flate2::Compression;+ use std::io::Write;+ let mut encoder = GzEncoder::new(Vec::new(), Compression::fast());+ encoder.write_all(data).unwrap();+ encoder.finish().unwrap()+ }+ "deflate" => {+ use flate2::write::DeflateEncoder;+ use flate2::Compression;+ use std::io::Write;+ let mut encoder = DeflateEncoder::new(Vec::new(), Compression::fast());+ encoder.write_all(data).unwrap();+ encoder.finish().unwrap()+ }+ "br" => {+ let mut output = Vec::new();+ let params = brotli::enc::BrotliEncoderParams::default();+ brotli::BrotliCompress(&mut std::io::Cursor::new(data), &mut output, ¶ms).unwrap();+ output+ }+ "zstd" => zstd::encode_all(std::io::Cursor::new(data), 1).unwrap(),+ other => panic!("unsupported encoding for test: {other}"),+ }+}++/// Event with all options populated.+pub fn event_with_all_options() -> Event {+ Event {+ event: "$pageview".to_string(),+ uuid: Uuid::new_v4().to_string(),+ distinct_id: "user-all-opts".to_string(),+ timestamp: "2026-03-19T14:29:58.123Z".to_string(),+ session_id: Some("sess-all".to_string()),+ window_id: Some("win-all".to_string()),+ options: Options {+ cookieless_mode: Some(true),+ disable_skew_correction: Some(true),+ product_tour_id: Some("tour-v2".to_string()),+ process_person_profile: Some(false),+ },+ properties: raw_obj(r#"{"existing":"prop"}"#),+ }+}++/// Event with empty `options: {}`.+pub fn event_with_empty_options() -> Event {+ Event {+ event: "$pageview".to_string(),+ uuid: Uuid::new_v4().to_string(),+ distinct_id: "user-empty-opts".to_string(),+ timestamp: "2026-03-19T14:29:58.123Z".to_string(),+ session_id: None,+ window_id: None,+ options: default_options(),+ properties: raw_obj("{}"),+ }+}++// ---------------------------------------------------------------------------+// Mock SinkResult for unit testing merge logic+// ---------------------------------------------------------------------------++use std::borrow::Cow;+use std::time::Duration;++use crate::v1::sinks::types::{Outcome, SinkResult as SinkResultTrait};++/// Concrete SinkResult for testing — all fields are user-specified.+pub struct MockSinkResult {+ pub uuid: Uuid,+ pub outcome: Outcome,+ pub cause: Option<&'static str>,+ pub detail: Option<String>,+ pub elapsed: Option<Duration>,+}++impl MockSinkResult {+ pub fn success(uuid: Uuid) -> Box<dyn SinkResultTrait> {+ Box::new(Self {+ uuid,+ outcome: Outcome::Success,+ cause: None,+ detail: None,+ elapsed: Some(Duration::from_millis(5)),+ })+ }++ pub fn retriable(uuid: Uuid, cause: &'static str) -> Box<dyn SinkResultTrait> {+ Box::new(Self {+ uuid,+ outcome: Outcome::RetriableError,+ cause: Some(cause),+ detail: Some(format!("{cause}: queue full")),+ elapsed: Some(Duration::from_millis(100)),+ })+ }++ pub fn timeout(uuid: Uuid) -> Box<dyn SinkResultTrait> {+ Box::new(Self {+ uuid,+ outcome: Outcome::Timeout,+ cause: Some("timeout"),+ detail: Some("message delivery timed out".to_string()),+ elapsed: Some(Duration::from_secs(30)),+ })+ }++ pub fn fatal(uuid: Uuid, cause: &'static str) -> Box<dyn SinkResultTrait> {+ Box::new(Self {+ uuid,+ outcome: Outcome::FatalError,+ cause: Some(cause),+ detail: Some(format!("{cause}: permanent failure")),+ elapsed: None,+ })+ }++ pub fn fatal_no_cause(uuid: Uuid) -> Box<dyn SinkResultTrait> {+ Box::new(Self {+ uuid,+ outcome: Outcome::FatalError,+ cause: None,+ detail: None,+ elapsed: None,+ })+ }+}++impl SinkResultTrait for MockSinkResult {+ fn key(&self) -> Uuid {+ self.uuid+ }++ fn outcome(&self) -> Outcome {+ self.outcome+ }++ fn cause(&self) -> Option<&'static str> {+ self.cause+ }++ fn detail(&self) -> Option<Cow<'_, str>> {+ self.detail.as_ref().map(|s| Cow::Borrowed(s.as_str()))+ }++ fn elapsed(&self) -> Option<Duration> {+ self.elapsed+ }+}++// ---------------------------------------------------------------------------+// TestStateBuilder — builds a router::State for V1 pipeline integration tests+// ---------------------------------------------------------------------------++use std::collections::HashMap;+use std::num::NonZeroU32;+use std::sync::Arc;++use common_redis::MockRedisClient;+use limiters::overflow::OverflowLimiter;+use limiters::redis::{QuotaResource, QUOTA_LIMITER_CACHE_KEY};+use limiters::token_dropper::TokenDropper;++use crate::config::CaptureMode;+use crate::event_restrictions::EventRestrictionService;+use crate::global_rate_limiter::GlobalRateLimiter;+use crate::quota_limiters::CaptureQuotaLimiter;+use crate::router::{self, HistoricalConfig};+use crate::sinks;+use crate::time::TimeSource;+use crate::v1::sinks::kafka::mock::MockProducer;+use crate::v1::sinks::kafka::sink::KafkaSink;+use crate::v1::sinks::sink::Sink;+use crate::v1::sinks::{self as v1_sinks, SinkName};++/// Result of building a test state — gives access to both the `router::State`+/// and the underlying `MockProducer` so tests can inspect sent records.+pub struct TestState {+ pub state: router::State,+ pub mock_producer: Arc<MockProducer>,+}++/// Builder for `router::State` with configurable mock services.+pub struct TestStateBuilder {+ quota_limited: bool,+ overflow_limiter: Option<(NonZeroU32, NonZeroU32)>,+ historical_threshold_days: Option<i64>,+ restriction_service: Option<EventRestrictionService>,+ global_rate_limiter: Option<Arc<GlobalRateLimiter>>,+ mock_producer: Option<Arc<MockProducer>>,+}++impl Default for TestStateBuilder {+ fn default() -> Self {+ Self::new()+ }+}++impl TestStateBuilder {+ pub fn new() -> Self {+ Self {+ quota_limited: false,+ overflow_limiter: None,+ historical_threshold_days: None,+ restriction_service: None,+ global_rate_limiter: None,+ mock_producer: None,+ }+ }++ /// Configure quota limiter to reject all events for any token.+ pub fn with_quota_limited(mut self) -> Self {+ self.quota_limited = true;+ self+ }++ /// Add an in-process overflow limiter with the given rate and burst.+ pub fn with_overflow_limiter(mut self, per_second: u32, burst: u32) -> Self {+ self.overflow_limiter = Some((+ NonZeroU32::new(per_second).expect("per_second must be > 0"),+ NonZeroU32::new(burst).expect("burst must be > 0"),+ ));+ self+ }++ /// Enable historical rerouting with the given threshold in days.+ pub fn with_historical_rerouting(mut self, threshold_days: i64) -> Self {+ self.historical_threshold_days = Some(threshold_days);+ self+ }++ /// Add a restriction service.+ pub fn with_restriction_service(mut self, service: EventRestrictionService) -> Self {+ self.restriction_service = Some(service);+ self+ }++ /// Add a global rate limiter.+ pub fn with_global_rate_limiter(mut self, limiter: Arc<GlobalRateLimiter>) -> Self {+ self.global_rate_limiter = Some(limiter);+ self+ }++ /// Supply a pre-configured MockProducer (e.g. for error injection).+ pub fn with_mock_producer(mut self, producer: Arc<MockProducer>) -> Self {+ self.mock_producer = Some(producer);+ self+ }++ pub fn build(self) -> TestState {+ let mut manager = lifecycle::Manager::builder("test_state")+ .with_trap_signals(false)+ .with_prestop_check(false)+ .build();+ let handle = manager.register("test_state", lifecycle::ComponentOptions::new());+ handle.report_healthy();+ let _monitor = manager.monitor_background();++ let redis: Arc<dyn common_redis::Client + Send + Sync> = if self.quota_limited {+ let mut mock = MockRedisClient::new();+ for resource in &[+ QuotaResource::Events,+ QuotaResource::Recordings,+ QuotaResource::Exceptions,+ QuotaResource::Surveys,+ QuotaResource::LLMEvents,+ ] {+ let key = format!("{}{}", QUOTA_LIMITER_CACHE_KEY, resource.as_str());+ // Return a wildcard token so every token is limited+ mock = mock.zrangebyscore_ret(&key, vec!["*".to_string()]);+ }+ Arc::new(mock)+ } else {+ Arc::new(MockRedisClient::new())+ };++ // CaptureQuotaLimiter needs a Config — build a minimal one via envconfig+ let cfg_env: HashMap<String, String> = [+ ("REDIS_URL", "redis://localhost:6379/"),+ ("CAPTURE_MODE", "events"),+ ("KAFKA_HOSTS", "localhost:9092"),+ ("KAFKA_TOPIC", "events_plugin_ingestion"),+ ]+ .into_iter()+ .map(|(k, v)| (k.to_string(), v.to_string()))+ .collect();+ let cfg: crate::config::Config =+ envconfig::Envconfig::init_from_hashmap(&cfg_env).expect("failed to build test Config");++ let quota_limiter = CaptureQuotaLimiter::new(&cfg, redis.clone(), Duration::from_secs(60));++ let historical_cfg = match self.historical_threshold_days {+ Some(days) => HistoricalConfig::new(true, days),+ None => HistoricalConfig::new(false, 1),+ };++ let overflow_limiter = self+ .overflow_limiter+ .map(|(per_sec, burst)| Arc::new(OverflowLimiter::new(per_sec, burst, None, false)));++ // Build the v1 sink router with a MockProducer-backed KafkaSink+ let mock_producer = self+ .mock_producer+ .unwrap_or_else(|| Arc::new(MockProducer::new(SinkName::Msk, handle.clone())));++ let kafka_config = test_kafka_config();+ let sink_config = v1_sinks::Config {+ produce_timeout: Duration::from_secs(30),+ kafka: kafka_config,+ };++ let kafka_sink = KafkaSink::new(+ SinkName::Msk,+ Arc::clone(&mock_producer),+ sink_config,+ CaptureMode::Events,+ handle.clone(),+ );++ let boxed_sink: Box<dyn Sink> = Box::new(kafka_sink);+ let sinks_map: HashMap<SinkName, Box<dyn Sink>> =+ [(SinkName::Msk, boxed_sink)].into_iter().collect();+ let v1_router = v1_sinks::Router::new(SinkName::Msk, sinks_map);++ // Legacy sink — no-op since V1 tests go through v1_sink_router+ let legacy_sink: Arc<dyn sinks::Event + Send + Sync> =+ Arc::new(crate::sinks::noop::NoOpSink::new());++ let timesource: Arc<dyn TimeSource + Send + Sync> = Arc::new(crate::time::SystemTime {});++ let state = router::State {+ sink: legacy_sink,+ timesource,+ redis,+ global_rate_limiter_token_distinctid: self.global_rate_limiter,+ quota_limiter: Arc::new(quota_limiter),+ token_dropper: Arc::new(TokenDropper::default()),+ event_restriction_service: self.restriction_service,+ event_payload_size_limit: 20 * 1024 * 1024,+ historical_cfg,+ 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,+ capture_v1_max_decompressed_body_bytes: 20 * 1024 * 1024,+ overflow_limiter,+ replay_overflow_limiter: None,+ v1_sink_router: Some(Arc::new(v1_router)),+ };++ TestState {+ state,+ mock_producer,+ }+ }+}diff --git a/rust/capture/src/v1/util.rs b/rust/capture/src/v1/util.rsindex cb4c958bf068..384672294b6e 100644--- a/rust/capture/src/v1/util.rs+++ b/rust/capture/src/v1/util.rs@@ -21,7 +21,7 @@ pub async fn extract_body_with_timeout(payload_size_limit: usize,chunk_timeout: Option<Duration>,chunk_size_kb: usize,- path: &str,+ path: &'static str,) -> Result<Bytes, Error> {let mut stream = body.into_data_stream();let mut buf = BytesMut::with_capacity(std::cmp::min(payload_size_limit, chunk_size_kb * 1024));@@ -31,8 +31,7 @@ pub async fn extract_body_with_timeout(Some(timeout) => match tokio::time::timeout(timeout, stream.next()).await {Ok(result) => result,Err(_elapsed) => {- metrics::counter!(CAPTURE_V1_BODY_READ_TIMEOUT, "path" => path.to_string())- .increment(1);+ metrics::counter!(CAPTURE_V1_BODY_READ_TIMEOUT, "path" => path).increment(1);return Err(Error::BodyReadTimeout(buf.len()));}},@@ -456,4 +455,20 @@ mod tests {let result = handler_roundtrip(None, original.clone(), 4096, 4096).await;assert_eq!(result.unwrap(), original);}++ #[tokio::test]+ async fn extract_body_stream_error_returns_decoding_error() {+ let error_stream = stream::once(async {+ Err::<Bytes, std::io::Error>(std::io::Error::new(+ std::io::ErrorKind::ConnectionReset,+ "simulated stream error",+ ))+ });+ let body = Body::from_stream(error_stream);+ let result = extract_body_with_timeout(body, 4096, None, TEST_CHUNK_SIZE_KB, "/test").await;+ assert!(+ matches!(result, Err(Error::RequestDecodingError(_))),+ "stream error should surface as RequestDecodingError, got: {result:?}"+ );+ }}diff --git a/rust/capture/tests/common/integration_utils.rs b/rust/capture/tests/common/integration_utils.rsindex eda6ec683581..460cdb64e884 100644--- a/rust/capture/tests/common/integration_utils.rs+++ b/rust/capture/tests/common/integration_utils.rs@@ -1109,6 +1109,7 @@ fn setup_capture_router(unit: &TestCase) -> (Router, MemorySink) {50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytesNone, // overflow_limiterNone, // replay_overflow_limiter+ None, // v1_sink_router),sink,)diff --git a/rust/capture/tests/common/mod.rs b/rust/capture/tests/common/mod.rsindex c8ad4d4cd5dd..c46034a91f63 100644--- a/rust/capture/tests/common/mod.rs+++ b/rust/capture/tests/common/mod.rs@@ -1,2 +1,36 @@+#![allow(clippy::duplicate_mod)]+pub mod integration_utils;pub mod utils;++/// Compress raw bytes using the given encoding.+/// Shared across integration tests to avoid duplicating compression logic.+#[allow(dead_code)]+pub fn compress(data: &[u8], encoding: &str) -> Vec<u8> {+ use std::io::Write;+ match encoding {+ "gzip" => {+ let mut enc = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::fast());+ enc.write_all(data).unwrap();+ enc.finish().unwrap()+ }+ "deflate" => {+ let mut enc =+ flate2::write::DeflateEncoder::new(Vec::new(), flate2::Compression::fast());+ enc.write_all(data).unwrap();+ enc.finish().unwrap()+ }+ "br" => {+ let mut out = Vec::new();+ brotli::BrotliCompress(+ &mut std::io::Cursor::new(data),+ &mut out,+ &brotli::enc::BrotliEncoderParams::default(),+ )+ .unwrap();+ out+ }+ "zstd" => zstd::encode_all(std::io::Cursor::new(data), 1).unwrap(),+ other => panic!("unsupported encoding: {other}"),+ }+}diff --git a/rust/capture/tests/integration_ai_endpoint.rs b/rust/capture/tests/integration_ai_endpoint.rsindex 080f891bf742..ec6549f389db 100644--- a/rust/capture/tests/integration_ai_endpoint.rs+++ b/rust/capture/tests/integration_ai_endpoint.rs@@ -195,6 +195,7 @@ fn setup_ai_test_router() -> Router {50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytesNone, // overflow_limiterNone, // replay_overflow_limiter+ None, // v1_sink_router)}@@ -1656,6 +1657,7 @@ fn setup_ai_test_router_with_capturing_sink() -> (Router, CapturingSink) {50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytesNone, // overflow_limiterNone, // replay_overflow_limiter+ None, // v1_sink_router);(router, sink_clone)@@ -2569,6 +2571,7 @@ fn setup_ai_test_router_with_token_dropper(token_dropper: TokenDropper) -> (Rout50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytesNone, // overflow_limiterNone, // replay_overflow_limiter+ None, // v1_sink_router);(router, sink_clone)@@ -2777,6 +2780,7 @@ fn setup_ai_test_router_with_llm_quota_limited(token: &str) -> (Router, Capturin50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytesNone, // overflow_limiterNone, // replay_overflow_limiter+ None, // v1_sink_router);(router, sink_clone)@@ -2930,6 +2934,7 @@ fn setup_ai_test_router_with_overflow_limiter(50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytesSome(overflow_limiter), // overflow_limiterNone, // replay_overflow_limiter+ None, // v1_sink_router);(router, sink_clone)diff --git a/rust/capture/tests/integration_ai_restrictions.rs b/rust/capture/tests/integration_ai_restrictions.rsindex e6107e882645..bbad40dfd575 100644--- a/rust/capture/tests/integration_ai_restrictions.rs+++ b/rust/capture/tests/integration_ai_restrictions.rs@@ -193,6 +193,7 @@ async fn setup_ai_router_with_restriction(50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytesNone, // overflow_limiterNone, // replay_overflow_limiter+ None, // v1_sink_router);(router, sink_clone)@@ -510,6 +511,7 @@ async fn setup_ai_router_with_redirect_to_topic(50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytesNone, // overflow_limiterNone, // replay_overflow_limiter+ None, // v1_sink_router);(router, sink_clone)@@ -584,6 +586,7 @@ async fn setup_ai_router_with_force_overflow_and_limiter(50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytesSome(overflow_limiter), // overflow_limiterNone, // replay_overflow_limiter+ None, // v1_sink_router);(router, sink_clone)diff --git a/rust/capture/tests/integration_analytics_restrictions.rs b/rust/capture/tests/integration_analytics_restrictions.rsindex 42238a2ba7ea..5704a5297edf 100644--- a/rust/capture/tests/integration_analytics_restrictions.rs+++ b/rust/capture/tests/integration_analytics_restrictions.rs@@ -127,6 +127,7 @@ async fn setup_analytics_router_with_restriction(50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytesNone, // overflow_limiterNone, // replay_overflow_limiter+ None, // v1_sink_router);(router, sink_clone)@@ -469,6 +470,7 @@ async fn setup_analytics_router_with_redirect_to_topic(50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytesNone, // overflow_limiterNone, // replay_overflow_limiter+ None, // v1_sink_router);(router, sink_clone)diff --git a/rust/capture/tests/integration_otel_endpoint.rs b/rust/capture/tests/integration_otel_endpoint.rsindex 1c1ce0514d2f..199b7e28a4bf 100644--- a/rust/capture/tests/integration_otel_endpoint.rs+++ b/rust/capture/tests/integration_otel_endpoint.rs@@ -185,6 +185,7 @@ fn make_test_client_with_options(sink: &CapturingSink, options: TestClientOption50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytesoptions.overflow_limiter, // overflow_limiterNone, // replay_overflow_limiter+ None, // v1_sink_router);TestClient::new(app)diff --git a/rust/capture/tests/integration_replay_restrictions.rs b/rust/capture/tests/integration_replay_restrictions.rsindex 54e87424b5e2..241355c02bc0 100644--- a/rust/capture/tests/integration_replay_restrictions.rs+++ b/rust/capture/tests/integration_replay_restrictions.rs@@ -129,6 +129,7 @@ async fn setup_recordings_router_with_restriction(50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytesNone, // overflow_limiterNone, // replay_overflow_limiter+ None, // v1_sink_router);(router, sink_clone)@@ -497,6 +498,7 @@ async fn setup_recordings_router_with_redirect_to_topic(50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytesNone, // overflow_limiterNone, // replay_overflow_limiter+ None, // v1_sink_router);(router, sink_clone)diff --git a/rust/capture/tests/quota_limiters.rs b/rust/capture/tests/quota_limiters.rsindex 6bf6f87754c1..48751360b3da 100644--- a/rust/capture/tests/quota_limiters.rs+++ b/rust/capture/tests/quota_limiters.rs@@ -151,6 +151,7 @@ async fn setup_router_with_limits(50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytesNone, // overflow_limiterNone, // replay_overflow_limiter+ None, // v1_sink_router);(app, sink)@@ -1201,6 +1202,7 @@ async fn test_survey_quota_cross_batch_first_submission_allowed() {50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytesNone, // overflow_limiterNone, // replay_overflow_limiter+ None, // v1_sink_router);let client = TestClient::new(app);@@ -1289,6 +1291,7 @@ async fn test_survey_quota_cross_batch_duplicate_submission_dropped() {50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytesNone, // overflow_limiterNone, // replay_overflow_limiter+ None, // v1_sink_router);let client = TestClient::new(app);@@ -1381,6 +1384,7 @@ async fn test_survey_quota_cross_batch_redis_error_fail_open() {50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytesNone, // overflow_limiterNone, // replay_overflow_limiter+ None, // v1_sink_router);let client = TestClient::new(app);@@ -1810,6 +1814,7 @@ async fn test_ai_quota_cross_batch_redis_error_fail_open() {50 * 1024 * 1024, // capture_v1_max_decompressed_body_bytesNone, // overflow_limiterNone, // replay_overflow_limiter+ None, // v1_sink_router);let client = TestClient::new(app);diff --git a/rust/capture/tests/v1_pipeline.rs b/rust/capture/tests/v1_pipeline.rsnew file mode 100644index 000000000000..68f58124baed--- /dev/null+++ b/rust/capture/tests/v1_pipeline.rs@@ -0,0 +1,304 @@+mod common;++use std::sync::Arc;++use rdkafka::error::RDKafkaErrorCode;+use rstest::rstest;+use uuid::Uuid;++use capture::v1::analytics::process::process_batch;+use capture::v1::analytics::response::BatchResponse;+use capture::v1::analytics::types::{Batch, EventResult};+use capture::v1::sinks::kafka::mock::MockProducer;+use capture::v1::sinks::kafka::producer::ProduceError;+use capture::v1::sinks::SinkName;+use capture::v1::test_utils::{self, batch_payload, valid_event, TestStateBuilder};+use capture::v1::Error;++fn event_with_name(name: &str) -> capture::v1::analytics::types::Event {+ let mut e = valid_event();+ e.event = name.to_string();+ e.uuid = Uuid::new_v4().to_string();+ e+}++async fn run_batch(payload: &[u8], builder: TestStateBuilder) -> Result<BatchResponse, Error> {+ run_batch_with_state(payload, builder).await.0+}++async fn run_batch_with_state(+ payload: &[u8],+ builder: TestStateBuilder,+) -> (Result<BatchResponse, Error>, test_utils::TestState) {+ let batch: Batch = serde_json::from_slice(payload).expect("payload must parse as Batch");+ let ts = builder.build();+ let mut ctx = test_utils::test_context();+ let result = process_batch(&ts.state, &mut ctx, batch).await;+ (result, ts)+}++// -------------------------------------------------------------------------+// Table 1: Event Type → Destination Routing+// -------------------------------------------------------------------------++#[rstest]+#[case::pageview("$pageview", "events_main")]+#[case::exception("$exception", "error_tracking_events")]+#[case::heatmap("$$heatmap", "heatmaps_ingestion")]+#[case::client_warning("$$client_ingestion_warning", "events_plugin_ingestion")]+#[case::custom("signup_complete", "events_main")]+#[tokio::test]+async fn event_type_routes_to_destination(#[case] event_name: &str, #[case] expected_topic: &str) {+ let events = vec![event_with_name(event_name)];+ let payload = batch_payload(&events);++ let (result, ts) = run_batch_with_state(&payload, TestStateBuilder::new()).await;++ let resp = result.expect("batch should succeed");+ assert_eq!(resp.entries().len(), 1);+ assert_eq!(resp.entries()[0].1.result, EventResult::Ok);++ ts.mock_producer.with_records(|records| {+ assert_eq!(records.len(), 1, "expected exactly 1 Kafka record");+ assert_eq!(records[0].topic, expected_topic);+ });+}++// -------------------------------------------------------------------------+// Table 2: Processing Outcomes (Mixed Batches)+// -------------------------------------------------------------------------++#[tokio::test]+async fn mixed_batch_all_ok() {+ let events = vec![+ event_with_name("$pageview"),+ event_with_name("$identify"),+ event_with_name("custom_event"),+ ];+ let payload = batch_payload(&events);++ let resp = run_batch(&payload, TestStateBuilder::new())+ .await+ .expect("batch should succeed");++ assert_eq!(resp.entries().len(), 3);+ assert!(!resp.has_retry);+ for (_, status) in resp.entries() {+ assert_eq!(status.result, EventResult::Ok);+ }+}++#[tokio::test]+async fn sink_ack_error_causes_retry() {+ let mut manager = lifecycle::Manager::builder("test_ack_err")+ .with_trap_signals(false)+ .with_prestop_check(false)+ .build();+ let handle = manager.register("test_ack_err", lifecycle::ComponentOptions::new());+ handle.report_healthy();+ let _monitor = manager.monitor_background();++ let producer =+ Arc::new(+ MockProducer::new(SinkName::Msk, handle).with_ack_error(|| ProduceError::Kafka {+ code: RDKafkaErrorCode::BrokerNotAvailable,+ }),+ );++ let events = vec![event_with_name("$pageview"), event_with_name("$identify")];+ let payload = batch_payload(&events);++ let resp = run_batch(+ &payload,+ TestStateBuilder::new().with_mock_producer(producer),+ )+ .await+ .expect("batch should succeed");++ assert_eq!(resp.entries().len(), 2);+ assert!(resp.has_retry);+ for (_, status) in resp.entries() {+ assert_eq!(status.result, EventResult::Retry);+ }+}++#[tokio::test]+async fn all_events_quota_dropped() {+ let events = vec![+ event_with_name("$pageview"),+ event_with_name("custom_event"),+ ];+ let payload = batch_payload(&events);++ let ts = TestStateBuilder::new().with_quota_limited().build();++ // with_quota_limited() loads a wildcard "*" token into the limiter's+ // DashMap — use "*" as the api_token so `is_limited("*")` matches.+ // Poll until the background task populates the cache (avoids flaky fixed sleep).+ let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(2);+ loop {+ let batch: Batch = serde_json::from_slice(&payload).expect("payload must parse as Batch");+ let mut ctx = test_utils::test_context();+ ctx.api_token = "*".to_string();+ let result = process_batch(&ts.state, &mut ctx, batch).await;+ if result.is_err() {+ let err = result.unwrap_err();+ assert!(+ matches!(err, Error::BillingLimitExceeded),+ "expected BillingLimitExceeded, got: {err:?}"+ );+ return;+ }+ assert!(+ tokio::time::Instant::now() < deadline,+ "quota limiter cache was not populated within 2s"+ );+ tokio::time::sleep(std::time::Duration::from_millis(5)).await;+ }+}++#[tokio::test]+async fn historical_rerouting() {+ let old_ts = chrono::Utc::now() - chrono::Duration::days(60);+ let mut event = valid_event();+ event.timestamp = old_ts.to_rfc3339_opts(chrono::SecondsFormat::Millis, true);+ event.uuid = Uuid::new_v4().to_string();++ let events = vec![event];+ let payload = batch_payload(&events);++ let (result, ts) = run_batch_with_state(+ &payload,+ TestStateBuilder::new().with_historical_rerouting(30),+ )+ .await;++ let resp = result.expect("batch should succeed");+ assert_eq!(resp.entries().len(), 1);+ assert_eq!(resp.entries()[0].1.result, EventResult::Ok);++ ts.mock_producer.with_records(|records| {+ assert_eq!(records.len(), 1);+ assert_eq!(+ records[0].topic, "events_hist",+ "old event should route to historical topic"+ );+ });+}++// -------------------------------------------------------------------------+// Table 3: Compression Round-Trip+// -------------------------------------------------------------------------++#[rstest]+#[case::identity(None)]+#[case::gzip(Some("gzip"))]+#[case::zstd(Some("zstd"))]+#[case::deflate(Some("deflate"))]+#[case::brotli(Some("br"))]+#[tokio::test]+async fn compression_round_trip(#[case] encoding: Option<&str>) {+ let events = vec![+ event_with_name("$pageview"),+ event_with_name("$exception"),+ event_with_name("custom"),+ ];+ let raw = batch_payload(&events);++ let payload = match encoding {+ Some(enc) => common::compress(&raw, enc),+ None => raw,+ };++ let batch: Batch = match encoding {+ Some(enc) => {+ let decompressed = capture::v1::util::decompress_payload(+ Some(enc),+ bytes::Bytes::from(payload),+ 20 * 1024 * 1024,+ 64,+ )+ .await+ .expect("decompression should succeed");+ serde_json::from_slice(&decompressed).expect("decompressed payload must parse")+ }+ None => serde_json::from_slice(&payload).expect("raw payload must parse"),+ };++ let ts = TestStateBuilder::new().build();+ let mut ctx = test_utils::test_context();+ if encoding.is_some() {+ ctx.content_encoding = encoding.map(String::from);+ }++ let resp = process_batch(&ts.state, &mut ctx, batch)+ .await+ .expect("batch should succeed");++ assert_eq!(resp.entries().len(), 3);+ assert!(!resp.has_retry);+ for (_, status) in resp.entries() {+ assert_eq!(status.result, EventResult::Ok);+ }+}++// -------------------------------------------------------------------------+// Table 4: Validation Errors+// -------------------------------------------------------------------------++#[tokio::test]+async fn empty_batch_error() {+ let payload = serde_json::to_vec(&serde_json::json!({+ "created_at": "2026-03-19T14:30:00.000Z",+ "batch": []+ }))+ .unwrap();++ let err = run_batch(&payload, TestStateBuilder::new())+ .await+ .expect_err("empty batch should fail");++ assert!(+ matches!(err, Error::EmptyBatch),+ "expected EmptyBatch, got: {err:?}"+ );+}++#[tokio::test]+async fn duplicate_uuid_error() {+ let shared_uuid = Uuid::new_v4().to_string();+ let mut e1 = valid_event();+ e1.uuid = shared_uuid.clone();+ let mut e2 = valid_event();+ e2.event = "$identify".to_string();+ e2.uuid = shared_uuid;++ let payload = batch_payload(&[e1, e2]);++ let err = run_batch(&payload, TestStateBuilder::new())+ .await+ .expect_err("duplicate uuid should fail");++ assert!(+ matches!(err, Error::DuplicateEventUuid(_)),+ "expected DuplicateEventUuid, got: {err:?}"+ );+}++#[tokio::test]+async fn missing_event_name_drops_event() {+ let mut bad = valid_event();+ bad.event = String::new();+ let good = event_with_name("$pageview");++ let payload = batch_payload(&[bad, good]);++ let resp = run_batch(&payload, TestStateBuilder::new())+ .await+ .expect("batch with mix of valid and invalid events should succeed");++ assert_eq!(resp.entries().len(), 2);+ assert_eq!(resp.entries()[0].1.result, EventResult::Drop);+ assert_eq!(resp.entries()[0].1.details, Some("missing_event_name"));+ assert_eq!(resp.entries()[1].1.result, EventResult::Ok);+}diff --git a/rust/capture/tests/v1_sink_integration.rs b/rust/capture/tests/v1_sink_integration.rsindex c381159841ff..df0ebdac28ba 100644--- a/rust/capture/tests/v1_sink_integration.rs+++ b/rust/capture/tests/v1_sink_integration.rs@@ -255,3 +255,194 @@ async fn v1_dropped_event_not_published() -> Result<()> {topic.assert_empty();Ok(())}++// ---------------------------------------------------------------------------+// Exception event routes to exception topic+// ---------------------------------------------------------------------------++#[tokio::test]+async fn v1_exception_event_round_trip() -> Result<()> {+ setup_tracing();+ let topic = EphemeralTopic::new().await;+ let (sink, _monitor) = build_v1_sink(topic.topic_name()).await;+ let ctx = v1_test_context();++ let uuid = uuid::Uuid::new_v4();+ let mut wrapped = test_utils::realistic_pageview("integ-user-exception");+ wrapped.event.event = "$exception".to_string();+ wrapped.uuid = uuid;+ wrapped.event.uuid = uuid.to_string();+ wrapped.destination = capture::v1::sinks::Destination::ExceptionErrorTracking;++ let events: Vec<&(dyn Event + Send + Sync)> = vec![&wrapped];+ let results = sink.publish_batch(&ctx, &events).await;+ assert_eq!(results.len(), 1);+ assert_eq!(results[0].outcome(), Outcome::Success);++ let event_json = topic.next_event()?;+ let captured: CapturedEvent = serde_json::from_value(event_json)?;+ assert_eq!(captured.event, "$exception");+ assert_eq!(captured.uuid, uuid);+ assert_eq!(captured.distinct_id, "integ-user-exception");++ topic.assert_empty();+ Ok(())+}++// ---------------------------------------------------------------------------+// Cookieless mode affects partition key+// ---------------------------------------------------------------------------++#[tokio::test]+async fn v1_cookieless_mode_partition_key() -> Result<()> {+ setup_tracing();+ let topic = EphemeralTopic::new().await;+ let (sink, _monitor) = build_v1_sink(topic.topic_name()).await;+ let mut ctx = v1_test_context();+ ctx.client_ip = "198.51.100.7".parse().unwrap();++ let uuid = uuid::Uuid::new_v4();+ let mut wrapped = test_utils::realistic_pageview("integ-user-cookieless");+ wrapped.uuid = uuid;+ wrapped.event.uuid = uuid.to_string();+ wrapped.event.options.cookieless_mode = Some(true);++ let events: Vec<&(dyn Event + Send + Sync)> = vec![&wrapped];+ let results = sink.publish_batch(&ctx, &events).await;+ assert_eq!(results[0].outcome(), Outcome::Success);++ let key = topic.next_message_key()?;+ assert_eq!(+ key.as_deref(),+ Some("phc_integration_test_token:198.51.100.7"),+ "cookieless mode should use token:IP as partition key"+ );++ Ok(())+}++// ---------------------------------------------------------------------------+// Event with all options fields set — property injection round-trip+// ---------------------------------------------------------------------------++#[tokio::test]+async fn v1_all_options_property_injection() -> Result<()> {+ setup_tracing();+ let topic = EphemeralTopic::new().await;+ let (sink, _monitor) = build_v1_sink(topic.topic_name()).await;+ let ctx = v1_test_context();++ let uuid = uuid::Uuid::new_v4();+ let mut wrapped = test_utils::realistic_pageview("integ-user-all-opts");+ wrapped.uuid = uuid;+ wrapped.event.uuid = uuid.to_string();+ wrapped.event.options = capture::v1::analytics::types::Options {+ cookieless_mode: Some(true),+ disable_skew_correction: Some(true),+ product_tour_id: Some("tour_abc123".to_string()),+ process_person_profile: Some(false),+ };+ wrapped.event.session_id = Some("sess-opt-test".to_string());+ wrapped.event.window_id = Some("win-opt-test".to_string());++ let events: Vec<&(dyn Event + Send + Sync)> = vec![&wrapped];+ let results = sink.publish_batch(&ctx, &events).await;+ assert_eq!(results[0].outcome(), Outcome::Success);++ let event_json = topic.next_event()?;+ let captured: CapturedEvent = serde_json::from_value(event_json)?;+ let data: RawEvent = serde_json::from_str(&captured.data)?;++ assert_eq!(data.properties["$session_id"], "sess-opt-test");+ assert_eq!(data.properties["$window_id"], "win-opt-test");+ assert_eq!(data.properties["$cookieless_mode"], true);+ assert_eq!(data.properties["$ignore_sent_at"], true);+ assert_eq!(data.properties["$product_tour_id"], "tour_abc123");+ assert_eq!(data.properties["$process_person_profile"], false);++ topic.assert_empty();+ Ok(())+}++// ---------------------------------------------------------------------------+// Event with empty options — no extra properties injected from options+// ---------------------------------------------------------------------------++#[tokio::test]+async fn v1_empty_options_no_injection() -> Result<()> {+ setup_tracing();+ let topic = EphemeralTopic::new().await;+ let (sink, _monitor) = build_v1_sink(topic.topic_name()).await;+ let ctx = v1_test_context();++ let uuid = uuid::Uuid::new_v4();+ let mut wrapped = test_utils::realistic_pageview("integ-user-no-opts");+ wrapped.uuid = uuid;+ wrapped.event.uuid = uuid.to_string();+ wrapped.event.options = capture::v1::analytics::types::Options {+ cookieless_mode: None,+ disable_skew_correction: None,+ product_tour_id: None,+ process_person_profile: None,+ };+ wrapped.event.session_id = None;+ wrapped.event.window_id = None;++ let events: Vec<&(dyn Event + Send + Sync)> = vec![&wrapped];+ let results = sink.publish_batch(&ctx, &events).await;+ assert_eq!(results[0].outcome(), Outcome::Success);++ let event_json = topic.next_event()?;+ let captured: CapturedEvent = serde_json::from_value(event_json)?;+ let data: RawEvent = serde_json::from_str(&captured.data)?;++ assert!(!data.properties.contains_key("$session_id"));+ assert!(!data.properties.contains_key("$window_id"));+ assert!(!data.properties.contains_key("$cookieless_mode"));+ assert!(!data.properties.contains_key("$ignore_sent_at"));+ assert!(!data.properties.contains_key("$product_tour_id"));+ assert!(!data.properties.contains_key("$process_person_profile"));++ topic.assert_empty();+ Ok(())+}++// ---------------------------------------------------------------------------+// Multi-destination batch — events route correctly+// ---------------------------------------------------------------------------++#[tokio::test]+async fn v1_multi_destination_batch() -> Result<()> {+ setup_tracing();+ let topic = EphemeralTopic::new().await;+ let (sink, _monitor) = build_v1_sink(topic.topic_name()).await;+ let ctx = v1_test_context();++ let main_ev = test_utils::realistic_pageview("integ-dest-main");+ let hist_ev = test_utils::realistic_pageview("integ-dest-hist")+ .with_destination(capture::v1::sinks::Destination::AnalyticsHistorical);+ let overflow_ev = test_utils::realistic_pageview("integ-dest-overflow")+ .with_destination(capture::v1::sinks::Destination::Overflow);++ let events: Vec<&(dyn Event + Send + Sync)> = vec![&main_ev, &hist_ev, &overflow_ev];+ let results = sink.publish_batch(&ctx, &events).await;+ assert_eq!(results.len(), 3);+ for r in &results {+ assert_eq!(r.outcome(), Outcome::Success);+ }++ let mut distinct_ids = Vec::new();+ for _ in 0..3 {+ let json = topic.next_event()?;+ let captured: CapturedEvent = serde_json::from_value(json)?;+ distinct_ids.push(captured.distinct_id.clone());+ }+ distinct_ids.sort();+ assert_eq!(+ distinct_ids,+ vec!["integ-dest-hist", "integ-dest-main", "integ-dest-overflow"]+ );++ topic.assert_empty();+ Ok(())+}