:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(capture-logs): charge decompressed bytes on remote-write ingestion (#88557)
Daniel Visca498d57a90eae
diff --git a/rust/capture-logs/src/endpoints/prometheus.rs b/rust/capture-logs/src/endpoints/prometheus.rsindex 3b54b0fe522e..6d8fb49f4fe4 100644--- a/rust/capture-logs/src/endpoints/prometheus.rs+++ b/rust/capture-logs/src/endpoints/prometheus.rs@@ -38,7 +38,8 @@ const ROW_OVERHEAD_BYTES: u64 = 256;/// below this; only expansion-bomb payloads exceed it.const MAX_EXPANSION_FACTOR: u64 = 16;-/// Decode a snappy-compressed Prometheus remote-write v1 payload.+/// Decode a snappy-compressed Prometheus remote-write v1 payload, returning the+/// request and its decompressed size in bytes.////// Prometheus sends `Content-Encoding: snappy` using the snappy *block* format/// (not the framed format), so we decode the raw body ourselves — the global@@ -47,7 +48,15 @@ const MAX_EXPANSION_FACTOR: u64 = 16;/// The block format's length header is sender-controlled, so the claimed/// decompressed size is checked against `max_decompressed_bytes` before any/// allocation happens.-pub fn decode_write_request(body: &[u8], max_decompressed_bytes: usize) -> Result<WriteRequest> {+///+/// The size is returned because this route bypasses `RequestDecompressionLayer`,+/// so the request body is still compressed when the handler sees it. The OTLP and+/// logs paths report a body that layer already decompressed, and all three feed+/// the same quota and rate-limiting counters, so the measure has to match.+pub fn decode_write_request(+ body: &[u8],+ max_decompressed_bytes: usize,+) -> Result<(WriteRequest, u64)> {let claimed =snap::raw::decompress_len(body).map_err(|e| anyhow!("snappy decode failed: {e}"))?;if claimed > max_decompressed_bytes {@@ -58,8 +67,10 @@ pub fn decode_write_request(body: &[u8], max_decompressed_bytes: usize) -> Resullet decompressed = snap::raw::Decoder::new().decompress_vec(body).map_err(|e| anyhow!("snappy decode failed: {e}"))?;- WriteRequest::decode(decompressed.as_slice())- .map_err(|e| anyhow!("remote-write protobuf decode failed: {e}"))+ let uncompressed_bytes = decompressed.len() as u64;+ let request = WriteRequest::decode(decompressed.as_slice())+ .map_err(|e| anyhow!("remote-write protobuf decode failed: {e}"))?;+ Ok((request, uncompressed_bytes))}/// Translate a decoded remote-write request into `KafkaMetricRow` records — the@@ -378,16 +389,17 @@ pub async fn export_prometheus_remote_write_http(tracing::Span::current().record("token", &token);- let write_request = match decode_write_request(&body, service.max_request_body_size_bytes) {- Ok(request) => request,- Err(e) => {- error!("Failed to decode remote-write request: {e}");- return Err((- StatusCode::BAD_REQUEST,- Json(json!({ "error": format!("{e}") })),- ));- }- };+ let (write_request, uncompressed_bytes) =+ match decode_write_request(&body, service.max_request_body_size_bytes) {+ Ok(decoded) => decoded,+ Err(e) => {+ error!("Failed to decode remote-write request: {e}");+ return Err((+ StatusCode::BAD_REQUEST,+ Json(json!({ "error": format!("{e}") })),+ ));+ }+ };// 400, not 5xx: a batch that expands past the limit will never fit, so the// sender must drop it rather than retry it forever.@@ -410,7 +422,7 @@ pub async fn export_prometheus_remote_write_http(if let Err(e) = service.sink- .write_metrics(&token, rows, body.len() as u64, timestamps_overridden)+ .write_metrics(&token, rows, uncompressed_bytes, timestamps_overridden).await{error!("Failed to send remote-write metrics to Kafka: {e}");diff --git a/rust/capture-logs/tests/prometheus_remote_write_test.rs b/rust/capture-logs/tests/prometheus_remote_write_test.rsindex 5460e00c7b29..249c8ae21f5f 100644--- a/rust/capture-logs/tests/prometheus_remote_write_test.rs+++ b/rust/capture-logs/tests/prometheus_remote_write_test.rs@@ -272,7 +272,7 @@ fn snappy_round_trip_decodes_and_maps() {req.encode(&mut encoded).unwrap();let compressed = snap::raw::Encoder::new().compress_vec(&encoded).unwrap();- let decoded =+ let (decoded, _) =decode_write_request(&compressed, MAX_DECOMPRESSED).expect("snappy+protobuf decode");let (rows, _) = write_request_to_kafka_rows(decoded);@@ -313,6 +313,41 @@ fn rejects_decompression_bomb_before_allocating() {assert!(decode_write_request(&compressed, encoded.len()).is_ok());}+/// Quota and rate limiting charge the payload size the handler reports. This+/// route bypasses `RequestDecompressionLayer`, so that size has to come from the+/// decoder: reporting the request body length charges the snappy-compressed+/// size, while the OTLP and logs paths charge the decompressed size.+#[test]+fn reports_decompressed_payload_size() {+ let req = WriteRequest {+ timeseries: vec![series(+ vec![label("__name__", "up"), label("job", "prometheus")],+ (0..200)+ .map(|i| Sample {+ value: 1.0,+ timestamp: now_ms() + i,+ })+ .collect(),+ )],+ metadata: vec![],+ };+ let mut encoded = Vec::new();+ req.encode(&mut encoded).unwrap();+ let compressed = snap::raw::Encoder::new().compress_vec(&encoded).unwrap();++ let (_, uncompressed_bytes) =+ decode_write_request(&compressed, MAX_DECOMPRESSED).expect("snappy+protobuf decode");++ assert_eq!(uncompressed_bytes, encoded.len() as u64);+ // Keeps the assertion above from passing vacuously: a payload that did not+ // compress would satisfy it whichever size the decoder reported.+ assert!(+ uncompressed_bytes > compressed.len() as u64,+ "fixture did not compress: {uncompressed_bytes} decompressed vs {} compressed",+ compressed.len()+ );+}+/// The prometheus route is deliberately kept off `RequestDecompressionLayer`, so/// a `Content-Encoding: snappy` request reaches the handler with the raw body to/// decode itself — proving the 415 problem is avoided.