diff --git a/crates/adapters/ingest/otlp/src/lib.rs b/crates/adapters/ingest/otlp/src/lib.rs index a29b1135e..4f4daa37f 100644 --- a/crates/adapters/ingest/otlp/src/lib.rs +++ b/crates/adapters/ingest/otlp/src/lib.rs @@ -176,6 +176,10 @@ impl Decoded { pub struct Decoder { decompressed: Vec, series: SeriesCache, + /// Each resource's labels and metric name (with its suffix) seen, as + /// bytes, by a number: a point's cache key is that number and its + /// encoded attributes, so a point copies and compares only those. + metric_ids: HashMap, u32>, builder: B, /// Where a point's cache key is built, kept between points. key_buffer: Vec, @@ -186,6 +190,7 @@ impl Decoder { Self { decompressed: Vec::new(), series: SeriesCache::new(), + metric_ids: HashMap::new(), builder, key_buffer: Vec::new(), } @@ -207,18 +212,24 @@ impl Decoder { let Self { decompressed, series, + metric_ids, builder, key_buffer, } = self; + let caches = Caches { + series, + metric_ids, + key_buffer, + }; let decoded = if gzip { gunzip(body, limits.max_decompressed_bytes, decompressed) - .and_then(|request| walk(request, series, builder, key_buffer, options, limits)) + .and_then(|request| walk(request, caches, builder, options, limits)) } else if body.len() > limits.max_decompressed_bytes { Err(OtlpError::DecompressedTooLarge( limits.max_decompressed_bytes, )) } else { - walk(body, series, builder, key_buffer, options, limits) + walk(body, caches, builder, options, limits) }; // An unusually large request's buffer is not kept, whether or not it // decoded, as the Remote Write decoder does. @@ -229,19 +240,27 @@ impl Decoder { } } +/// A decoder's series cache, its metric numbers and its key buffer +/// ([`Decoder`]), lent to a walk. +struct Caches<'a, S: Copy> { + series: &'a mut SeriesCache, + metric_ids: &'a mut HashMap, u32>, + key_buffer: &'a mut Vec, +} + /// The samples of the uncompressed request `request` ([`Decoder::decode`]). fn walk( request: &[u8], - series: &mut SeriesCache, + caches: Caches<'_, B::Series>, builder: &mut B, - key_buffer: &mut Vec, options: &LabelOptions, limits: &Limits, ) -> Result, OtlpError> { let mut walk = Walk { - series, + series: caches.series, + metric_ids: caches.metric_ids, builder, - key_buffer, + key_buffer: caches.key_buffer, options, max_points: limits.max_points, point_limit: limits.max_points, @@ -381,6 +400,7 @@ const TEMPORALITY_DELTA: u64 = 1; /// One request's walk. struct Walk<'a, B: SampleBuilder> { series: &'a mut SeriesCache, + metric_ids: &'a mut HashMap, u32>, builder: &'a mut B, key_buffer: &'a mut Vec, options: &'a LabelOptions, @@ -489,6 +509,15 @@ impl Walk<'_, B> { } temporality == TEMPORALITY_DELTA }; + // The number of each sample's metric (with its suffix), found once + // per metric, not per point. + let metric_ids = match kind { + PointKind::Number => [self.metric_id(resource, name, ""), 0], + _ => [ + self.metric_id(resource, name, "_sum"), + self.metric_id(resource, name, "_count"), + ], + }; let mut previous = None; let mut reader = Reader::new(data); while let Some((field, value)) = reader.field()? { @@ -498,12 +527,29 @@ impl Walk<'_, B> { if delta_sum { self.decoded.rejected_points += 1; } else { - self.point(resource, name, kind, point, &mut previous)?; + self.point(resource, name, kind, metric_ids, point, &mut previous)?; } } Ok(()) } + /// The number of `resource`'s labels with metric `name` and `suffix`, + /// given on first sight. + fn metric_id(&mut self, resource: &ResourceLabels, name: &str, suffix: &str) -> u32 { + let key = &mut *self.key_buffer; + key.clear(); + key.extend_from_slice(&resource.key_prefix); + key.extend_from_slice(&((name.len() + suffix.len()) as u32).to_le_bytes()); + key.extend_from_slice(name.as_bytes()); + key.extend_from_slice(suffix.as_bytes()); + if let Some(&id) = self.metric_ids.get(&key[..]) { + return id; + } + let id = u32::try_from(self.metric_ids.len()).expect("fewer than 2^32 metrics"); + self.metric_ids.insert(key[..].into(), id); + id + } + /// An encoded data point of `kind` of metric `name`. `previous` is the /// metric's point before it, whose series it takes when it has the same /// encoded attributes, as a series' consecutive points do. @@ -512,6 +558,7 @@ impl Walk<'_, B> { resource: &ResourceLabels, name: &str, kind: PointKind, + metric_ids: [u32; 2], point: &'p [u8], previous: &mut Option>, ) -> Result<(), OtlpError> { @@ -602,7 +649,10 @@ impl Walk<'_, B> { let series = match known { Some(series) => series, None => { - let Some(series) = self.series(resource, name, suffix, attributes)? else { + let metric_id = metric_ids[index]; + let Some(series) = + self.series(resource, name, suffix, metric_id, attributes)? + else { // A sketch payload point. return Ok(()); }; @@ -622,24 +672,24 @@ impl Walk<'_, B> { Ok(()) } - /// The series of a point of metric `name` (with `suffix`) and the - /// encoded `attributes` (`KeyValue` fields), from the cache or - /// translated and interned; `None` for a point that carries a sketch - /// payload. + /// The series of a point of metric `name` (with `suffix`, numbered + /// `metric_id` with `resource`: [`Self::metric_id`]) and the encoded + /// `attributes` (`KeyValue` fields), from the cache or translated and + /// interned; `None` for a point that carries a sketch payload. The + /// cache key is the metric number and the attributes' bytes; labels + /// are built only for a series not cached yet. #[inline] fn series( &mut self, resource: &ResourceLabels, name: &str, suffix: &str, + metric_id: u32, attributes: &[u8], ) -> Result, OtlpError> { let key = &mut *self.key_buffer; key.clear(); - key.extend_from_slice(&resource.key_prefix); - key.extend_from_slice(&((name.len() + suffix.len()) as u32).to_le_bytes()); - key.extend_from_slice(name.as_bytes()); - key.extend_from_slice(suffix.as_bytes()); + key.extend_from_slice(&metric_id.to_le_bytes()); key.extend_from_slice(attributes); if let Some(series) = self.series.get(key) { return Ok(Some(series)); diff --git a/crates/adapters/ingest/otlp/src/tests.rs b/crates/adapters/ingest/otlp/src/tests.rs index b9d41e7d1..08178f268 100644 --- a/crates/adapters/ingest/otlp/src/tests.rs +++ b/crates/adapters/ingest/otlp/src/tests.rs @@ -684,6 +684,65 @@ fn a_decoder_interns_each_series_once() { assert_eq!(decoder.builder.series.len(), 5); } +/// Points with the same encoded attributes are one series per resource +/// and metric: across requests, with the metrics in another order and +/// interleaved with other resources, the same attributes under the same +/// resource and metric take the same series, built once; under another +/// metric (a prefix of the name included) or resource, another series. +#[test] +fn equal_attributes_are_one_series_per_resource_and_metric() { + let points = |values: &[&str]| -> Vec { + values + .iter() + .map(|value| { + number_point( + vec![text("a", value)], + NANOS, + number_data_point::Value::AsDouble(1.0), + ) + }) + .collect() + }; + let request = |metrics: &[&str], jobs: &[&str]| { + let mut request = ExportMetricsServiceRequest::default(); + for job in jobs { + let one = request_with( + vec![text("service.name", job)], + metrics + .iter() + .map(|name| gauge(name, points(&["1", "2"]))) + .collect(), + ); + request.resource_metrics.extend(one.resource_metrics); + } + encode(&request) + }; + let mut decoder = Decoder::new(Labeled::default()); + let mut decode = |body: Vec| -> Vec { + let decoded = decoder + .decode(&body, None, &LabelOptions::default(), &LIMITS) + .unwrap(); + decoded + .samples + .iter() + .map(|(series, _, _)| decoder.builder.series[*series].clone()) + .collect() + }; + let first = decode(request(&["g", "gg"], &["x", "y"])); + // Every point is its own series: 2 resources x 2 metrics x 2 attributes. + let distinct: std::collections::BTreeSet<&Labels> = first.iter().collect(); + assert_eq!(distinct.len(), 8); + // Again, metrics and resources in another order: the same series, and + // no series built again. + let again = decode(request(&["gg", "g"], &["y", "x"])); + let mut expected = first.clone(); + expected.sort(); + let mut got = again.clone(); + got.sort(); + assert_eq!(got, expected); + assert_eq!(decoder.builder.series.len(), 8); +} + /// Attributes interleaved with a point's other fields decode as the same /// attributes written together. #[test] diff --git a/crates/data-plane/Cargo.toml b/crates/data-plane/Cargo.toml index 4d87444fa..cd98a1f0b 100644 --- a/crates/data-plane/Cargo.toml +++ b/crates/data-plane/Cargo.toml @@ -28,6 +28,9 @@ axum.workspace = true reqwest.workspace = true form_urlencoded = "1" +# OTLP bodies read frame by frame into a kept buffer. +http-body-util = "0.1" + [dev-dependencies] # Plans and IR the tests and the micro benchmarks build. asap-planner.workspace = true @@ -36,7 +39,6 @@ futures = "0.3" control_plane = { workspace = true, features = ["test-support"] } asap_sketchlib.workspace = true tower = { version = "0.5", features = ["util"] } -http-body-util = "0.1" # posix_fadvise in the tier and view-read benchmarks (cold reads). libc = "0.2" # Remote Write bodies built by hand, and the reference decoder's series diff --git a/crates/data-plane/src/lib.rs b/crates/data-plane/src/lib.rs index b658f083d..8cc2b2ad8 100644 --- a/crates/data-plane/src/lib.rs +++ b/crates/data-plane/src/lib.rs @@ -475,7 +475,7 @@ async fn write_victoriametrics(State(state): State>, body: Bytes) async fn write_otlp( State(state): State>, headers: HeaderMap, - body: Bytes, + body: axum::body::Body, ) -> Response { let header_text = |name| headers.get(name).and_then(|value| value.to_str().ok()); let encoding = otlp::Encoding::of_content_type(header_text(header::CONTENT_TYPE)); @@ -493,9 +493,17 @@ async fn write_otlp( "OTLP/JSON is not supported: send application/x-protobuf", ); } + let mut buffer = BodyBuffer::take(); + let length = header_text(header::CONTENT_LENGTH).and_then(|length| length.parse().ok()); + if let Err((status, message)) = buffer + .read(body, length, state.limits.max_compressed_bytes) + .await + { + return (status, message).into_response(); + } let timer = internal_metrics::Timer::start(); let decoded = match remote_write::decode_otlp_samples( - &body, + &buffer.bytes, header_text(header::CONTENT_ENCODING), &state.otlp_label_options, &state.limits, @@ -503,6 +511,7 @@ async fn write_otlp( Ok(decoded) => decoded, Err(error) => return failed(StatusCode::BAD_REQUEST, &error.to_string()), }; + drop(buffer); let metrics = state.engine.metrics(); metrics.otlp_decode.record(timer); let mut rejected_points = decoded.rejected_points; @@ -558,6 +567,81 @@ async fn write_otlp( ([(header::CONTENT_TYPE, encoding.content_type())], reply).into_response() } +/// A request body read into a buffer kept between requests: each body is +/// copied once into memory already resident, rather than collected into a +/// new allocation whose pages fault in on every request (about a tenth of +/// the OTLP threads' CPU at 100k samples/s). Dropping it returns the +/// buffer, unless it grew past what a decoder keeps. +struct BodyBuffer { + bytes: Vec, +} + +impl BodyBuffer { + /// The most buffers kept, about as many as requests in flight. + const KEPT: usize = 16; + + fn pool() -> &'static std::sync::Mutex>> { + static POOL: std::sync::Mutex>> = std::sync::Mutex::new(Vec::new()); + &POOL + } + + fn take() -> Self { + let bytes = Self::pool() + .lock() + .unwrap_or_else(|e| e.into_inner()) + .pop() + .unwrap_or_default(); + Self { bytes } + } + + /// Reads `body` (of `length` bytes, when the request says) into the + /// buffer: 413 past `max_bytes`, as the body limit of the other write + /// routes answers, and 400 when the body cannot be read. + async fn read( + &mut self, + mut body: axum::body::Body, + length: Option, + max_bytes: usize, + ) -> Result<(), (StatusCode, &'static str)> { + use http_body_util::BodyExt; + // The texts axum's body extractor answers with. + const TOO_LARGE: (StatusCode, &str) = ( + StatusCode::PAYLOAD_TOO_LARGE, + "Failed to buffer the request body: length limit exceeded", + ); + self.bytes.clear(); + if let Some(length) = length { + if length > max_bytes { + return Err(TOO_LARGE); + } + self.bytes.reserve(length); + } + while let Some(frame) = body.frame().await { + let frame = frame + .map_err(|_| (StatusCode::BAD_REQUEST, "Failed to buffer the request body"))?; + if let Ok(data) = frame.into_data() { + if self.bytes.len() + data.len() > max_bytes { + return Err(TOO_LARGE); + } + self.bytes.extend_from_slice(&data); + } + } + Ok(()) + } +} + +impl Drop for BodyBuffer { + fn drop(&mut self) { + if self.bytes.capacity() > prometheus_remote_write::KEPT_DECOMPRESSED_BYTES { + return; + } + let mut pool = Self::pool().lock().unwrap_or_else(|e| e.into_inner()); + if pool.len() < Self::KEPT { + pool.push(std::mem::take(&mut self.bytes)); + } + } +} + /// Hands decoded samples to the engine: `None` once it has them, or the /// status and reason refusing them when it is busy (503, which senders /// retry) or has stopped (500).