Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(capture): v1 smoke test papercuts (#62546)

Eli Reismand0a014a77184
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index 29a317f86542..533096fa423f 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -1762,6 +1762,7 @@ dependencies = [
"flate2",
"futures",
"hex",
+ "http-body-util",
"httparse",
"hyper 1.9.0",
"hyper-util",
diff --git a/rust/capture/Cargo.toml b/rust/capture/Cargo.toml
index 7bae3ec1bcd3..02602138bbb5 100644
--- a/rust/capture/Cargo.toml
+++ b/rust/capture/Cargo.toml
@@ -21,6 +21,7 @@ bytes = { workspace = true }
envconfig = { workspace = true }
flate2 = { workspace = true }
hex = "0.4"
+http-body-util = { workspace = true }
lifecycle = { path = "../common/lifecycle" }
hyper = { workspace = true }
hyper-util = { workspace = true }
diff --git a/rust/capture/src/config.rs b/rust/capture/src/config.rs
index 52a0de6ccbd1..b232dcadd269 100644
--- a/rust/capture/src/config.rs
+++ b/rust/capture/src/config.rs
@@ -227,9 +227,6 @@ pub struct Config {
pub ai_s3_access_key_id: Option<String>,
pub ai_s3_secret_access_key: Option<String>,
- // if set in env, will configure a request timeout on the server's Axum router
- pub request_timeout_seconds: Option<u64>,
-
// HTTP/1 header read timeout in milliseconds - closes connections that don't
// send complete headers within this duration (slow loris protection).
// Set env var to enable; unset to disable.
diff --git a/rust/capture/src/metrics_middleware.rs b/rust/capture/src/metrics_middleware.rs
index bb708a61019e..665ce5868358 100644
--- a/rust/capture/src/metrics_middleware.rs
+++ b/rust/capture/src/metrics_middleware.rs
@@ -1,13 +1,11 @@
use std::sync::atomic::{AtomicUsize, Ordering};
-use std::time::{Duration, Instant};
+use std::time::Instant;
use axum::{
body::Body,
extract::{MatchedPath, Request},
- http::StatusCode,
middleware::Next,
response::IntoResponse,
- routing::Router,
};
use metrics::gauge;
@@ -30,8 +28,6 @@ impl Drop for ConnectionGuard {
const METRIC_CAPTURE_ACTIVE_CONNECTIONS: &str = "capture_active_connections";
const METRIC_HTTP_REQUESTS_TOTAL: &str = "http_requests_total";
const METRIC_HTTP_REQUESTS_DURATION_SECONDS: &str = "http_requests_duration_seconds";
-const METRIC_CAPTURE_REQUEST_TIMED_OUT: &str = "middleware_request_timed_out_total";
-const METRIC_CAPTURE_TIMEOUT_MIDDLEWARE_PASS: &str = "middleware_pass_total";
/// Middleware to record some common HTTP metrics
/// Generic over B to allow for arbitrary body types (eg Vec<u8>, Streams, a deserialized thing, etc)
@@ -69,119 +65,3 @@ pub async fn track_metrics(req: Request<Body>, next: Next) -> impl IntoResponse
response
}
-
-pub fn apply_request_timeout<S>(
- router: Router<S>,
- request_timeout_seconds: Option<u64>,
-) -> Router<S>
-where
- S: Clone + Send + Sync + 'static,
-{
- if let Some(request_timeout_seconds) = request_timeout_seconds {
- let timeout_duration = Duration::from_secs(request_timeout_seconds);
- tracing::info!(
- "Applying request timeout middleware with duration: {:?}",
- timeout_duration
- );
-
- return router.layer(axum::middleware::from_fn(
- move |req: axum::extract::Request, next: axum::middleware::Next| async move {
- let start = std::time::Instant::now();
- let method = req.method().to_string();
- let path = if let Some(matched) = req.extensions().get::<MatchedPath>() {
- matched.as_str().to_owned()
- } else {
- UNMATCHED_PATH_LABEL.to_owned()
- };
- let client_ip = req
- .headers()
- .get("X-Forwarded-For")
- .and_then(|v| v.to_str().ok())
- .and_then(|s| s.split(',').next())
- .map_or_else(|| "UNKNOWN".to_string(), |s| s.trim().to_string());
- let request_id = req
- .headers()
- .get("X-REQUEST-ID")
- .and_then(|v| v.to_str().ok())
- .map_or_else(|| "UNKNOWN".to_string(), |s| s.to_string());
- let content_type = req
- .headers()
- .get("Content-Type")
- .and_then(|v| v.to_str().ok())
- .map_or_else(|| "UNKNOWN".to_string(), |s| s.to_string());
- let content_length = req
- .headers()
- .get("Content-Length")
- .and_then(|v| v.to_str().ok())
- .map_or_else(|| "UNKNOWN".to_string(), |s| s.to_string());
- let user_agent = req
- .headers()
- .get("User-Agent")
- .and_then(|v| v.to_str().ok())
- .map_or_else(|| "UNKNOWN".to_string(), |s| s.to_string());
- let envoy_ip = req
- .headers()
- .get("X-Envoy-External-Address")
- .and_then(|v| v.to_str().ok())
- .map_or_else(|| "UNKNOWN".to_string(), |s| s.to_string());
-
- match tokio::time::timeout(timeout_duration, next.run(req)).await {
- Ok(response) => {
- let elapsed = start.elapsed();
- let threshold_exceeded = elapsed.as_secs() > request_timeout_seconds;
-
- let mut tags = vec![
- ("method", method.clone()),
- ("path", path.clone()),
- ("status", response.status().as_u16().to_string()),
- ];
- if threshold_exceeded {
- tags.push(("threshold", "exceeded".to_string()));
- } else {
- tags.push(("threshold", "respected".to_string()));
- }
- metrics::counter!(METRIC_CAPTURE_TIMEOUT_MIDDLEWARE_PASS, &tags)
- .increment(1);
-
- response
- }
- Err(_) => {
- let elapsed = start.elapsed();
- let threshold_exceeded = elapsed.as_secs() > request_timeout_seconds;
-
- let mut tags = vec![("method", method.clone()), ("path", path.clone())];
- if threshold_exceeded {
- tags.push(("threshold", "exceeded".to_string()));
- } else {
- tags.push(("threshold", "respected".to_string()));
- }
- metrics::counter!(METRIC_CAPTURE_REQUEST_TIMED_OUT, &tags).increment(1);
-
- tracing::warn!(
- method = method,
- path = path,
- request_id = request_id,
- client_ip = client_ip,
- envoy_ip = envoy_ip,
- content_type = content_type,
- content_length = content_length,
- user_agent = user_agent,
- timeout_threshold_seconds = request_timeout_seconds,
- threshold_exceeded = threshold_exceeded,
- elapsed_seconds = elapsed.as_secs_f64(),
- "Request timed out"
- );
-
- // This should be a 408 Request Timeout, but we need to set it to
- // a >500 status code to avoid breaking SDK integrations.
- (StatusCode::GATEWAY_TIMEOUT, "Request timeout").into_response()
- }
- }
- },
- ));
- }
-
- // no timeout configured
- tracing::info!("No request timeout middleware applied");
- router
-}
diff --git a/rust/capture/src/router.rs b/rust/capture/src/router.rs
index 0f6e3089858d..bff0cce82106 100644
--- a/rust/capture/src/router.rs
+++ b/rust/capture/src/router.rs
@@ -27,7 +27,7 @@ use limiters::redis::RedisLimiter;
use limiters::token_dropper::TokenDropper;
use crate::config::CaptureMode;
-use crate::metrics_middleware::{apply_request_timeout, track_metrics};
+use crate::metrics_middleware::track_metrics;
use crate::prometheus::setup_metrics_recorder;
use crate::quota_limiters::CaptureQuotaLimiter;
@@ -142,7 +142,6 @@ pub fn router<TZ: TimeSource + Send + Sync + 'static, R: Client + Send + Sync +
verbose_sample_percent: f32,
ai_max_sum_of_parts_bytes: usize,
ai_blob_storage: Option<Arc<dyn BlobStorage>>,
- request_timeout_seconds: Option<u64>,
body_chunk_read_timeout_ms: Option<u64>,
body_read_chunk_size_kb: usize,
capture_v1_max_compressed_body_bytes: usize,
@@ -336,25 +335,12 @@ pub fn router<TZ: TimeSource + Send + Sync + 'static, R: Client + Send + Sync +
.layer(DefaultBodyLimit::max(otel::OTEL_BODY_SIZE));
let mut router = match capture_mode {
- CaptureMode::Events | CaptureMode::Ai => {
- let mut events_router = Router::new()
- .merge(batch_router)
- .merge(event_router)
- .merge(test_router)
- .merge(ai_router)
- .merge(otel_router);
- // The v1 analytics endpoint is only routable when a v1 sink is
- // configured. Without a sink the handler can't publish, so we keep
- // the path unregistered (404) rather than advertising an endpoint
- // that can only ever return 503. This also isolates the route to
- // deployments that opt in via CAPTURE_V1_SINKS.
- if state.v1_sink_router.is_some() {
- events_router = events_router.merge(crate::v1::analytics::router::router().layer(
- DefaultBodyLimit::max(state.capture_v1_max_compressed_body_bytes),
- ));
- }
- events_router
- }
+ CaptureMode::Events | CaptureMode::Ai => Router::new()
+ .merge(batch_router)
+ .merge(event_router)
+ .merge(test_router)
+ .merge(ai_router)
+ .merge(otel_router),
CaptureMode::Recordings => Router::new().merge(recordings_router),
};
@@ -362,15 +348,33 @@ pub fn router<TZ: TimeSource + Send + Sync + 'static, R: Client + Send + Sync +
router = router.layer(ConcurrencyLimitLayer::new(limit));
}
- // add this prior to timeout middleware to ensure healthchecks are sensitive to load
+ // keep healthchecks outside the concurrency limit so they stay responsive under load
router = router.merge(status_router);
- // apply request timeout middleware if request_timeout_seconds is set
- router = apply_request_timeout(router, request_timeout_seconds);
+ // Legacy CORS is applied before the v1 router is merged so it stays
+ // scoped to v0/status routes; v1 ships its own policy.
+ router = router.layer(cors);
+
+ // The v1 analytics endpoint is only routable when a v1 sink is
+ // configured. Without a sink the handler can't publish, so we keep
+ // the path unregistered (404) rather than advertising an endpoint
+ // that can only ever return 503. This also isolates the route to
+ // deployments that opt in via CAPTURE_V1_SINKS.
+ //
+ // Merged after every legacy layer above: the v1 router owns its full
+ // middleware stack (CORS, limits) and applies the same per-route
+ // concurrency cap to its own routes.
+ if matches!(capture_mode, CaptureMode::Events | CaptureMode::Ai)
+ && state.v1_sink_router.is_some()
+ {
+ router = router.merge(crate::v1::router::router(crate::v1::router::RouterConfig {
+ concurrency_limit,
+ max_compressed_body_bytes: state.capture_v1_max_compressed_body_bytes,
+ }));
+ }
let router = router
.layer(TraceLayer::new_for_http())
- .layer(cors)
.layer(axum::middleware::from_fn(track_metrics))
.with_state(state);
@@ -387,165 +391,8 @@ pub fn router<TZ: TimeSource + Send + Sync + 'static, R: Client + Send + Sync +
#[cfg(test)]
mod tests {
- use super::*;
-
use std::time::Duration as StdDuration;
- use axum::http::StatusCode;
- use axum_test_helper::TestClient;
-
- async fn slow_handler() -> &'static str {
- // Sleep for 2 seconds to ensure timeout with 1 second timeout
- tokio::time::sleep(StdDuration::from_secs(2)).await;
- "slow response"
- }
-
- async fn fast_handler() -> &'static str {
- "fast response"
- }
-
- #[tokio::test]
- async fn test_timeout_returns_408() {
- // Use a 1 second timeout - the slow handler sleeps for 2 seconds, so it should timeout
- // Create router with test route included before timeout middleware is applied
- let router = Router::new().route("/slow", get(slow_handler));
- let router = apply_request_timeout(router, Some(1));
-
- let client = TestClient::new(router);
- let response = client.get("/slow").send().await;
-
- assert_eq!(response.status(), StatusCode::GATEWAY_TIMEOUT);
- let body = response.text().await;
- assert_eq!(body, "Request timeout");
- }
-
- #[tokio::test]
- async fn test_normal_request_completes_within_timeout() {
- // Use a longer timeout (1 second) so normal requests complete
- let router = Router::new().route("/fast", get(fast_handler));
- let router = apply_request_timeout(router, Some(1));
-
- let client = TestClient::new(router);
- let response = client.get("/fast").send().await;
-
- assert_eq!(response.status(), StatusCode::OK);
- let body = response.text().await;
- assert_eq!(body, "fast response");
- }
-
- #[tokio::test]
- async fn test_timeout_configuration_works() {
- // Test with 1 second timeout - should timeout on slow handler (which sleeps 2 seconds)
- let router = Router::new().route("/slow", get(slow_handler));
- let router = apply_request_timeout(router, Some(1));
-
- let client = TestClient::new(router);
- let start = std::time::Instant::now();
- let response = client.get("/slow").send().await;
- let elapsed = start.elapsed();
-
- assert_eq!(response.status(), StatusCode::GATEWAY_TIMEOUT);
- // Should timeout around 1 second (within 1.5 seconds, accounting for test overhead)
- assert!(elapsed >= StdDuration::from_millis(900)); // At least 900ms
- assert!(elapsed < StdDuration::from_millis(1500)); // But less than 1.5s
- }
-
- #[tokio::test]
- async fn test_no_timeout_when_none_specified() {
- // Test when None is specified - should complete without timeout
- let router = Router::new().route("/slow", get(slow_handler));
- let router = apply_request_timeout(router, None);
-
- let client = TestClient::new(router);
- let start = std::time::Instant::now();
- let response = client.get("/slow").send().await;
- let elapsed = start.elapsed();
-
- assert_eq!(response.status(), StatusCode::OK);
- // Should complete within 2 seconds since no timeout is specified
- assert!(elapsed >= StdDuration::from_millis(2000)); // At least 2 seconds
- }
-
- #[tokio::test]
- async fn test_timeout_on_incomplete_request() {
- // Test with 1 second timeout - simulate slow body transfer (slowloris style)
- // Send complete headers but incomplete/slow body so handler starts but times out during body reading
- use std::net::SocketAddr;
- use tokio::io::{AsyncReadExt, AsyncWriteExt};
- use tokio::net::{TcpListener, TcpStream};
-
- async fn body_reading_handler(body: axum::body::Body) -> &'static str {
- // This handler reads body as a stream, which will hang if body is incomplete
- // The timeout middleware should trigger while waiting for body chunks
- use futures::StreamExt;
-
- let mut stream = body.into_data_stream();
- // Try to read all chunks - this will hang if body is incomplete
- while stream.next().await.is_some() {
- // Process chunks
- }
- "should never reach here"
- }
-
- let router = Router::new().route("/test", post(body_reading_handler));
- let router = apply_request_timeout(router, Some(1));
-
- // Bind to a random port
- let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
- let addr = listener.local_addr().unwrap();
-
- // Spawn the server
- let server_handle = tokio::spawn(async move {
- axum::serve(
- listener,
- router.into_make_service_with_connect_info::<SocketAddr>(),
- )
- .await
- .unwrap();
- });
-
- // Give server time to start
- tokio::time::sleep(StdDuration::from_millis(100)).await;
-
- // Connect and send complete headers but incomplete body
- let mut stream = TcpStream::connect(addr).await.unwrap();
-
- // Send complete request line and headers
- stream.write_all(b"POST /test HTTP/1.1\r\n").await.unwrap();
- stream.write_all(b"Host: localhost\r\n").await.unwrap();
- stream
- .write_all(b"Content-Length: 10000\r\n")
- .await
- .unwrap(); // Claim large body
- stream
- .write_all(b"Content-Type: application/json\r\n")
- .await
- .unwrap();
- stream.write_all(b"\r\n").await.unwrap(); // Complete headers - this triggers request parsing
-
- // Send just a tiny bit of body data, then wait
- stream.write_all(b"{").await.unwrap();
-
- // Keep connection alive but don't send more data
- // The handler is waiting for the remaining 9999 bytes
- tokio::time::sleep(StdDuration::from_millis(1200)).await;
-
- // Try to read response - should get timeout response
- let mut buf = [0u8; 1024];
- let read_result = stream.read(&mut buf).await;
-
- // Should receive timeout response (408 Request Timeout)
- if let Ok(bytes_read) = read_result {
- if bytes_read > 0 {
- let response = String::from_utf8_lossy(&buf[..bytes_read]);
- assert!(response.contains("408") || response.contains("Request timeout"));
- }
- }
-
- // Clean up
- server_handle.abort();
- }
-
#[tokio::test]
async fn test_body_chunk_timeout_fires_on_stalled_upload() {
use crate::extractors::extract_body_with_timeout;
diff --git a/rust/capture/src/setup.rs b/rust/capture/src/setup.rs
index 9456aa22eb2c..e2ee231fcd37 100644
--- a/rust/capture/src/setup.rs
+++ b/rust/capture/src/setup.rs
@@ -319,7 +319,6 @@ pub async fn build_components(
config.verbose_sample_percent,
config.ai_max_sum_of_parts_bytes,
ai_blob_storage,
- config.request_timeout_seconds,
config.body_chunk_read_timeout_ms,
config.body_read_chunk_size_kb,
config.capture_v1_max_compressed_body_bytes,
diff --git a/rust/capture/src/v1/analytics/handler.rs b/rust/capture/src/v1/analytics/handler.rs
index 03b7bc7dbf2d..8e499c80abd5 100644
--- a/rust/capture/src/v1/analytics/handler.rs
+++ b/rust/capture/src/v1/analytics/handler.rs
@@ -36,6 +36,22 @@ pub async fn handle_request(
// TODO: purposely chatty, for now
ctx_log!(Level::INFO, context, "handle_request called");
+ // Non-fatal: unusable PostHog-Sdk-Info means $lib/$lib_version can't be
+ // materialized for this batch. Count once per request for visibility.
+ if context.sdk_lib_and_version().is_none() {
+ let reason = if context.sdk_info.len() > MAX_SDK_INFO_LEN {
+ "sdk_info_oversized"
+ } else {
+ "sdk_info_unparseable"
+ };
+ metrics::counter!(
+ CAPTURE_V1_WARNING_METRIC,
+ "reason" => reason,
+ "path" => context.path,
+ )
+ .increment(1);
+ }
+
let raw_bytes = v1::util::extract_body_with_timeout(
body,
state.capture_v1_max_compressed_body_bytes,
@@ -157,7 +173,7 @@ mod tests {
Router::new()
.route(CAPTURE_V1_PATH, axum::routing::post(super::handle_request))
.layer(axum::middleware::from_fn(
- super::super::router::v1_common_headers,
+ crate::v1::middleware::v1_common_headers,
))
.with_state(state)
}
@@ -169,7 +185,7 @@ mod tests {
.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_SDK_INFO, "posthog-rs/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")
@@ -236,7 +252,7 @@ mod tests {
.uri(CAPTURE_V1_PATH)
.header("Content-Type", "application/json")
.header("X-Forwarded-For", "127.0.0.1")
- .header(POSTHOG_SDK_INFO, "posthog-rust/1.0.0")
+ .header(POSTHOG_SDK_INFO, "posthog-rs/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")
@@ -327,7 +343,7 @@ mod tests {
.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_SDK_INFO, "posthog-rs/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")
@@ -358,7 +374,7 @@ mod tests {
.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_SDK_INFO, "posthog-rs/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")
@@ -385,7 +401,7 @@ mod tests {
.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_SDK_INFO, "posthog-rs/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")
diff --git a/rust/capture/src/v1/analytics/process.rs b/rust/capture/src/v1/analytics/process.rs
index 56eb5f974a5f..1bd85f1bf063 100644
--- a/rust/capture/src/v1/analytics/process.rs
+++ b/rust/capture/src/v1/analytics/process.rs
@@ -174,14 +174,13 @@ fn validate_events(context: &Context, batch: Batch) -> Result<Vec<WrappedEvent>,
let mut illegal_distinct_id_count: u64 = 0;
for event in batch.batch.into_iter() {
- let uuid_str = event.uuid();
- if uuid_str.is_empty() {
+ if event.uuid.is_empty() {
return Err(Error::MissingEventUuid);
}
- let uuid =
- Uuid::parse_str(uuid_str).map_err(|_| Error::InvalidEventUuid(uuid_str.to_owned()))?;
+ let uuid = Uuid::parse_str(&event.uuid)
+ .map_err(|_| Error::InvalidEventUuid(event.uuid.clone()))?;
if !seen.insert(uuid) {
- return Err(Error::DuplicateEventUuid(event.uuid().to_owned()));
+ return Err(Error::DuplicateEventUuid(event.uuid.clone()));
}
let destination = destination_for_event_name(&event.event);
@@ -264,11 +263,12 @@ fn observe_malformed_events(context: &Context, events: &[WrappedEvent]) {
crate::ctx_log!(Level::WARN, context, "malformed events: {summary}");
}
+/// Expects a pre-trimmed distinct_id (`Event.distinct_id` is trimmed at
+/// deserialization).
fn is_distinct_id_illegal(distinct_id: &str) -> bool {
- let trimmed = distinct_id.trim();
ILLEGAL_DISTINCT_IDS
.iter()
- .any(|id| trimmed.eq_ignore_ascii_case(id))
+ .any(|id| distinct_id.eq_ignore_ascii_case(id))
}
fn validate_event(event: &Event) -> Result<DateTime<Utc>, Error> {
@@ -407,7 +407,7 @@ async fn apply_restrictions(
distinct_id: Some(&event.event.distinct_id),
session_id: event.event.session_id.as_deref(),
event_name: Some(&event.event.event),
- event_uuid: Some(event.event.uuid()),
+ event_uuid: Some(&event.event.uuid),
now_ts,
};
@@ -539,6 +539,18 @@ mod tests {
}
}
+ /// Build an Event through serde — the production entry point — so the
+ /// trim-at-deserialization invariant on uuid/distinct_id applies.
+ fn deserialized_event(uuid: &str, distinct_id: &str) -> Event {
+ let json = serde_json::json!({
+ "event": "$pageview",
+ "uuid": uuid,
+ "distinct_id": distinct_id,
+ "timestamp": "2026-03-19T14:29:58.123Z",
+ });
+ serde_json::from_str(&json.to_string()).unwrap()
+ }
+
// --- validate_batch ---
#[test]
@@ -635,6 +647,42 @@ mod tests {
assert!(validate_event(&event).is_ok());
}
+ #[test]
+ fn event_whitespace_only_distinct_id_rejected() {
+ let event = deserialized_event(&Uuid::new_v4().to_string(), " ");
+ assert_eq!(event.distinct_id, "");
+ assert!(matches!(
+ validate_event(&event),
+ Err(Error::MissingDistinctId)
+ ));
+ }
+
+ #[test]
+ fn event_padded_distinct_id_ok() {
+ let event = deserialized_event(&Uuid::new_v4().to_string(), " user-42 ");
+ assert_eq!(event.distinct_id, "user-42");
+ assert!(validate_event(&event).is_ok());
+ }
+
+ #[test]
+ fn event_distinct_id_length_checked_after_trim() {
+ let uuid = Uuid::new_v4().to_string();
+ let event = deserialized_event(
+ &uuid,
+ &format!(" {} ", "d".repeat(CAPTURE_V1_DISTINCT_ID_MAX_SIZE)),
+ );
+ assert!(validate_event(&event).is_ok());
+
+ let event = deserialized_event(
+ &uuid,
+ &format!(" {} ", "d".repeat(CAPTURE_V1_DISTINCT_ID_MAX_SIZE + 1)),
+ );
+ assert!(matches!(
+ validate_event(&event),
+ Err(Error::DistinctIdTooLarge)
+ ));
+ }
+
#[test]
fn event_illegal_distinct_ids_pass_validation() {
let illegal_ids = [
@@ -656,8 +704,7 @@ mod tests {
"not_authenticated",
];
for id in illegal_ids {
- let mut event = valid_event();
- event.distinct_id = id.to_string();
+ let event = deserialized_event(&Uuid::new_v4().to_string(), id);
assert!(
validate_event(&event).is_ok(),
"expected Ok for illegal distinct_id={id:?} (flagging happens in validate_events)"
@@ -733,9 +780,9 @@ mod tests {
event: "$performance_event".to_string(),
..valid_event()
};
- let perf_uuid = Uuid::parse_str(perf.uuid()).unwrap();
+ let perf_uuid = Uuid::parse_str(&perf.uuid).unwrap();
let normal = valid_event();
- let normal_uuid = Uuid::parse_str(normal.uuid()).unwrap();
+ let normal_uuid = Uuid::parse_str(&normal.uuid).unwrap();
let batch = valid_batch(vec![perf, normal]);
let events = validate_events(&ctx, batch).unwrap();
assert_eq!(events.len(), 2);
@@ -797,6 +844,17 @@ mod tests {
}
}
+ #[test]
+ fn validate_events_padded_illegal_distinct_id_still_flagged() {
+ let ctx = test_utils::test_context();
+ let event = deserialized_event(&Uuid::new_v4().to_string(), " NULL ");
+ let batch = valid_batch(vec![event]);
+ let events = validate_events(&ctx, batch).unwrap();
+ assert_eq!(events[0].result, EventResult::Ok);
+ assert!(events[0].force_disable_person_processing);
+ assert_eq!(events[0].details, Some(DETAIL_PERSON_PROCESSING_DISABLED));
+ }
+
#[test]
fn validate_events_illegal_distinct_id_still_publishable() {
for id in ILLEGAL_DISTINCT_IDS {
@@ -872,15 +930,9 @@ mod tests {
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 event = deserialized_event(&padded_uuid, "user-42");
+ assert_eq!(event.uuid, inner_uuid.to_string());
+ let batch = valid_batch(vec![event]);
let events = validate_events(&ctx, batch).unwrap();
assert_eq!(events.len(), 1);
assert_eq!(events[0].uuid, inner_uuid);
@@ -893,7 +945,7 @@ mod tests {
properties: raw_obj("[1,2,3]"),
..valid_event()
};
- let uuid = Uuid::parse_str(bad_event.uuid()).unwrap();
+ let uuid = Uuid::parse_str(&bad_event.uuid).unwrap();
let batch = Batch {
created_at: "2026-03-19T14:30:00.000Z".to_string(),
historical_migration: false,
diff --git a/rust/capture/src/v1/analytics/router.rs b/rust/capture/src/v1/analytics/router.rs
index 34dcf9c92ce6..95499781380b 100644
--- a/rust/capture/src/v1/analytics/router.rs
+++ b/rust/capture/src/v1/analytics/router.rs
@@ -1,17 +1,11 @@
-use std::time::Instant;
-
-use axum::extract::{MatchedPath, Request};
-use axum::http::{header, HeaderValue};
-use axum::middleware::Next;
-use axum::response::Response;
use axum::Router;
-use chrono::Utc;
use super::constants::{CAPTURE_V1_PATH, CAPTURE_V1_PATH_TRAILING};
use crate::router::State;
-use crate::v1::constants::{CAPTURE_V1_RESPONSE_TIME, POSTHOG_REQUEST_ID};
-pub fn router() -> Router<State> {
+/// Route declarations only. The shared v1 middleware stack (headers, metrics,
+/// timeout, CORS, limits) is owned by `crate::v1::router`.
+pub fn routes() -> Router<State> {
Router::new()
.route(
CAPTURE_V1_PATH,
@@ -21,177 +15,4 @@ pub fn router() -> Router<State> {
CAPTURE_V1_PATH_TRAILING,
axum::routing::post(super::handler::handle_request),
)
- .layer(axum::middleware::from_fn(v1_common_headers))
- .layer(axum::middleware::from_fn(v1_track_response_time))
-}
-
-pub(super) async fn v1_common_headers(req: Request, next: Next) -> Response {
- let received_at = Utc::now();
- let request_id = req.headers().get(POSTHOG_REQUEST_ID).cloned();
-
- let mut response = next.run(req).await;
-
- let headers = response.headers_mut();
- if let Ok(date_val) = HeaderValue::from_str(&received_at.to_rfc2822()) {
- headers.insert(header::DATE, date_val);
- }
- if let Some(id) = request_id {
- headers.insert(POSTHOG_REQUEST_ID, id);
- }
- response
-}
-
-pub(super) async fn v1_track_response_time(req: Request, next: Next) -> Response {
- let start = Instant::now();
-
- let path = req
- .extensions()
- .get::<MatchedPath>()
- .map(|m| m.as_str().to_owned())
- .unwrap_or_else(|| req.uri().path().to_owned());
-
- let response = next.run(req).await;
-
- let status = response.status().as_u16().to_string();
- let elapsed = start.elapsed().as_secs_f64();
-
- metrics::histogram!(
- CAPTURE_V1_RESPONSE_TIME,
- "status" => status,
- "path" => path,
- )
- .record(elapsed);
-
- response
-}
-
-#[cfg(test)]
-mod tests {
- use axum::body::Body;
- use axum::http::{header, HeaderValue, Request, StatusCode};
- use axum::middleware;
- use axum::routing::get;
- use axum::Router;
- use chrono::DateTime;
- use tower::ServiceExt;
- use uuid::Uuid;
-
- use super::{v1_common_headers, v1_track_response_time};
- use crate::v1::constants::POSTHOG_REQUEST_ID;
-
- fn test_router() -> Router {
- Router::new()
- .route("/test", get(|| async { "ok" }))
- .layer(middleware::from_fn(v1_common_headers))
- }
-
- fn test_router_with_response_time() -> Router {
- Router::new()
- .route("/test", get(|| async { "ok" }))
- .route(
- "/error",
- get(|| async { StatusCode::INTERNAL_SERVER_ERROR }),
- )
- .layer(middleware::from_fn(v1_track_response_time))
- }
-
- #[tokio::test]
- async fn common_headers_sets_date() {
- let resp = test_router()
- .oneshot(Request::builder().uri("/test").body(Body::empty()).unwrap())
- .await
- .unwrap();
-
- assert_eq!(resp.status(), StatusCode::OK);
- let date = resp
- .headers()
- .get(header::DATE)
- .expect("Date header missing");
- let parsed = DateTime::parse_from_rfc2822(date.to_str().unwrap());
- assert!(
- parsed.is_ok(),
- "Date header is not valid RFC 2822: {date:?}"
- );
- }
-
- #[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();
- let resp = test_router()
- .oneshot(
- Request::builder()
- .uri("/test")
- .header(POSTHOG_REQUEST_ID, HeaderValue::from_str(&id).unwrap())
- .body(Body::empty())
- .unwrap(),
- )
- .await
- .unwrap();
-
- assert_eq!(resp.status(), StatusCode::OK);
- let returned = resp
- .headers()
- .get(POSTHOG_REQUEST_ID)
- .expect("PostHog-Request-Id missing on response");
- assert_eq!(returned.to_str().unwrap(), id);
- }
-
- #[tokio::test]
- async fn common_headers_omits_request_id_when_absent() {
- 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(POSTHOG_REQUEST_ID).is_none(),
- "PostHog-Request-Id should not be set when absent from request"
- );
- }
-
- // --- v1_track_response_time ---
-
- #[tokio::test]
- async fn response_time_middleware_passes_through_success() {
- let resp = test_router_with_response_time()
- .oneshot(Request::builder().uri("/test").body(Body::empty()).unwrap())
- .await
- .unwrap();
-
- assert_eq!(resp.status(), StatusCode::OK);
- }
-
- #[tokio::test]
- async fn response_time_middleware_passes_through_error_status() {
- let resp = test_router_with_response_time()
- .oneshot(
- Request::builder()
- .uri("/error")
- .body(Body::empty())
- .unwrap(),
- )
- .await
- .unwrap();
-
- assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
- }
}
diff --git a/rust/capture/src/v1/analytics/types.rs b/rust/capture/src/v1/analytics/types.rs
index 00cc894a8bdf..2685f19e3180 100644
--- a/rust/capture/src/v1/analytics/types.rs
+++ b/rust/capture/src/v1/analytics/types.rs
@@ -30,6 +30,21 @@ fn empty_raw_object() -> Box<RawValue> {
RawValue::from_string("{}".to_owned()).unwrap()
}
+/// Trim client-submitted whitespace once, at the deserialization boundary.
+/// Only reallocates when padding is actually present.
+fn deserialize_trimmed_string<'de, D>(deserializer: D) -> Result<String, D::Error>
+where
+ D: serde::Deserializer<'de>,
+{
+ let s = String::deserialize(deserializer)?;
+ let trimmed = s.trim();
+ Ok(if trimmed.len() == s.len() {
+ s
+ } else {
+ trimmed.to_owned()
+ })
+}
+
/// Per-event outcome in the batch response.
/// Ok: captured successfully. Drop: rejected (billing/validation). Warning: accepted
/// with person processing disabled (do not resubmit). Retry: not persisted, safe to resubmit.
@@ -68,7 +83,12 @@ pub struct Options {
#[derive(Debug, Deserialize)]
pub struct Event {
pub event: String,
+ /// Trimmed at deserialization: callers may rely on this being free of
+ /// client-submitted leading/trailing whitespace.
+ #[serde(deserialize_with = "deserialize_trimmed_string")]
pub uuid: String,
+ /// Trimmed at deserialization so padded IDs resolve to the same person.
+ #[serde(deserialize_with = "deserialize_trimmed_string")]
pub distinct_id: String,
pub timestamp: String,
pub session_id: Option<String>,
@@ -79,14 +99,6 @@ pub struct Event {
pub properties: Box<RawValue>,
}
-impl Event {
- /// Trimmed accessor for the raw UUID string. Prefer this over direct
- /// field access so callers are insulated from client-submitted whitespace.
- pub fn uuid(&self) -> &str {
- self.uuid.trim()
- }
-}
-
#[derive(Debug)]
pub struct WrappedEvent {
pub event: Event,
@@ -162,7 +174,7 @@ impl SinkEvent for WrappedEvent {
.adjusted_timestamp
.map(|ts| ts.timestamp_millis().to_string()),
event: Some(self.event.event.clone()),
- uuid: Some(self.event.uuid().to_owned()),
+ uuid: Some(self.event.uuid.clone()),
now: Some(
ctx.server_received_at
.to_rfc3339_opts(SecondsFormat::AutoSi, true),
@@ -196,7 +208,7 @@ impl SinkEvent for WrappedEvent {
}
fn serialize_into(&self, ctx: &Context, buf: &mut String) -> anyhow::Result<()> {
- let spliced = self.build_spliced_properties()?;
+ let spliced = self.build_spliced_properties(ctx)?;
let properties: &RawValue = spliced.as_deref().unwrap_or(&self.event.properties);
let ingestion_data = IngestionData {
event: &self.event.event,
@@ -243,7 +255,7 @@ impl SinkEvent for WrappedEvent {
impl WrappedEvent {
#[allow(unused_assignments)]
- fn build_property_injections(&self) -> anyhow::Result<String> {
+ fn build_property_injections(&self, ctx: &Context) -> anyhow::Result<String> {
let mut buf = String::with_capacity(256);
let mut first = true;
@@ -280,13 +292,23 @@ impl WrappedEvent {
inject!(buf, first, "$process_person_profile", &ppp);
}
+ // Materialize $lib/$lib_version from the required PostHog-Sdk-Info
+ // header — the canonical v1 SDK identity. Appended after client keys,
+ // so the header wins under last-key-wins parsing (same duplicate-key
+ // semantics as the injections above). Unusable headers inject nothing
+ // and are counted per-request in the handler.
+ if let Some((lib, lib_version)) = ctx.sdk_lib_and_version() {
+ inject!(buf, first, "$lib", lib);
+ inject!(buf, first, "$lib_version", lib_version);
+ }
+
Ok(buf)
}
/// Build spliced properties if injection is needed, or return None
/// to signal the caller should borrow `self.event.properties` directly.
- fn build_spliced_properties(&self) -> anyhow::Result<Option<Box<RawValue>>> {
- let injection = self.build_property_injections()?;
+ fn build_spliced_properties(&self, ctx: &Context) -> anyhow::Result<Option<Box<RawValue>>> {
+ let injection = self.build_property_injections(ctx)?;
if injection.is_empty() {
return Ok(None);
}
@@ -419,6 +441,39 @@ mod tests {
assert_eq!(event.properties.get(), "{}");
}
+ #[test]
+ fn parse_event_trims_uuid_and_distinct_id() {
+ let json = r#"{
+ "created_at": "2026-03-19T14:30:00.000Z",
+ "batch": [{
+ "event": "$pageview",
+ "uuid": " a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d ",
+ "distinct_id": " user-42 ",
+ "timestamp": "2026-03-19T14:29:58.123Z"
+ }]
+ }"#;
+ let batch: Batch = serde_json::from_str(json).unwrap();
+ let event = &batch.batch[0];
+ assert_eq!(event.uuid, "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d");
+ assert_eq!(event.distinct_id, "user-42");
+ }
+
+ #[test]
+ fn parse_event_whitespace_only_distinct_id_collapses_to_empty() {
+ // Validation rejects the empty result with MissingDistinctId.
+ let json = r#"{
+ "created_at": "2026-03-19T14:30:00.000Z",
+ "batch": [{
+ "event": "$pageview",
+ "uuid": "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d",
+ "distinct_id": " ",
+ "timestamp": "2026-03-19T14:29:58.123Z"
+ }]
+ }"#;
+ let batch: Batch = serde_json::from_str(json).unwrap();
+ assert_eq!(batch.batch[0].distinct_id, "");
+ }
+
#[test]
fn parse_batch_with_properties() {
let json = r#"{
@@ -1072,6 +1127,89 @@ mod tests {
assert_eq!(props["$process_person_profile"], true);
}
+ #[test]
+ fn serialize_injects_lib_from_sdk_info_header() {
+ let wrapped = pageview_event();
+ let ctx = serialize_ctx(); // sdk_info: "posthog-rs/1.0.0"
+ let (_, data) = serialize_and_parse(&wrapped, &ctx);
+
+ assert_eq!(data.properties["$lib"], "posthog-rs");
+ assert_eq!(data.properties["$lib_version"], "1.0.0");
+ }
+
+ #[test]
+ fn serialize_lib_injection_header_wins_over_client_properties() {
+ let mut wrapped = pageview_event();
+ wrapped.event.properties =
+ raw_obj(r#"{"$lib":"client-lib","$lib_version":"9.9.9","custom_prop":42}"#);
+ let ctx = serialize_ctx();
+ let (_, data) = serialize_and_parse(&wrapped, &ctx);
+
+ // Injections append after client keys; last-key-wins parsing makes
+ // the header authoritative.
+ assert_eq!(data.properties["$lib"], "posthog-rs");
+ assert_eq!(data.properties["$lib_version"], "1.0.0");
+ assert_eq!(data.properties["custom_prop"], 42);
+ }
+
+ #[test]
+ fn serialize_oversized_sdk_info_skips_lib_injection() {
+ use crate::v1::constants::MAX_SDK_INFO_LEN;
+
+ let wrapped = pageview_event();
+ let mut ctx = serialize_ctx();
+ ctx.sdk_info = format!("posthog-rs/{}", "9".repeat(MAX_SDK_INFO_LEN));
+ let (_, data) = serialize_and_parse(&wrapped, &ctx);
+
+ assert!(!data.properties.contains_key("$lib"));
+ assert!(!data.properties.contains_key("$lib_version"));
+ }
+
+ #[test]
+ fn serialize_malformed_sdk_info_skips_lib_injection() {
+ for bad in &["garbage-no-slash", "/1.0.0", "posthog-rs/", ""] {
+ let wrapped = pageview_event();
+ let mut ctx = serialize_ctx();
+ ctx.sdk_info = bad.to_string();
+ let (_, data) = serialize_and_parse(&wrapped, &ctx);
+
+ // No placeholders: absent rather than "unknown"/"0.0.0".
+ assert!(
+ !data.properties.contains_key("$lib"),
+ "expected no $lib for sdk_info {bad:?}"
+ );
+ assert!(
+ !data.properties.contains_key("$lib_version"),
+ "expected no $lib_version for sdk_info {bad:?}"
+ );
+ }
+ }
+
+ #[test]
+ fn serialize_padded_distinct_id_trimmed_everywhere() {
+ // Padding is stripped at the deserialization boundary; everything
+ // downstream (serialization, headers, partition key) sees it trimmed.
+ let mut wrapped = pageview_event();
+ let json = format!(
+ r#"{{"event":"$pageview","uuid":"{}","distinct_id":" user-42 ","timestamp":"2026-03-19T14:29:58.123Z"}}"#,
+ wrapped.uuid
+ );
+ wrapped.event = serde_json::from_str(&json).unwrap();
+ assert_eq!(wrapped.event.distinct_id, "user-42");
+ let ctx = serialize_ctx();
+
+ let (captured, data) = serialize_and_parse(&wrapped, &ctx);
+ assert_eq!(captured.distinct_id, "user-42");
+ assert_eq!(data.distinct_id, Some(Value::String("user-42".to_string())));
+
+ let headers = wrapped.headers(&ctx);
+ assert_eq!(headers.distinct_id.as_deref(), Some("user-42"));
+
+ let mut key = String::new();
+ wrapped.partition_key(&ctx, &mut key);
+ assert_eq!(key, format!("{}:user-42", ctx.api_token));
+ }
+
#[test]
fn serialize_ip_redaction_capture_internal() {
let wrapped = pageview_event();
@@ -1197,7 +1335,11 @@ mod tests {
let ctx = serialize_ctx();
let (_, data) = serialize_and_parse(&wrapped, &ctx);
- assert!(data.properties.is_empty());
+ // $lib/$lib_version always materialize from the (valid) Sdk-Info header.
+ let props = &data.properties;
+ assert_eq!(props["$lib"], "posthog-rs");
+ assert_eq!(props["$lib_version"], "1.0.0");
+ assert_eq!(props.len(), 2);
}
#[test]
@@ -1232,7 +1374,9 @@ mod tests {
let props = &data.properties;
assert_eq!(props["$session_id"], "sess-abc");
assert_eq!(props["$cookieless_mode"], true);
- assert_eq!(props.len(), 2);
+ assert_eq!(props["$lib"], "posthog-rs");
+ assert_eq!(props["$lib_version"], "1.0.0");
+ assert_eq!(props.len(), 4);
}
#[test]
@@ -1267,8 +1411,10 @@ mod tests {
let ctx = serialize_ctx();
let (_, data) = serialize_and_parse(&wrapped, &ctx);
let props = &data.properties;
- assert_eq!(props["$lib"], "posthog-js");
- assert_eq!(props["$lib_version"], "1.150.0");
+ // Non-identity client properties survive; $lib/$lib_version come from
+ // the Sdk-Info header (header-wins).
+ assert_eq!(props["$lib"], "posthog-rs");
+ assert_eq!(props["$lib_version"], "1.0.0");
assert_eq!(props["$referrer"], "https://google.com");
assert_eq!(props["$session_id"], "sess-abc");
}
@@ -1500,7 +1646,9 @@ mod tests {
let ctx = serialize_ctx();
let (_, data) = serialize_and_parse(&wrapped, &ctx);
assert_eq!(data.properties["$session_id"], "sess-abc");
- assert_eq!(data.properties.len(), 1);
+ assert_eq!(data.properties["$lib"], "posthog-rs");
+ assert_eq!(data.properties["$lib_version"], "1.0.0");
+ assert_eq!(data.properties.len(), 3);
}
// --- CapturedEvent round-trip parity using realistic fixtures ---
diff --git a/rust/capture/src/v1/constants.rs b/rust/capture/src/v1/constants.rs
index 086030c75b6e..9f6cf4bd6bb8 100644
--- a/rust/capture/src/v1/constants.rs
+++ b/rust/capture/src/v1/constants.rs
@@ -7,6 +7,11 @@
/// Header carrying SDK name/version metadata.
pub const POSTHOG_SDK_INFO: &str = "PostHog-Sdk-Info";
+/// Max accepted `PostHog-Sdk-Info` length (real values are ~20 bytes). Longer
+/// values skip `$lib` injection so an oversized header can't be amplified
+/// into every event of a batch.
+pub(super) const MAX_SDK_INFO_LEN: usize = 200;
+
/// Header indicating the SDK retry attempt number.
pub const POSTHOG_ATTEMPT: &str = "PostHog-Attempt";
@@ -40,6 +45,10 @@ pub(super) const REQUIRED_HEADERS: &[&str] = &[
/// Counter name for v1 analytics errors (labels: error, level, path, status_code).
pub(super) const CAPTURE_V1_ERROR_METRIC: &str = "capture_v1_analytics_error";
+/// Counter for non-fatal conditions on otherwise-successful v1 requests
+/// (labels: reason, path). Shared key to avoid single-use metrics in Grafana.
+pub(super) const CAPTURE_V1_WARNING_METRIC: &str = "capture_v1_analytics_warning";
+
/// Counter name for body-read timeouts during payload extraction.
pub(super) const CAPTURE_V1_BODY_READ_TIMEOUT: &str = "capture_v1_body_read_timeout_total";
diff --git a/rust/capture/src/v1/context.rs b/rust/capture/src/v1/context.rs
index e5ef16328028..619c0c28ad6c 100644
--- a/rust/capture/src/v1/context.rs
+++ b/rust/capture/src/v1/context.rs
@@ -48,6 +48,21 @@ impl Context {
.signed_duration_since(self.server_received_at)
}
+ /// Parse `PostHog-Sdk-Info` (`<canonical-$lib-name>/<semver>`, split at
+ /// the last '/') into `($lib, $lib_version)`. Returns `None` for malformed
+ /// or oversized values — callers skip injection, never inject placeholders.
+ pub fn sdk_lib_and_version(&self) -> Option<(&str, &str)> {
+ if self.sdk_info.len() > MAX_SDK_INFO_LEN {
+ return None;
+ }
+ let (lib, version) = self.sdk_info.rsplit_once('/')?;
+ let (lib, version) = (lib.trim(), version.trim());
+ if lib.is_empty() || version.is_empty() {
+ return None;
+ }
+ Some((lib, version))
+ }
+
pub fn new(
headers: &HeaderMap,
ip: &InsecureClientIp,
@@ -199,7 +214,7 @@ mod tests {
);
h.insert(
POSTHOG_SDK_INFO,
- HeaderValue::from_static("posthog-rust/1.0.0"),
+ HeaderValue::from_static("posthog-rs/1.0.0"),
);
h.insert(POSTHOG_ATTEMPT, HeaderValue::from_static("1"));
h.insert(
@@ -381,6 +396,61 @@ mod tests {
assert!(matches!(err, Error::InvalidHeaderValue(_)));
}
+ #[test]
+ fn sdk_lib_and_version_parses_canonical_format() {
+ let headers = valid_headers();
+ let ctx = test_context(&headers).unwrap();
+ assert_eq!(ctx.sdk_lib_and_version(), Some(("posthog-rs", "1.0.0")));
+ }
+
+ #[test]
+ fn sdk_lib_and_version_splits_at_last_slash() {
+ let mut headers = valid_headers();
+ headers.insert(
+ POSTHOG_SDK_INFO,
+ HeaderValue::from_static("posthog/sub-sdk/2.3.4"),
+ );
+ let ctx = test_context(&headers).unwrap();
+ assert_eq!(
+ ctx.sdk_lib_and_version(),
+ Some(("posthog/sub-sdk", "2.3.4"))
+ );
+ }
+
+ #[test]
+ fn sdk_lib_and_version_trims_whitespace() {
+ let mut headers = valid_headers();
+ headers.insert(
+ POSTHOG_SDK_INFO,
+ HeaderValue::from_static(" posthog-rs / 1.2.3 "),
+ );
+ let ctx = test_context(&headers).unwrap();
+ assert_eq!(ctx.sdk_lib_and_version(), Some(("posthog-rs", "1.2.3")));
+ }
+
+ #[test]
+ fn sdk_lib_and_version_rejects_oversized_value() {
+ let mut headers = valid_headers();
+ let long = format!("posthog-rs/{}", "9".repeat(MAX_SDK_INFO_LEN));
+ headers.insert(POSTHOG_SDK_INFO, HeaderValue::from_str(&long).unwrap());
+ let ctx = test_context(&headers).unwrap();
+ assert_eq!(ctx.sdk_lib_and_version(), None);
+ }
+
+ #[test]
+ fn sdk_lib_and_version_rejects_malformed_values() {
+ for bad in &["no-slash", "/1.0.0", "posthog-rs/", "/", "", " / "] {
+ let mut headers = valid_headers();
+ headers.insert(POSTHOG_SDK_INFO, HeaderValue::from_str(bad).unwrap());
+ let ctx = test_context(&headers).unwrap();
+ assert_eq!(
+ ctx.sdk_lib_and_version(),
+ None,
+ "expected None for sdk_info: {bad:?}"
+ );
+ }
+ }
+
#[test]
fn invalid_rfc3339_timestamp() {
let mut headers = valid_headers();
diff --git a/rust/capture/src/v1/middleware.rs b/rust/capture/src/v1/middleware.rs
new file mode 100644
index 000000000000..a73120f74cbf
--- /dev/null
+++ b/rust/capture/src/v1/middleware.rs
@@ -0,0 +1,183 @@
+//! Middleware shared by all v1 endpoints. Applied by `v1::router`; individual
+//! feature routers (e.g. `v1::analytics`) only declare routes.
+
+use std::time::Instant;
+
+use axum::extract::{MatchedPath, Request};
+use axum::http::{header, HeaderValue};
+use axum::middleware::Next;
+use axum::response::Response;
+use chrono::Utc;
+
+use crate::v1::constants::{CAPTURE_V1_RESPONSE_TIME, POSTHOG_REQUEST_ID};
+
+pub async fn v1_common_headers(req: Request, next: Next) -> Response {
+ let received_at = Utc::now();
+ let request_id = req.headers().get(POSTHOG_REQUEST_ID).cloned();
+
+ let mut response = next.run(req).await;
+
+ let headers = response.headers_mut();
+ if let Ok(date_val) = HeaderValue::from_str(&received_at.to_rfc2822()) {
+ headers.insert(header::DATE, date_val);
+ }
+ if let Some(id) = request_id {
+ headers.insert(POSTHOG_REQUEST_ID, id);
+ }
+ response
+}
+
+pub async fn v1_track_response_time(req: Request, next: Next) -> Response {
+ let start = Instant::now();
+
+ let path = req
+ .extensions()
+ .get::<MatchedPath>()
+ .map(|m| m.as_str().to_owned())
+ .unwrap_or_else(|| req.uri().path().to_owned());
+
+ let response = next.run(req).await;
+
+ let status = response.status().as_u16().to_string();
+ let elapsed = start.elapsed().as_secs_f64();
+
+ metrics::histogram!(
+ CAPTURE_V1_RESPONSE_TIME,
+ "status" => status,
+ "path" => path,
+ )
+ .record(elapsed);
+
+ response
+}
+
+#[cfg(test)]
+mod tests {
+ use axum::body::Body;
+ use axum::http::{header, HeaderValue, Request, StatusCode};
+ use axum::middleware;
+ use axum::routing::get;
+ use axum::Router;
+ use chrono::DateTime;
+ use tower::ServiceExt;
+ use uuid::Uuid;
+
+ use super::{v1_common_headers, v1_track_response_time};
+ use crate::v1::constants::POSTHOG_REQUEST_ID;
+
+ fn test_router() -> Router {
+ Router::new()
+ .route("/test", get(|| async { "ok" }))
+ .layer(middleware::from_fn(v1_common_headers))
+ }
+
+ fn test_router_with_response_time() -> Router {
+ Router::new()
+ .route("/test", get(|| async { "ok" }))
+ .route(
+ "/error",
+ get(|| async { StatusCode::INTERNAL_SERVER_ERROR }),
+ )
+ .layer(middleware::from_fn(v1_track_response_time))
+ }
+
+ #[tokio::test]
+ async fn common_headers_sets_date() {
+ let resp = test_router()
+ .oneshot(Request::builder().uri("/test").body(Body::empty()).unwrap())
+ .await
+ .unwrap();
+
+ assert_eq!(resp.status(), StatusCode::OK);
+ let date = resp
+ .headers()
+ .get(header::DATE)
+ .expect("Date header missing");
+ let parsed = DateTime::parse_from_rfc2822(date.to_str().unwrap());
+ assert!(
+ parsed.is_ok(),
+ "Date header is not valid RFC 2822: {date:?}"
+ );
+ }
+
+ #[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();
+ let resp = test_router()
+ .oneshot(
+ Request::builder()
+ .uri("/test")
+ .header(POSTHOG_REQUEST_ID, HeaderValue::from_str(&id).unwrap())
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(resp.status(), StatusCode::OK);
+ let returned = resp
+ .headers()
+ .get(POSTHOG_REQUEST_ID)
+ .expect("PostHog-Request-Id missing on response");
+ assert_eq!(returned.to_str().unwrap(), id);
+ }
+
+ #[tokio::test]
+ async fn common_headers_omits_request_id_when_absent() {
+ 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(POSTHOG_REQUEST_ID).is_none(),
+ "PostHog-Request-Id should not be set when absent from request"
+ );
+ }
+
+ // --- v1_track_response_time ---
+
+ #[tokio::test]
+ async fn response_time_middleware_passes_through_success() {
+ let resp = test_router_with_response_time()
+ .oneshot(Request::builder().uri("/test").body(Body::empty()).unwrap())
+ .await
+ .unwrap();
+
+ assert_eq!(resp.status(), StatusCode::OK);
+ }
+
+ #[tokio::test]
+ async fn response_time_middleware_passes_through_error_status() {
+ let resp = test_router_with_response_time()
+ .oneshot(
+ Request::builder()
+ .uri("/error")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
+ }
+}
diff --git a/rust/capture/src/v1/mod.rs b/rust/capture/src/v1/mod.rs
index b2178d7f53b7..1bea9431ec7d 100644
--- a/rust/capture/src/v1/mod.rs
+++ b/rust/capture/src/v1/mod.rs
@@ -2,7 +2,9 @@ pub mod analytics;
pub mod constants;
pub mod context;
pub mod error;
+pub mod middleware;
pub mod quota_limiter_shim;
+pub mod router;
pub mod sinks;
#[cfg(any(test, feature = "test-utils"))]
pub mod test_utils;
diff --git a/rust/capture/src/v1/quota_limiter_shim.rs b/rust/capture/src/v1/quota_limiter_shim.rs
index 88869f10ad53..634546af41ec 100644
--- a/rust/capture/src/v1/quota_limiter_shim.rs
+++ b/rust/capture/src/v1/quota_limiter_shim.rs
@@ -227,7 +227,6 @@ mod tests {
ai_s3_region: "us-east-1".to_string(),
ai_s3_access_key_id: None,
ai_s3_secret_access_key: None,
- request_timeout_seconds: Some(10),
http1_header_read_timeout_ms: Some(5000),
body_chunk_read_timeout_ms: None,
body_read_chunk_size_kb: 256,
diff --git a/rust/capture/src/v1/router.rs b/rust/capture/src/v1/router.rs
new file mode 100644
index 000000000000..26a30f11194b
--- /dev/null
+++ b/rust/capture/src/v1/router.rs
@@ -0,0 +1,169 @@
+//! Top-level v1 router. Owns the complete middleware stack for every v1
+//! endpoint so no legacy/v0 layer (CORS, body limits, etc.) applies to v1
+//! requests. `crate::router` merges this after all legacy layers are in place;
+//! future v1 endpoints mount their routes here to inherit the same contract.
+//!
+//! Stack, outermost first:
+//! CORS -> response-time metric -> common headers
+//! -> concurrency limit -> body-size backstop -> routes
+
+use axum::extract::DefaultBodyLimit;
+use axum::http::Method;
+use axum::Router;
+use tower::limit::ConcurrencyLimitLayer;
+use tower_http::cors::{AllowHeaders, AllowOrigin, CorsLayer};
+
+use crate::router::State;
+use crate::v1::middleware::{v1_common_headers, v1_track_response_time};
+
+pub struct RouterConfig {
+ /// Per-route in-flight cap, same `CONCURRENCY_LIMIT` value the legacy
+ /// router applies to its own routes (axum's `Router::layer` wraps each
+ /// route individually, so every route gets its own permit pool).
+ pub concurrency_limit: Option<usize>,
+ /// Backstop only: `v1::util` enforces the real compressed-size limit and
+ /// returns the 413 envelope before this extractor-level limit can trip.
+ pub max_compressed_body_bytes: usize,
+}
+
+pub fn router(cfg: RouterConfig) -> Router<State> {
+ // v1 endpoints are POST-only; preflight is answered by the CORS layer.
+ let cors = CorsLayer::new()
+ .allow_methods([Method::POST, Method::OPTIONS])
+ .allow_headers(AllowHeaders::mirror_request())
+ .allow_credentials(true)
+ .allow_origin(AllowOrigin::mirror_request());
+
+ let mut router = crate::v1::analytics::router::routes()
+ .layer(DefaultBodyLimit::max(cfg.max_compressed_body_bytes));
+
+ if let Some(limit) = cfg.concurrency_limit {
+ router = router.layer(ConcurrencyLimitLayer::new(limit));
+ }
+
+ router
+ .layer(axum::middleware::from_fn(v1_common_headers))
+ .layer(axum::middleware::from_fn(v1_track_response_time))
+ .layer(cors)
+}
+
+#[cfg(test)]
+mod tests {
+ use axum::body::Body;
+ use axum::http::{header, Method, Request, StatusCode};
+ use axum::Router;
+ use tower::ServiceExt;
+ use uuid::Uuid;
+
+ use super::{router, RouterConfig};
+ use crate::v1::analytics::constants::CAPTURE_V1_PATH;
+ use crate::v1::constants::{
+ POSTHOG_ATTEMPT, POSTHOG_REQUEST_ID, POSTHOG_REQUEST_TIMESTAMP, POSTHOG_SDK_INFO,
+ };
+ use crate::v1::test_utils::{batch_payload, valid_event, TestStateBuilder};
+
+ fn app(cfg: RouterConfig) -> Router {
+ let ts = TestStateBuilder::new().build();
+ router(cfg).with_state(ts.state)
+ }
+
+ fn default_cfg() -> RouterConfig {
+ RouterConfig {
+ concurrency_limit: Some(8),
+ max_compressed_body_bytes: 1024 * 1024,
+ }
+ }
+
+ fn valid_request() -> axum::http::request::Builder {
+ Request::builder()
+ .method("POST")
+ .uri(CAPTURE_V1_PATH)
+ .header("Authorization", "Bearer phc_test_token")
+ .header("Content-Type", "application/json")
+ .header("X-Forwarded-For", "127.0.0.1")
+ .header(POSTHOG_SDK_INFO, "posthog-rs/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")
+ }
+
+ #[tokio::test]
+ async fn post_reaches_handler_through_full_stack() {
+ let payload = batch_payload(&[valid_event()]);
+ let resp = app(default_cfg())
+ .oneshot(valid_request().body(Body::from(payload)).unwrap())
+ .await
+ .unwrap();
+
+ assert_eq!(resp.status(), StatusCode::OK);
+ assert!(resp.headers().get(header::DATE).is_some());
+ }
+
+ #[tokio::test]
+ async fn preflight_answered_by_v1_cors() {
+ let resp = app(default_cfg())
+ .oneshot(
+ Request::builder()
+ .method(Method::OPTIONS)
+ .uri(CAPTURE_V1_PATH)
+ .header(header::ORIGIN, "https://example.com")
+ .header("Access-Control-Request-Method", "POST")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(resp.status(), StatusCode::OK);
+ assert_eq!(
+ resp.headers()
+ .get(header::ACCESS_CONTROL_ALLOW_ORIGIN)
+ .and_then(|v| v.to_str().ok()),
+ Some("https://example.com")
+ );
+ let methods = resp
+ .headers()
+ .get(header::ACCESS_CONTROL_ALLOW_METHODS)
+ .and_then(|v| v.to_str().ok())
+ .unwrap_or_default();
+ assert!(methods.contains("POST"));
+ assert!(!methods.contains("GET"), "v1 endpoints are POST-only");
+ }
+
+ #[tokio::test]
+ async fn get_method_not_allowed() {
+ let resp = app(default_cfg())
+ .oneshot(
+ Request::builder()
+ .method(Method::GET)
+ .uri(CAPTURE_V1_PATH)
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED);
+ }
+
+ #[tokio::test]
+ async fn cors_headers_on_error_responses() {
+ let resp = app(default_cfg())
+ .oneshot(
+ valid_request()
+ .header(header::ORIGIN, "https://example.com")
+ .body(Body::from("not json"))
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+
+ assert!(resp.status().is_client_error());
+ assert_eq!(
+ resp.headers()
+ .get(header::ACCESS_CONTROL_ALLOW_ORIGIN)
+ .and_then(|v| v.to_str().ok()),
+ Some("https://example.com")
+ );
+ }
+}
diff --git a/rust/capture/src/v1/test_utils.rs b/rust/capture/src/v1/test_utils.rs
index a363e9886b95..d62d811c8ae6 100644
--- a/rust/capture/src/v1/test_utils.rs
+++ b/rust/capture/src/v1/test_utils.rs
@@ -32,7 +32,7 @@ pub fn test_context() -> Context {
user_agent: "test-agent/1.0".to_string(),
content_type: "application/json".to_string(),
content_encoding: None,
- sdk_info: "posthog-rust/1.0.0".to_string(),
+ sdk_info: "posthog-rs/1.0.0".to_string(),
attempt: 1,
request_id: Uuid::new_v4(),
client_timestamp: Utc::now(),
diff --git a/rust/capture/src/v1/util.rs b/rust/capture/src/v1/util.rs
index 384672294b6e..a8ece0ee0d10 100644
--- a/rust/capture/src/v1/util.rs
+++ b/rust/capture/src/v1/util.rs
@@ -48,6 +48,14 @@ pub async fn extract_body_with_timeout(
buf.put(chunk);
}
Some(Err(e)) => {
+ // A body wrapped by axum's DefaultBodyLimit surfaces over-limit
+ // reads as a LengthLimitError in the stream; report those as 413
+ // rather than a generic decoding failure.
+ if error_chain_has_length_limit(&e) {
+ return Err(Error::PayloadTooLarge(format!(
+ "Request body exceeds limit of {payload_size_limit} bytes"
+ )));
+ }
return Err(Error::RequestDecodingError(format!(
"Error reading request body: {e:#}"
)));
@@ -63,6 +71,17 @@ pub async fn extract_body_with_timeout(
Ok(bytes)
}
+fn error_chain_has_length_limit(err: &axum::Error) -> bool {
+ let mut source = std::error::Error::source(err);
+ while let Some(e) = source {
+ if e.is::<http_body_util::LengthLimitError>() {
+ return true;
+ }
+ source = e.source();
+ }
+ false
+}
+
/// Decompress a payload using the specified Content-Encoding.
///
/// Returns bytes unchanged when `content_encoding` is `None`. For recognized
@@ -200,6 +219,17 @@ mod tests {
assert!(matches!(result, Err(Error::BodyReadTimeout(_))));
}
+ #[tokio::test]
+ async fn extract_body_length_limited_maps_to_payload_too_large() {
+ let inner = Body::from(vec![b'x'; 1024]);
+ let limited = http_body_util::Limited::new(inner, 128);
+ let body = Body::new(limited);
+ // Manual limit (4096) is larger than the Limited wrapper's, so only the
+ // wrapped body's LengthLimitError can trigger the failure.
+ let result = extract_body_with_timeout(body, 4096, None, TEST_CHUNK_SIZE_KB, "/test").await;
+ assert!(matches!(result, Err(Error::PayloadTooLarge(_))));
+ }
+
#[tokio::test]
async fn extract_body_empty() {
let body = Body::empty();
diff --git a/rust/capture/tests/common/integration_utils.rs b/rust/capture/tests/common/integration_utils.rs
index 460cdb64e884..4a5a1b8ea219 100644
--- a/rust/capture/tests/common/integration_utils.rs
+++ b/rust/capture/tests/common/integration_utils.rs
@@ -1102,7 +1102,6 @@ fn setup_capture_router(unit: &TestCase) -> (Router, MemorySink) {
verbose_sample_percent,
26_214_400, // 25MB default for AI endpoint
None, // ai_blob_storage
- Some(10), // request_timeout_seconds
None, // body_chunk_read_timeout_ms
256, // body_read_chunk_size_kb
10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
diff --git a/rust/capture/tests/common/utils.rs b/rust/capture/tests/common/utils.rs
index 18e73a80babc..1d341b348bcc 100644
--- a/rust/capture/tests/common/utils.rs
+++ b/rust/capture/tests/common/utils.rs
@@ -149,7 +149,6 @@ pub static DEFAULT_CONFIG: Lazy<Config> = Lazy::new(|| Config {
ai_s3_region: "us-east-1".to_string(),
ai_s3_access_key_id: None,
ai_s3_secret_access_key: None,
- request_timeout_seconds: Some(10),
http1_header_read_timeout_ms: Some(5000), // 5 seconds default
body_chunk_read_timeout_ms: None, // disabled by default in tests
body_read_chunk_size_kb: 256, // 256KB default
@@ -292,7 +291,7 @@ impl ServerHandle {
self.client
.post(format!("http://{:?}/i/v1/analytics/events", self.addr))
.header("authorization", format!("Bearer {token}"))
- .header("PostHog-Sdk-Info", "posthog-rust/1.0.0")
+ .header("PostHog-Sdk-Info", "posthog-rs/1.0.0")
.header("PostHog-Attempt", "1")
.header("PostHog-Request-Id", uuid::Uuid::new_v4().to_string())
.header("PostHog-Request-Timestamp", "2026-03-19T14:30:00.000Z")
diff --git a/rust/capture/tests/integration_ai_endpoint.rs b/rust/capture/tests/integration_ai_endpoint.rs
index ec6549f389db..db2bea9861b5 100644
--- a/rust/capture/tests/integration_ai_endpoint.rs
+++ b/rust/capture/tests/integration_ai_endpoint.rs
@@ -188,7 +188,6 @@ fn setup_ai_test_router() -> Router {
0.0_f32,
26_214_400, // 25MB default for AI endpoint
Some(create_mock_blob_storage()), // ai_blob_storage
- Some(10), // request_timeout_seconds
None, // body_chunk_read_timeout_ms
256, // body_read_chunk_size_kb
10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
@@ -1650,7 +1649,6 @@ fn setup_ai_test_router_with_capturing_sink() -> (Router, CapturingSink) {
0.0_f32,
26_214_400, // 25MB default for AI endpoint
Some(create_mock_blob_storage()), // ai_blob_storage
- Some(10), // request_timeout_seconds
None, // body_chunk_read_timeout_ms
256, // body_read_chunk_size_kb
10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
@@ -2564,7 +2562,6 @@ fn setup_ai_test_router_with_token_dropper(token_dropper: TokenDropper) -> (Rout
0.0, // verbose_sample_percent
26_214_400, // ai_max_sum_of_parts_bytes
Some(create_mock_blob_storage()), // ai_blob_storage
- Some(10), // request_timeout_seconds
None, // body_chunk_read_timeout_ms
256, // body_read_chunk_size_kb
10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
@@ -2773,7 +2770,6 @@ fn setup_ai_test_router_with_llm_quota_limited(token: &str) -> (Router, Capturin
0.0_f32,
26_214_400,
Some(create_mock_blob_storage()), // ai_blob_storage
- Some(10), // request_timeout_seconds
None, // body_chunk_read_timeout_ms
256, // body_read_chunk_size_kb
10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
@@ -2927,7 +2923,6 @@ fn setup_ai_test_router_with_overflow_limiter(
0.0_f32,
26_214_400,
Some(create_mock_blob_storage()),
- Some(10),
None,
256,
10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
diff --git a/rust/capture/tests/integration_ai_restrictions.rs b/rust/capture/tests/integration_ai_restrictions.rs
index bbad40dfd575..af70dbf638f6 100644
--- a/rust/capture/tests/integration_ai_restrictions.rs
+++ b/rust/capture/tests/integration_ai_restrictions.rs
@@ -186,7 +186,6 @@ async fn setup_ai_router_with_restriction(
0.0_f32,
26_214_400,
Some(create_mock_blob_storage()),
- Some(10),
None,
256, // body_read_chunk_size_kb
10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
@@ -504,7 +503,6 @@ async fn setup_ai_router_with_redirect_to_topic(
0.0_f32,
26_214_400,
Some(create_mock_blob_storage()),
- Some(10),
None,
256, // body_read_chunk_size_kb
10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
@@ -579,7 +577,6 @@ async fn setup_ai_router_with_force_overflow_and_limiter(
0.0_f32,
26_214_400,
Some(create_mock_blob_storage()),
- Some(10),
None,
256,
10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
diff --git a/rust/capture/tests/integration_analytics_restrictions.rs b/rust/capture/tests/integration_analytics_restrictions.rs
index 5704a5297edf..640ca0f3f315 100644
--- a/rust/capture/tests/integration_analytics_restrictions.rs
+++ b/rust/capture/tests/integration_analytics_restrictions.rs
@@ -120,7 +120,6 @@ async fn setup_analytics_router_with_restriction(
0.0_f32,
26_214_400,
None, // no blob storage for analytics
- Some(10),
None,
256, // body_read_chunk_size_kb
10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
@@ -463,7 +462,6 @@ async fn setup_analytics_router_with_redirect_to_topic(
0.0_f32,
26_214_400,
None,
- Some(10),
None,
256, // body_read_chunk_size_kb
10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
diff --git a/rust/capture/tests/integration_otel_endpoint.rs b/rust/capture/tests/integration_otel_endpoint.rs
index 199b7e28a4bf..b3f822c3e8d4 100644
--- a/rust/capture/tests/integration_otel_endpoint.rs
+++ b/rust/capture/tests/integration_otel_endpoint.rs
@@ -178,7 +178,6 @@ fn make_test_client_with_options(sink: &CapturingSink, options: TestClientOption
"test-bucket".to_string(),
"llma/".to_string(),
))), // ai_blob_storage
- Some(10), // request_timeout_seconds
None, // body_chunk_read_timeout_ms
256, // body_read_chunk_size_kb
10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
diff --git a/rust/capture/tests/integration_replay_restrictions.rs b/rust/capture/tests/integration_replay_restrictions.rs
index 241355c02bc0..0c958401398a 100644
--- a/rust/capture/tests/integration_replay_restrictions.rs
+++ b/rust/capture/tests/integration_replay_restrictions.rs
@@ -122,7 +122,6 @@ async fn setup_recordings_router_with_restriction(
0.0_f32,
26_214_400,
None, // no blob storage for recordings
- Some(10),
None,
256, // body_read_chunk_size_kb
10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
@@ -491,7 +490,6 @@ async fn setup_recordings_router_with_redirect_to_topic(
0.0_f32,
26_214_400,
None, // no blob storage for recordings
- Some(10),
None,
256, // body_read_chunk_size_kb
10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
diff --git a/rust/capture/tests/quota_limiters.rs b/rust/capture/tests/quota_limiters.rs
index 48751360b3da..55e76c7e8f44 100644
--- a/rust/capture/tests/quota_limiters.rs
+++ b/rust/capture/tests/quota_limiters.rs
@@ -144,7 +144,6 @@ async fn setup_router_with_limits(
0.0, // verbose_sample_percent
26_214_400, // ai_max_sum_of_parts_bytes (25MB)
None, // ai_blob_storage
- Some(10), // request_timeout_seconds
None, // body_chunk_read_timeout_ms
256, // body_read_chunk_size_kb
10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
@@ -1195,7 +1194,6 @@ async fn test_survey_quota_cross_batch_first_submission_allowed() {
0.0,
26_214_400,
None, // ai_blob_storage
- Some(10), // request_timeout_seconds
None, // body_chunk_read_timeout_ms
256, // body_read_chunk_size_kb
10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
@@ -1284,7 +1282,6 @@ async fn test_survey_quota_cross_batch_duplicate_submission_dropped() {
0.0,
26_214_400,
None, // ai_blob_storage
- Some(10), // request_timeout_seconds
None, // body_chunk_read_timeout_ms
256, // body_read_chunk_size_kb
10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
@@ -1377,7 +1374,6 @@ async fn test_survey_quota_cross_batch_redis_error_fail_open() {
0.0,
26_214_400,
None, // ai_blob_storage
- Some(10), // request_timeout_seconds
None, // body_chunk_read_timeout_ms
256, // body_read_chunk_size_kb
10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes
@@ -1807,7 +1803,6 @@ async fn test_ai_quota_cross_batch_redis_error_fail_open() {
0.0,
26_214_400,
None, // ai_blob_storage
- Some(10), // request_timeout_seconds
None, // body_chunk_read_timeout_ms
256, // body_read_chunk_size_kb
10 * 1024 * 1024, // capture_v1_max_compressed_body_bytes