From 63d96da039def1e313fc616431a6958d01a960e4 Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:12:29 -0600 Subject: [PATCH 01/31] test(otel): let OTEL_BENCH_ITERS override the benchmark iterations Co-Authored-By: Claude Opus 5.5 --- src/otel.rs | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/src/otel.rs b/src/otel.rs index 9accb4622..1a44d45a9 100644 --- a/src/otel.rs +++ b/src/otel.rs @@ -38,10 +38,19 @@ pub(crate) mod bench { /// Runs `body` `iters` times, requiring identical output every time, and /// prints the rows, their digest and the nanoseconds spent per row. + /// + /// `OTEL_BENCH_ITERS=` overrides `iters`. Running a benchmark at two + /// iteration counts under `perf stat` and dividing the difference in + /// instructions by the difference in rows flattened removes the fixed cost + /// of building the request and taking the digests. pub fn run(name: &str, iters: usize, mut body: F) where F: FnMut() -> Vec, { + let iters = std::env::var("OTEL_BENCH_ITERS") + .ok() + .and_then(|iters| iters.parse().ok()) + .unwrap_or(iters); // Serialising the rows costs more than flattening them, so the digest is // taken before and after the timed loop, never inside it. let first = body(); @@ -69,7 +78,7 @@ pub(crate) mod bench { ); println!( "{name}: rows={rows} iters={iters} ns_per_row={:.1} bytes={} digest={:016x}", - elapsed.as_secs_f64() * 1e9 / (rows * iters) as f64, + elapsed.as_secs_f64() * 1e9 / (rows * iters.max(1)) as f64, expected.0, expected.1 ); From 301b0fc2b2572d56bc1ec5fa0245e96a61974c28 Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Mon, 23 Nov 2026 22:58:44 -0600 Subject: [PATCH 02/31] test(otel): measure the memory an OTLP request holds while its rows are built (red) Ports the measurements of the budget review as assertions, with a per-thread test allocator (moved out of strict.rs; a reallocation now counts the old and the new block at its peak). Each case must stay under one chunk of rows (2 x 16 MiB + 8 MiB), which no longer grows with the rows of the request: - the events, the links of one span and the data points of one gauge (131,072 / 65,536 / 131,072 empty children); - 1000 tiny resource attributes copied into 2000 rows; - a 10 MiB log body of JSON text, parsed before anything was charged; - 3,600 exemplars with distinct keys, whose column table holds 13M null cells; - maps sized by the raw count of attributes without a value. All fail on this commit; the following commits turn them green. Co-Authored-By: Claude Opus 5.5 --- src/lib.rs | 4 + src/otel.rs | 3 + src/otel/memory_tests.rs | 448 +++++++++++++++++++++++++++++++++++++++ src/test_alloc.rs | 108 ++++++++++ src/utils/json/strict.rs | 46 +--- 5 files changed, 564 insertions(+), 45 deletions(-) create mode 100644 src/otel/memory_tests.rs create mode 100644 src/test_alloc.rs diff --git a/src/lib.rs b/src/lib.rs index 25d723809..5ec167060 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -134,6 +134,10 @@ pub static INTRA_CLUSTER_CLIENT: Lazy = Lazy::new(|| { .expect("Construction of client shouldn't fail") }); +// Counts what a test thread allocates, see `test_alloc::measure` +#[cfg(test)] +pub(crate) mod test_alloc; + // Keep the native build contract covered without network or frontend tooling. #[cfg(test)] #[path = "../build_support/native_ui.rs"] diff --git a/src/otel.rs b/src/otel.rs index 1a44d45a9..94c8df581 100644 --- a/src/otel.rs +++ b/src/otel.rs @@ -21,6 +21,9 @@ pub mod metrics; pub mod otel_utils; pub mod traces; +#[cfg(test)] +mod memory_tests; + /// Shared driver for the release-profile micro-benchmarks. Each benchmark is an /// `#[ignore]`d test that never touches the `PARSEABLE` global, so it can be run /// with a test-name filter: diff --git a/src/otel/memory_tests.rs b/src/otel/memory_tests.rs new file mode 100644 index 000000000..4c1394ffd --- /dev/null +++ b/src/otel/memory_tests.rs @@ -0,0 +1,448 @@ +/* + * Parseable Server (C) 2022 - 2025 Parseable, Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + */ + +//! Memory one OTLP request makes the server hold while its rows are built and +//! handed to staging, measured with the test allocator (`test_alloc`, layout +//! bytes on the calling thread). The decoded request is built before the +//! measurement starts. Each test prints `MEMORY : ...` with its numbers. +//! None of them touches `PARSEABLE`, so they may be run with a name filter. + +use crate::test_alloc::{Allocated, measure}; +use crate::utils::json::flatten::{FlattenBudget, FlattenLimits, JsonFlattenError}; +use opentelemetry_proto::tonic::collector::logs::v1::ExportLogsServiceRequest; +use opentelemetry_proto::tonic::collector::metrics::v1::ExportMetricsServiceRequest; +use opentelemetry_proto::tonic::collector::trace::v1::ExportTraceServiceRequest; +use opentelemetry_proto::tonic::common::v1::{AnyValue, KeyValue, any_value}; +use opentelemetry_proto::tonic::logs::v1::{LogRecord, ResourceLogs, ScopeLogs}; +use opentelemetry_proto::tonic::metrics::v1::{ + Exemplar, Gauge, Metric, NumberDataPoint, ResourceMetrics, ScopeMetrics, metric, +}; +use opentelemetry_proto::tonic::resource::v1::Resource; +use opentelemetry_proto::tonic::trace::v1::span::{Event, Link}; +use opentelemetry_proto::tonic::trace::v1::{ResourceSpans, ScopeSpans, Span}; +use serde_json::Value; + +const MIB: usize = 1024 * 1024; + +/// What a request may make the server hold while its rows are built and staged: +/// one chunk of rows (whose real size stays within 2x of its estimate), the row +/// that filled it and the chunk's `Vec`. It does not grow with the rows of the +/// request. +const PEAK_BOUND: usize = 2 * 16 * MIB + 8 * MIB; + +fn mb(bytes: impl TryInto) -> f64 { + bytes.try_into().ok().unwrap() as f64 / MIB as f64 +} + +fn kv(key: impl Into, value: any_value::Value) -> KeyValue { + KeyValue { + key: key.into(), + value: Some(AnyValue { value: Some(value) }), + ..Default::default() + } +} + +/// Rows handed over, and the most rows a chunk held +#[derive(Debug, Default)] +struct Handed { + rows: usize, + largest_chunk: usize, +} + +/// Hands the rows of a request to a consumer that drops every chunk once it is +/// full, as staging does, and reports what that allocated +fn hand_over( + name: &str, + flatten: impl FnOnce(&mut dyn FnMut(Vec) -> Result<(), JsonFlattenError>) -> Result<(), E>, +) -> (Result, Allocated) { + let (result, allocated) = measure(|| { + let mut handed = Handed::default(); + let mut stage = |rows: Vec| { + handed.rows += rows.len(); + handed.largest_chunk = handed.largest_chunk.max(rows.len()); + Ok(()) + }; + flatten(&mut stage).map_err(|e| format!("{e:?}"))?; + Ok(handed) + }); + println!( + "MEMORY {name}: {:?}, peak {:.1} MiB, bound {:.0} MiB", + result, + mb(allocated.peak), + mb(PEAK_BOUND) + ); + (result, allocated) +} + +/// The flatteners build every row of a request before handing them over, so the +/// consumer gets them as one chunk +fn all_at_once( + rows: Vec, + stage: &mut dyn FnMut(Vec) -> Result<(), JsonFlattenError>, +) -> Result<(), JsonFlattenError> { + stage(rows) +} + +fn traces( + request: &ExportTraceServiceRequest, +) -> impl FnOnce( + &mut dyn FnMut(Vec) -> Result<(), JsonFlattenError>, +) -> Result<(), JsonFlattenError> ++ '_ { + move |stage| { + all_at_once( + crate::otel::traces::flatten_otel_traces_protobuf(request, "t"), + stage, + ) + } +} + +fn metrics( + request: &ExportMetricsServiceRequest, +) -> impl FnOnce( + &mut dyn FnMut(Vec) -> Result<(), JsonFlattenError>, +) -> Result<(), JsonFlattenError> ++ '_ { + move |stage| { + all_at_once( + crate::otel::metrics::flatten_otel_metrics_protobuf_with_options(request, "t", false), + stage, + ) + } +} + +fn logs<'a>( + request: &'a ExportLogsServiceRequest, + budget: &'a mut FlattenBudget, +) -> impl FnOnce( + &mut dyn FnMut(Vec) -> Result<(), JsonFlattenError>, +) -> Result<(), JsonFlattenError> ++ 'a { + move |stage| { + all_at_once( + crate::otel::logs::flatten_otel_protobuf(request, "t", budget)?, + stage, + ) + } +} + +fn one_span(span: Span) -> ExportTraceServiceRequest { + ExportTraceServiceRequest { + resource_spans: vec![ResourceSpans { + scope_spans: vec![ScopeSpans { + spans: vec![span], + ..Default::default() + }], + ..Default::default() + }], + } +} + +fn one_metric(metric: Metric) -> ExportMetricsServiceRequest { + ExportMetricsServiceRequest { + resource_metrics: vec![ResourceMetrics { + scope_metrics: vec![ScopeMetrics { + metrics: vec![metric], + ..Default::default() + }], + ..Default::default() + }], + } +} + +/// Review finding 1: every event row of a span was built before the first was +/// handed over. 131,072 empty events (256 KiB of protobuf) held about 600 MiB. +#[test] +fn events_of_one_span_are_handed_over_in_bounded_memory() { + let n = 1 << 17; + let request = one_span(Span { + start_time_unix_nano: 1, + end_time_unix_nano: 2, + events: vec![ + Event { + time_unix_nano: 1, + ..Default::default() + }; + n + ], + ..Default::default() + }); + let (result, allocated) = hand_over("events of one span", traces(&request)); + let handed = result.unwrap(); + assert_eq!(handed.rows, n); + assert!(handed.largest_chunk < n); + assert!(allocated.peak < PEAK_BOUND, "peak {} B", allocated.peak); +} + +/// Same for the links of one span +#[test] +fn links_of_one_span_are_handed_over_in_bounded_memory() { + let n = 1 << 16; + let request = one_span(Span { + start_time_unix_nano: 1, + end_time_unix_nano: 2, + links: vec![Link::default(); n], + ..Default::default() + }); + let (result, allocated) = hand_over("links of one span", traces(&request)); + assert_eq!(result.unwrap().rows, n); + assert!(allocated.peak < PEAK_BOUND, "peak {} B", allocated.peak); +} + +/// Same for the data points of one gauge +#[test] +fn data_points_of_one_metric_are_handed_over_in_bounded_memory() { + let n = 1 << 17; + let request = one_metric(Metric { + name: "g".into(), + data: Some(metric::Data::Gauge(Gauge { + data_points: vec![ + NumberDataPoint { + time_unix_nano: 1, + start_time_unix_nano: 1, + ..Default::default() + }; + n + ], + })), + ..Default::default() + }); + let (result, allocated) = hand_over("points of one gauge", metrics(&request)); + assert_eq!(result.unwrap().rows, n); + assert!(allocated.peak < PEAK_BOUND, "peak {} B", allocated.peak); +} + +/// 1000 tiny resource attributes copied into every row of 2000 records: a 13 KB +/// body whose rows held about 400 MiB at once (review finding 3) +#[test] +fn tiny_copied_fields_are_handed_over_in_bounded_memory() { + let attributes: Vec = (0..1000) + .map(|i| kv(format!("k{i:03}"), any_value::Value::IntValue(0))) + .collect(); + let rows = 2000; + let request = ExportLogsServiceRequest { + resource_logs: vec![ResourceLogs { + resource: Some(Resource { + attributes, + ..Default::default() + }), + scope_logs: vec![ScopeLogs { + log_records: (0..rows) + .map(|i| LogRecord { + time_unix_nano: 1_700_000_000_000_000_000 + i as u64, + observed_time_unix_nano: 1_700_000_000_000_000_000, + ..Default::default() + }) + .collect(), + ..Default::default() + }], + ..Default::default() + }], + }; + let mut budget = FlattenBudget::new(FlattenLimits::DEFAULT); + let (result, allocated) = hand_over("tiny copied fields", logs(&request, &mut budget)); + assert_eq!(result.unwrap().rows, rows); + assert!(allocated.peak < PEAK_BOUND, "peak {} B", allocated.peak); +} + +/// Review finding 7: a log body that is JSON text was parsed before anything was +/// charged. A 10 MiB body `{"a":[0,0,...]}` peaked at 586 MiB. +#[test] +fn json_text_log_body_is_not_parsed_into_unbounded_memory() { + let mut text = String::with_capacity(10 * MIB); + text.push_str(r#"{"a":["#); + while text.len() < 10 * MIB - 4096 { + text.push_str("0,"); + } + text.push_str("0]}"); + let body_len = text.len(); + let request = ExportLogsServiceRequest { + resource_logs: vec![ResourceLogs { + scope_logs: vec![ScopeLogs { + log_records: vec![LogRecord { + time_unix_nano: 1_700_000_000_000_000_000, + observed_time_unix_nano: 1_700_000_000_000_000_000, + body: Some(AnyValue { + value: Some(any_value::Value::StringValue(text)), + }), + ..Default::default() + }], + ..Default::default() + }], + ..Default::default() + }], + }; + let mut budget = FlattenBudget::new(FlattenLimits::DEFAULT); + let (result, allocated) = hand_over("10 MiB JSON text body", logs(&request, &mut budget)); + assert!(result.is_err(), "the body expands far beyond the limits"); + // The row holds copies of the body text, nothing parsed from it + assert!( + allocated.peak < PEAK_BOUND + 3 * body_len, + "peak {} B", + allocated.peak + ); +} + +/// Review finding 4: an array of objects with distinct keys becomes a column per +/// key with a cell for every object: 3,600 exemplars held 890 MiB once their row +/// was structurally flattened +#[test] +fn exemplar_column_tables_are_bounded() { + let exemplars: Vec = (0..3_600) + .map(|i| Exemplar { + filtered_attributes: vec![kv(format!("k{i}"), any_value::Value::IntValue(1))], + time_unix_nano: 1, + ..Default::default() + }) + .collect(); + let request = one_metric(Metric { + name: "g".into(), + data: Some(metric::Data::Gauge(Gauge { + data_points: vec![NumberDataPoint { + time_unix_nano: 1, + start_time_unix_nano: 1, + exemplars, + ..Default::default() + }], + })), + ..Default::default() + }); + let mut rows = + crate::otel::metrics::flatten_otel_metrics_protobuf_with_options(&request, "t", false); + let mut row = rows.pop().unwrap(); + let (result, allocated) = + measure(|| crate::utils::json::flatten::flatten(&mut row, "_", None, None, None, false)); + println!( + "MEMORY exemplar table: {:?}, peak {:.1} MiB", + result.as_ref().map_err(ToString::to_string), + mb(allocated.peak) + ); + assert!(result.is_err()); + assert!(allocated.peak < PEAK_BOUND, "peak {} B", allocated.peak); +} + +/// `count` attributes without a value: two bytes each on the wire, skipped when rows +/// are built +fn valueless(count: usize) -> Vec { + vec![KeyValue::default(); count] +} + +const VALUELESS: usize = 50_000; + +/// Maps sized by the raw attribute count of the request held room for every +/// attribute without a value: 50,000 of them (100 KB of protobuf) made a row map +/// reserve about 5.5 MB +#[test] +fn valueless_attributes_do_not_size_row_maps() { + let point = NumberDataPoint { + attributes: valueless(VALUELESS), + time_unix_nano: 1, + start_time_unix_nano: 1, + exemplars: vec![Exemplar { + filtered_attributes: valueless(VALUELESS), + time_unix_nano: 1, + ..Default::default() + }], + ..Default::default() + }; + let metric = |data| Metric { + name: "m".into(), + metadata: valueless(VALUELESS), + data: Some(data), + ..Default::default() + }; + for (name, metric) in [ + ( + "gauge point", + metric(metric::Data::Gauge(Gauge { + data_points: vec![point.clone()], + })), + ), + ( + "metric without points", + metric(metric::Data::Gauge(Gauge::default())), + ), + ] { + let (rows, allocated) = + measure(|| crate::otel::metrics::flatten_metrics_record(&metric, false)); + println!( + "MEMORY valueless attributes, {name}: {} rows, retained {} B, peak {} B", + rows.len(), + allocated.retained, + allocated.peak + ); + assert_eq!(rows.len(), 1); + assert!( + allocated.peak < 256 * 1024, + "{name}: peak {} B", + allocated.peak + ); + } +} + +/// Same for the maps built while a row is: event and link attributes, and the +/// entries of key-value lists and arrays +#[test] +fn valueless_attributes_do_not_size_temporary_maps() { + let list = |values: Vec| { + vec![kv( + "list", + any_value::Value::KvlistValue(opentelemetry_proto::tonic::common::v1::KeyValueList { + values, + }), + )] + }; + let array = vec![kv( + "array", + any_value::Value::ArrayValue(opentelemetry_proto::tonic::common::v1::ArrayValue { + values: vec![AnyValue::default(); VALUELESS], + }), + )]; + let span = Span { + start_time_unix_nano: 1, + end_time_unix_nano: 2, + attributes: [list(valueless(VALUELESS)), array].concat(), + events: vec![Event { + time_unix_nano: 1, + attributes: valueless(VALUELESS), + ..Default::default() + }], + links: vec![Link { + attributes: valueless(VALUELESS), + ..Default::default() + }], + ..Default::default() + }; + let request = one_span(span); + let (rows, allocated) = + measure(|| crate::otel::traces::flatten_otel_traces_protobuf(&request, "t")); + println!( + "MEMORY valueless attributes, span: {} rows, peak {} B", + rows.len(), + allocated.peak + ); + assert_eq!(rows.len(), 2); + // Converting an attribute clones its decoded value first: the 50,000 entries of + // the list and of the array, as decoded, are held once more + let clones = VALUELESS * (std::mem::size_of::() + std::mem::size_of::()); + assert!( + allocated.peak < clones + 256 * 1024, + "peak {} B, clones {clones} B", + allocated.peak + ); +} diff --git a/src/test_alloc.rs b/src/test_alloc.rs new file mode 100644 index 000000000..c7571a0d9 --- /dev/null +++ b/src/test_alloc.rs @@ -0,0 +1,108 @@ +/* + * Parseable Server (C) 2022 - 2025 Parseable, Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + */ + +//! The global allocator of the library's test binary. It forwards to the system +//! allocator and, on a thread that asked for it, counts the bytes that thread +//! allocates, so a test can assert how much memory a call needs instead of +//! inferring it. Other threads (other tests) are never counted. Sizes are +//! layout sizes, not what the system allocator rounds them up to, and a +//! reallocation counts the old and the new block together at its peak. + +use std::{ + alloc::{GlobalAlloc, Layout, System}, + cell::Cell, +}; + +#[derive(Debug, Clone, Copy)] +struct Counter { + live: isize, + peak: isize, +} + +std::thread_local! { + static COUNTER: Cell> = const { Cell::new(None) }; +} + +fn add(bytes: isize) { + let _ = COUNTER.try_with(|counter| { + if let Some(mut c) = counter.get() { + c.live += bytes; + c.peak = c.peak.max(c.live); + counter.set(Some(c)); + } + }); +} + +struct Tracking; + +unsafe impl GlobalAlloc for Tracking { + unsafe fn alloc(&self, layout: Layout) -> *mut u8 { + let ptr = unsafe { System.alloc(layout) }; + if !ptr.is_null() { + add(layout.size() as isize); + } + ptr + } + unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { + add(-(layout.size() as isize)); + unsafe { System.dealloc(ptr, layout) } + } + unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, size: usize) -> *mut u8 { + // A move holds the old and the new block at once, so the peak counts both + add(size as isize); + let result = unsafe { System.realloc(ptr, layout, size) }; + if result.is_null() { + add(-(size as isize)); + } else { + add(-(layout.size() as isize)); + } + result + } +} + +#[global_allocator] +static ALLOCATOR: Tracking = Tracking; + +/// What a call allocated on the calling thread +#[derive(Debug, Clone, Copy)] +pub struct Allocated { + /// Bytes still allocated when the call returned, its result included + pub retained: isize, + /// The most bytes the call held at once, above what was allocated before it + pub peak: usize, +} + +/// Runs `f` on this thread and reports what it allocated. Not reentrant. +pub fn measure(f: impl FnOnce() -> T) -> (T, Allocated) { + COUNTER.with(|c| c.set(Some(Counter { live: 0, peak: 0 }))); + let value = f(); + let counter = COUNTER.with(|c| c.replace(None)).expect("measuring"); + ( + value, + Allocated { + retained: counter.live, + peak: counter.peak.max(0) as usize, + }, + ) +} + +/// Bytes `f` still holds allocated when it returns, its result included +pub fn retained(f: impl FnOnce() -> T) -> (T, isize) { + let (value, allocated) = measure(f); + (value, allocated.retained) +} diff --git a/src/utils/json/strict.rs b/src/utils/json/strict.rs index 5851f925b..4232e67cb 100644 --- a/src/utils/json/strict.rs +++ b/src/utils/json/strict.rs @@ -438,51 +438,7 @@ mod tests { // serde_json::Map hides IndexMap's capacity. Compare retained allocation // bytes with the oracle as well as inspecting Vec capacities directly. - mod allocations { - use std::{ - alloc::{GlobalAlloc, Layout, System}, - cell::Cell, - }; - std::thread_local! { - static LIVE: Cell> = const { Cell::new(None) }; - } - struct Tracking; - fn add(bytes: isize) { - let _ = LIVE.try_with(|live| { - if let Some(n) = live.get() { - live.set(Some(n + bytes)); - } - }); - } - unsafe impl GlobalAlloc for Tracking { - unsafe fn alloc(&self, layout: Layout) -> *mut u8 { - let ptr = unsafe { System.alloc(layout) }; - if !ptr.is_null() { - add(layout.size() as isize); - } - ptr - } - unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { - add(-(layout.size() as isize)); - unsafe { System.dealloc(ptr, layout) } - } - unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, size: usize) -> *mut u8 { - let result = unsafe { System.realloc(ptr, layout, size) }; - if !result.is_null() { - add(size as isize - layout.size() as isize); - } - result - } - } - #[global_allocator] - static ALLOCATOR: Tracking = Tracking; - pub fn retained(f: impl FnOnce() -> T) -> (T, isize) { - LIVE.with(|n| n.set(Some(0))); - let value = f(); - let bytes = LIVE.with(|n| n.replace(None).unwrap()); - (value, bytes) - } - } + use crate::test_alloc as allocations; #[test] fn final_container_capacities_match_oracle() { From fb1d042c28e87d77c650c8172804e99d3f550b1a Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Mon, 23 Nov 2026 22:58:47 -0600 Subject: [PATCH 03/31] feat(otel): hand OTLP rows to a sink one at a time, collected in bounded chunks The flatteners built every row of a request (and every event, link and data point row of one span or metric) before handing any over. They now hand each row to a RowSink as soon as it is built; shared resource, scope, span and metric fields are still built once per parent, and rows are byte-identical (bench digests unchanged). The Vec-returning functions remain as wrappers. A Chunker collects rows into chunks of at most 8192 rows or 16 MiB of estimated row memory and passes each full chunk on before the next is built. row_bytes estimates Value memory (128 B per map entry, 72 B per Value, string capacities plus 16 B per heap block, and the null cells structural flattening adds for arrays of objects), not JSON length: allocated/estimated is 1.02 for realistic rows and 1.25 for rows of 1000 tiny fields. Co-Authored-By: Claude Opus 5.5 --- src/otel.rs | 26 ++ src/otel/logs.rs | 179 ++++---- src/otel/memory_tests.rs | 140 +++++- src/otel/metrics.rs | 946 +++++++++++++++++++++------------------ src/otel/sink.rs | 368 +++++++++++++++ src/otel/traces.rs | 386 ++++++++-------- 6 files changed, 1301 insertions(+), 744 deletions(-) create mode 100644 src/otel/sink.rs diff --git a/src/otel.rs b/src/otel.rs index 94c8df581..d2fb9424c 100644 --- a/src/otel.rs +++ b/src/otel.rs @@ -19,6 +19,7 @@ pub mod logs; pub mod metrics; pub mod otel_utils; +pub mod sink; pub mod traces; #[cfg(test)] @@ -37,6 +38,7 @@ mod memory_tests; /// the per-row wall time for `perf stat` to turn into instruction counts. #[cfg(test)] pub(crate) mod bench { + use crate::utils::json::flatten::JsonFlattenError; use std::time::Instant; /// Runs `body` `iters` times, requiring identical output every time, and @@ -107,6 +109,30 @@ pub(crate) mod bench { ); } + /// The rows `flatten` hands to a `Chunker` with the default limits, each + /// chunk appended to the result as it is passed on + pub fn chunked( + flatten: impl FnOnce( + &mut super::sink::Chunker< + &mut dyn FnMut(Vec) -> Result<(), JsonFlattenError>, + >, + ) -> Result<(), JsonFlattenError>, + ) -> Vec { + let mut rows = Vec::new(); + let mut stage = |chunk: Vec| { + rows.extend(chunk); + Ok(()) + }; + let mut chunker = super::sink::Chunker::new( + super::sink::CHUNK_LIMITS, + &mut stage as &mut dyn FnMut(Vec) -> Result<(), JsonFlattenError>, + ); + flatten(&mut chunker).expect("benchmark rows flatten"); + chunker.finish().expect("benchmark rows stage"); + drop(chunker); + rows + } + fn dump_dir() -> Option { std::env::var("OTEL_BENCH_DUMP").ok() } diff --git a/src/otel/logs.rs b/src/otel/logs.rs index ca3a98eb7..c9a129215 100644 --- a/src/otel/logs.rs +++ b/src/otel/logs.rs @@ -19,16 +19,19 @@ use super::otel_utils::attribute_capacity; use super::otel_utils::collect_json_from_values; use super::otel_utils::convert_epoch_nano_to_timestamp; use super::otel_utils::insert_attributes; +use super::sink::RowSink; use crate::metrics::increment_logs_collected_by_date; use crate::utils::json::flatten::{ FlattenBudget, FlattenCost, JsonFlattenError, expand_generic_flattening, flatten_pipeline_cost, string_json_len, }; use opentelemetry_proto::tonic::collector::logs::v1::ExportLogsServiceRequest; +use opentelemetry_proto::tonic::common::v1::InstrumentationScope; use opentelemetry_proto::tonic::logs::v1::LogRecord; use opentelemetry_proto::tonic::logs::v1::LogsData; -use opentelemetry_proto::tonic::logs::v1::ScopeLogs; +use opentelemetry_proto::tonic::logs::v1::ResourceLogs; use opentelemetry_proto::tonic::logs::v1::SeverityNumber; +use opentelemetry_proto::tonic::resource::v1::Resource; use serde_json::Map; use serde_json::Value; @@ -311,20 +314,14 @@ pub fn flatten_log_record( Ok(log_record_json) } -/// this function flattens the `ScopeLogs` object -/// and returns a `Vec` of `Map` of the flattened json -fn flatten_scope_log( - scope_log: &ScopeLogs, - budget: &mut FlattenBudget, -) -> Result>, JsonFlattenError> { - let mut vec_scope_log_json = Vec::with_capacity(scope_log.log_records.len()); - let mut scope_log_json = Map::with_capacity( - 5 + scope_log - .scope - .as_ref() - .map_or(0, |scope| attribute_capacity(&scope.attributes)), - ); - if let Some(scope) = &scope_log.scope { +/// Fields every row of one `ScopeLogs` gets, before the record's own fields +pub fn scope_log_fields( + scope: Option<&InstrumentationScope>, + schema_url: &str, +) -> Map { + let mut scope_log_json = + Map::with_capacity(5 + scope.map_or(0, |scope| attribute_capacity(&scope.attributes))); + if let Some(scope) = scope { scope_log_json.insert("scope_name".to_string(), Value::String(scope.name.clone())); scope_log_json.insert( "scope_version".to_string(), @@ -338,78 +335,84 @@ fn flatten_scope_log( } scope_log_json.insert( "scope_log_schema_url".to_string(), - Value::String(scope_log.schema_url.clone()), + Value::String(schema_url.to_string()), ); + scope_log_json +} - for log_record in &scope_log.log_records { - let log_record_json = flatten_log_record(log_record, budget)?; - let mut combined_json = scope_log_json.clone(); - combined_json.extend(log_record_json); - vec_scope_log_json.push(combined_json); +/// Fields every row of one `ResourceLogs` gets, after the record's own fields +pub fn resource_log_fields(resource: Option<&Resource>, schema_url: &str) -> Map { + let mut resource_log_json = Map::with_capacity( + 4 + resource.map_or(0, |resource| attribute_capacity(&resource.attributes)), + ); + if let Some(resource) = resource { + insert_attributes(&mut resource_log_json, &resource.attributes); + resource_log_json.insert( + "resource_dropped_attributes_count".to_string(), + Value::Number(resource.dropped_attributes_count.into()), + ); } - - Ok(vec_scope_log_json) + resource_log_json.insert( + "schema_url".to_string(), + Value::String(schema_url.to_string()), + ); + resource_log_json } -/// Common function to process resource logs and merge resource-level fields -fn process_resource_logs( - resource_logs: &[T], - get_resource: fn(&T) -> Option<&opentelemetry_proto::tonic::resource::v1::Resource>, - get_scope_logs: fn(&T) -> &[ScopeLogs], - get_schema_url: fn(&T) -> &str, - tenant_id: &str, +/// The row of one log record: the scope fields, the record's own fields over them, +/// then the resource fields over both +pub fn log_record_row( + log_record: &LogRecord, + scope_fields: &Map, + resource_fields: &Map, budget: &mut FlattenBudget, -) -> Result, JsonFlattenError> -where - T: std::fmt::Debug, -{ - let mut vec_otel_json = Vec::new(); - let mut logs_collected: u64 = 0; +) -> Result, JsonFlattenError> { + let log_record_json = flatten_log_record(log_record, budget)?; + let mut row = scope_fields.clone(); + row.extend(log_record_json); + row.extend(resource_fields.clone()); + Ok(row) +} +/// Hands the row of every log record of `resource_logs` to `sink`, one at a time. +/// The JSON bodies of every record are charged to `budget`, which all records of the +/// request share, before their rows are built. +pub fn flatten_logs_into( + resource_logs: &[ResourceLogs], + budget: &mut FlattenBudget, + sink: &mut S, +) -> Result<(), S::Error> { for resource_log in resource_logs { - let resource = get_resource(resource_log); - let mut resource_log_json = Map::with_capacity( - 4 + resource.map_or(0, |resource| attribute_capacity(&resource.attributes)), - ); - - // Process resource attributes if present - if let Some(resource) = resource { - insert_attributes(&mut resource_log_json, &resource.attributes); - resource_log_json.insert( - "resource_dropped_attributes_count".to_string(), - Value::Number(resource.dropped_attributes_count.into()), - ); - } - - let scope_logs = get_scope_logs(resource_log); - let mut vec_resource_logs_json = Vec::with_capacity( - scope_logs - .iter() - .map(|scope_log| scope_log.log_records.len()) - .sum(), - ); - - for scope_log in scope_logs { - vec_resource_logs_json.extend(flatten_scope_log(scope_log, budget)?); - logs_collected += scope_log.log_records.len() as u64; - } - - resource_log_json.insert( - "schema_url".to_string(), - Value::String(get_schema_url(resource_log).to_string()), - ); - - for mut resource_logs_json in vec_resource_logs_json { - resource_logs_json.extend(resource_log_json.clone()); - vec_otel_json.push(Value::Object(resource_logs_json)); + let resource_fields = + resource_log_fields(resource_log.resource.as_ref(), &resource_log.schema_url); + for scope_log in &resource_log.scope_logs { + let scope_fields = scope_log_fields(scope_log.scope.as_ref(), &scope_log.schema_url); + for log_record in &scope_log.log_records { + sink.row(log_record_row( + log_record, + &scope_fields, + &resource_fields, + budget, + )?)?; + sink.record_end(); + } } } + Ok(()) +} - // Only count the logs of a request that was converted in full +/// All rows of `resource_logs` at once. Counts the records for `tenant_id` once +/// every one was converted. Ingestion streams the rows instead, see `flatten_logs_into`. +fn collect_resource_logs( + resource_logs: &[ResourceLogs], + tenant_id: &str, + budget: &mut FlattenBudget, +) -> Result, JsonFlattenError> { + let mut rows = Vec::new(); + flatten_logs_into(resource_logs, budget, &mut rows)?; let date = chrono::Utc::now().date_naive().to_string(); - increment_logs_collected_by_date(logs_collected, &date, tenant_id); - - Ok(vec_otel_json) + increment_logs_collected_by_date(rows.len() as u64, &date, tenant_id); + Ok(rows) } /// Same as `flatten_otel_logs`, for the protobuf request @@ -418,14 +421,7 @@ pub fn flatten_otel_protobuf( tenant_id: &str, budget: &mut FlattenBudget, ) -> Result, JsonFlattenError> { - process_resource_logs( - &message.resource_logs, - |record| record.resource.as_ref(), - |record| &record.scope_logs, - |record| &record.schema_url, - tenant_id, - budget, - ) + collect_resource_logs(&message.resource_logs, tenant_id, budget) } /// this function performs the custom flattening of the otel logs @@ -438,14 +434,7 @@ pub fn flatten_otel_logs( tenant_id: &str, budget: &mut FlattenBudget, ) -> Result, JsonFlattenError> { - process_resource_logs( - &message.resource_logs, - |record| record.resource.as_ref(), - |record| &record.scope_logs, - |record| &record.schema_url, - tenant_id, - budget, - ) + collect_resource_logs(&message.resource_logs, tenant_id, budget) } #[cfg(test)] @@ -995,7 +984,6 @@ mod tests { // They never touch the PARSEABLE global: every timestamp is set, so the rows // are deterministic, and the flatten budget is built from FlattenLimits::DEFAULT. mod benches { - use super::super::flatten_otel_protobuf; use crate::otel::bench; use crate::utils::json::flatten::{FlattenBudget, FlattenLimits}; use opentelemetry_proto::tonic::collector::logs::v1::ExportLogsServiceRequest; @@ -1142,10 +1130,13 @@ mod tests { ExportLogsServiceRequest { resource_logs } } + /// What ingestion does with a decoded request before staging: the rows + /// handed over in chunks (collected here) fn flatten(request: &ExportLogsServiceRequest) -> Vec { let mut budget = FlattenBudget::new(FlattenLimits::DEFAULT); - flatten_otel_protobuf(request, "perfbench", &mut budget) - .expect("benchmark rows flatten") + bench::chunked(|chunker| { + super::super::flatten_logs_into(&request.resource_logs, &mut budget, chunker) + }) } #[test] diff --git a/src/otel/memory_tests.rs b/src/otel/memory_tests.rs index 4c1394ffd..a5de0976f 100644 --- a/src/otel/memory_tests.rs +++ b/src/otel/memory_tests.rs @@ -22,6 +22,7 @@ //! measurement starts. Each test prints `MEMORY : ...` with its numbers. //! None of them touches `PARSEABLE`, so they may be run with a name filter. +use crate::otel::sink::{CHUNK_LIMITS, Chunker, row_bytes}; use crate::test_alloc::{Allocated, measure}; use crate::utils::json::flatten::{FlattenBudget, FlattenLimits, JsonFlattenError}; use opentelemetry_proto::tonic::collector::logs::v1::ExportLogsServiceRequest; @@ -43,7 +44,7 @@ const MIB: usize = 1024 * 1024; /// one chunk of rows (whose real size stays within 2x of its estimate), the row /// that filled it and the chunk's `Vec`. It does not grow with the rows of the /// request. -const PEAK_BOUND: usize = 2 * 16 * MIB + 8 * MIB; +const PEAK_BOUND: usize = 2 * CHUNK_LIMITS.bytes + 8 * MIB; fn mb(bytes: impl TryInto) -> f64 { bytes.try_into().ok().unwrap() as f64 / MIB as f64 @@ -89,15 +90,6 @@ fn hand_over( (result, allocated) } -/// The flatteners build every row of a request before handing them over, so the -/// consumer gets them as one chunk -fn all_at_once( - rows: Vec, - stage: &mut dyn FnMut(Vec) -> Result<(), JsonFlattenError>, -) -> Result<(), JsonFlattenError> { - stage(rows) -} - fn traces( request: &ExportTraceServiceRequest, ) -> impl FnOnce( @@ -105,10 +97,9 @@ fn traces( ) -> Result<(), JsonFlattenError> + '_ { move |stage| { - all_at_once( - crate::otel::traces::flatten_otel_traces_protobuf(request, "t"), - stage, - ) + let mut chunker = Chunker::new(CHUNK_LIMITS, stage); + crate::otel::traces::flatten_traces_into(&request.resource_spans, &mut chunker)?; + chunker.finish() } } @@ -119,10 +110,9 @@ fn metrics( ) -> Result<(), JsonFlattenError> + '_ { move |stage| { - all_at_once( - crate::otel::metrics::flatten_otel_metrics_protobuf_with_options(request, "t", false), - stage, - ) + let mut chunker = Chunker::new(CHUNK_LIMITS, stage); + crate::otel::metrics::flatten_metrics_into(&request.resource_metrics, false, &mut chunker)?; + chunker.finish() } } @@ -134,10 +124,9 @@ fn logs<'a>( ) -> Result<(), JsonFlattenError> + 'a { move |stage| { - all_at_once( - crate::otel::logs::flatten_otel_protobuf(request, "t", budget)?, - stage, - ) + let mut chunker = Chunker::new(CHUNK_LIMITS, stage); + crate::otel::logs::flatten_logs_into(&request.resource_logs, budget, &mut chunker)?; + chunker.finish() } } @@ -429,8 +418,11 @@ fn valueless_attributes_do_not_size_temporary_maps() { ..Default::default() }; let request = one_span(span); - let (rows, allocated) = - measure(|| crate::otel::traces::flatten_otel_traces_protobuf(&request, "t")); + let (rows, allocated) = measure(|| { + let mut rows = Vec::new(); + crate::otel::traces::flatten_traces_into(&request.resource_spans, &mut rows).unwrap(); + rows + }); println!( "MEMORY valueless attributes, span: {} rows, peak {} B", rows.len(), @@ -446,3 +438,103 @@ fn valueless_attributes_do_not_size_temporary_maps() { allocated.peak ); } + +/// The chunk limit is an estimate of the memory rows hold (`row_bytes`); it must +/// track what they really allocate, for realistic rows and for rows of many tiny +/// fields alike (review finding 3: JSON length was 18.5x off) +#[test] +fn row_estimate_tracks_allocated_memory() { + use opentelemetry_proto::tonic::common::v1::InstrumentationScope; + + let realistic: Vec = [ + ("service.name", "checkout"), + ("service.namespace", "shop"), + ("service.instance.id", "checkout-7d9f8b6c4-x2x9q"), + ("k8s.namespace.name", "production"), + ("k8s.pod.name", "checkout-7d9f8b6c4-x2x9q"), + ("k8s.pod.uid", "6b1a3c1e-2f0e-4d5a-9a43-77b8c2d1e0f1"), + ("k8s.deployment.name", "checkout"), + ("k8s.node.name", "ip-10-0-12-34.ec2.internal"), + ("k8s.cluster.name", "prod-eu-west-1"), + ("host.name", "ip-10-0-12-34.ec2.internal"), + ("cloud.provider", "aws"), + ("cloud.region", "eu-west-1"), + ("container.name", "checkout"), + ("container.image.name", "registry.example.com/shop/checkout"), + ("container.image.tag", "1.42.3"), + ("telemetry.sdk.name", "opentelemetry"), + ("telemetry.sdk.language", "java"), + ("telemetry.sdk.version", "1.38.0"), + ] + .into_iter() + .map(|(k, v)| kv(k, any_value::Value::StringValue(v.into()))) + .collect(); + let tiny: Vec = (0..1000) + .map(|i| kv(format!("k{i:03}"), any_value::Value::IntValue(0))) + .collect(); + for (name, resource, record_attributes) in + [("realistic", realistic, 6), ("tiny fields", tiny, 0)] + { + let request = ExportLogsServiceRequest { + resource_logs: vec![ResourceLogs { + resource: Some(Resource { + attributes: resource, + ..Default::default() + }), + scope_logs: vec![ScopeLogs { + scope: Some(InstrumentationScope { + name: "io.opentelemetry.logback".into(), + version: "2.6.0".into(), + ..Default::default() + }), + log_records: (0..500u64) + .map(|i| LogRecord { + time_unix_nano: 1_700_000_000_000_000_000 + i, + observed_time_unix_nano: 1_700_000_000_000_000_000 + i, + severity_number: 9, + severity_text: "INFO".into(), + body: Some(AnyValue { + value: Some(any_value::Value::StringValue(format!( + "GET /api/v1/orders/{i} 200 in 12ms" + ))), + }), + attributes: (0..record_attributes) + .map(|a| { + kv(format!("attr.{a}"), any_value::Value::IntValue(i as i64)) + }) + .collect(), + trace_id: vec![7; 16], + span_id: vec![3; 8], + ..Default::default() + }) + .collect(), + ..Default::default() + }], + ..Default::default() + }], + }; + let (rows, allocated) = measure(|| { + let mut rows = Vec::new(); + crate::otel::logs::flatten_logs_into( + &request.resource_logs, + &mut FlattenBudget::new(FlattenLimits::DEFAULT), + &mut rows, + ) + .unwrap(); + rows + }); + let estimate: usize = rows + .iter() + .map(|row| row_bytes(row.as_object().unwrap())) + .sum(); + let ratio = allocated.retained as f64 / estimate as f64; + println!( + "MEMORY row estimate, {name}: {} rows, allocated {} B, estimated {} B, allocated/estimated {:.2}", + rows.len(), + allocated.retained, + estimate, + ratio, + ); + assert!((0.5..=2.0).contains(&ratio), "{name}: {ratio:.2}"); + } +} diff --git a/src/otel/metrics.rs b/src/otel/metrics.rs index b71a5d76f..10e675352 100644 --- a/src/otel/metrics.rs +++ b/src/otel/metrics.rs @@ -17,11 +17,14 @@ */ use once_cell::sync::Lazy; use opentelemetry_proto::tonic::collector::metrics::v1::ExportMetricsServiceRequest; +use opentelemetry_proto::tonic::common::v1::InstrumentationScope; use opentelemetry_proto::tonic::metrics::v1::number_data_point::Value as NumberDataPointValue; use opentelemetry_proto::tonic::metrics::v1::{ - Exemplar, ExponentialHistogram, Gauge, Histogram, Metric, MetricsData, NumberDataPoint, Sum, - Summary, exemplar::Value as ExemplarValue, exponential_histogram_data_point::Buckets, metric, + Exemplar, ExponentialHistogram, ExponentialHistogramDataPoint, Histogram, HistogramDataPoint, + Metric, MetricsData, NumberDataPoint, ResourceMetrics, Sum, SummaryDataPoint, + exemplar::Value as ExemplarValue, exponential_histogram_data_point::Buckets, metric, }; +use opentelemetry_proto::tonic::resource::v1::Resource; use serde_json::{Map, Value}; use rustc_hash::FxHasher; @@ -36,6 +39,7 @@ use crate::parseable::PARSEABLE; use super::otel_utils::{ convert_epoch_nano_to_timestamp, insert_attributes, insert_number_if_some, }; +use super::sink::RowSink; pub const SERIES_HASH_COLUMN: &str = "__series_hash_u64"; @@ -293,148 +297,128 @@ fn insert_exemplars(map: &mut Map, exemplars: &[Exemplar], flatte } } -/// otel metrics event has json array for number data points -/// this function flatten the number data points json array -/// and returns a `Vec` of `Map` of the flattened json -/// this function is reused in all json objects that have number data points -fn flatten_number_data_points( - data_points: &[NumberDataPoint], +/// The own fields of the row of one number data point (gauge or sum) +fn number_data_point_row( + data_point: &NumberDataPoint, flatten_exemplars: bool, -) -> Vec> { - data_points - .iter() - .map(|data_point| { - let mut data_point_json = Map::with_capacity(data_point.attributes.len() + 8); - insert_attributes(&mut data_point_json, &data_point.attributes); - data_point_json.insert( - "start_time_unix_nano".to_string(), - Value::String(convert_epoch_nano_to_timestamp( - data_point.start_time_unix_nano as i64, - )), - ); - data_point_json.insert( - "time_unix_nano".to_string(), - Value::String(convert_epoch_nano_to_timestamp( - data_point.time_unix_nano as i64, - )), - ); +) -> Map { + let mut data_point_json = Map::with_capacity(data_point.attributes.len() + 8); + insert_attributes(&mut data_point_json, &data_point.attributes); + data_point_json.insert( + "start_time_unix_nano".to_string(), + Value::String(convert_epoch_nano_to_timestamp( + data_point.start_time_unix_nano as i64, + )), + ); + data_point_json.insert( + "time_unix_nano".to_string(), + Value::String(convert_epoch_nano_to_timestamp( + data_point.time_unix_nano as i64, + )), + ); - insert_exemplars( - &mut data_point_json, - &data_point.exemplars, - flatten_exemplars, - ); + insert_exemplars( + &mut data_point_json, + &data_point.exemplars, + flatten_exemplars, + ); - insert_data_point_flags(&mut data_point_json, data_point.flags); - if let Some(value) = &data_point.value { - match value { - NumberDataPointValue::AsDouble(double_val) => { - data_point_json.insert( - "data_point_value".to_string(), - serde_json::Number::from_f64(*double_val) - .map(Value::Number) - .unwrap_or(Value::Null), - ); - } - NumberDataPointValue::AsInt(int_val) => { - data_point_json.insert( - "data_point_value".to_string(), - Value::Number(serde_json::Number::from(*int_val)), - ); - } - } + insert_data_point_flags(&mut data_point_json, data_point.flags); + if let Some(value) = &data_point.value { + match value { + NumberDataPointValue::AsDouble(double_val) => { + data_point_json.insert( + "data_point_value".to_string(), + serde_json::Number::from_f64(*double_val) + .map(Value::Number) + .unwrap_or(Value::Null), + ); } - data_point_json - }) - .collect() -} - -/// otel metrics event has json object for gauge -/// each gauge object has json array for data points -/// this function flatten the gauge json object -/// and returns a `Vec` of `Map` for each data point -fn flatten_gauge(gauge: &Gauge, flatten_exemplars: bool) -> Vec> { - flatten_number_data_points(&gauge.data_points, flatten_exemplars) + NumberDataPointValue::AsInt(int_val) => { + data_point_json.insert( + "data_point_value".to_string(), + Value::Number(serde_json::Number::from(*int_val)), + ); + } + } + } + data_point_json } -/// otel metrics event has json object for sum -/// each sum object has json array for data points -/// this function flatten the sum json object -/// and returns a `Vec` of `Map` for each data point -fn flatten_sum(sum: &Sum, flatten_exemplars: bool) -> Vec> { - let mut data_points = flatten_number_data_points(&sum.data_points, flatten_exemplars); - for dp in &mut data_points { - insert_aggregation_temporality(dp, sum.aggregation_temporality); - dp.insert("is_monotonic".to_string(), Value::Bool(sum.is_monotonic)); - } - data_points +/// The own fields of the row of one sum data point +fn sum_data_point_row( + sum: &Sum, + data_point: &NumberDataPoint, + flatten_exemplars: bool, +) -> Map { + let mut dp = number_data_point_row(data_point, flatten_exemplars); + insert_aggregation_temporality(&mut dp, sum.aggregation_temporality); + dp.insert("is_monotonic".to_string(), Value::Bool(sum.is_monotonic)); + dp } -/// otel metrics event has json object for histogram -/// each histogram object has json array for data points -/// this function flatten the histogram json object -/// and returns a `Vec` of `Map` for each data point -fn flatten_histogram(histogram: &Histogram, flatten_exemplars: bool) -> Vec> { - let mut data_points_json = Vec::with_capacity(histogram.data_points.len()); - for data_point in &histogram.data_points { - let mut data_point_json = Map::with_capacity(data_point.attributes.len() + 10); - insert_attributes(&mut data_point_json, &data_point.attributes); - data_point_json.insert( - "start_time_unix_nano".to_string(), - Value::String(convert_epoch_nano_to_timestamp( - data_point.start_time_unix_nano as i64, - )), - ); - data_point_json.insert( - "time_unix_nano".to_string(), - Value::String(convert_epoch_nano_to_timestamp( - data_point.time_unix_nano as i64, - )), - ); - data_point_json.insert( - "data_point_count".to_string(), - Value::Number(data_point.count.into()), - ); - insert_number_if_some(&mut data_point_json, "data_point_sum", &data_point.sum); - let data_point_bucket_counts = Value::Array( - data_point - .bucket_counts - .iter() - .map(|&count| Value::Number(count.into())) - .collect(), - ); - data_point_json.insert( - "data_point_bucket_counts".to_string(), - data_point_bucket_counts, - ); - let data_point_explicit_bounds = Value::Array( - data_point - .explicit_bounds - .iter() - .map(|bound| { - serde_json::Number::from_f64(*bound) - .map(Value::Number) - .unwrap_or(Value::Null) - }) - .collect(), - ); - data_point_json.insert( - "data_point_explicit_bounds".to_string(), - data_point_explicit_bounds, - ); - insert_exemplars( - &mut data_point_json, - &data_point.exemplars, - flatten_exemplars, - ); +/// The own fields of the row of one histogram data point +fn histogram_data_point_row( + histogram: &Histogram, + data_point: &HistogramDataPoint, + flatten_exemplars: bool, +) -> Map { + let mut data_point_json = Map::with_capacity(data_point.attributes.len() + 10); + insert_attributes(&mut data_point_json, &data_point.attributes); + data_point_json.insert( + "start_time_unix_nano".to_string(), + Value::String(convert_epoch_nano_to_timestamp( + data_point.start_time_unix_nano as i64, + )), + ); + data_point_json.insert( + "time_unix_nano".to_string(), + Value::String(convert_epoch_nano_to_timestamp( + data_point.time_unix_nano as i64, + )), + ); + data_point_json.insert( + "data_point_count".to_string(), + Value::Number(data_point.count.into()), + ); + insert_number_if_some(&mut data_point_json, "data_point_sum", &data_point.sum); + let data_point_bucket_counts = Value::Array( + data_point + .bucket_counts + .iter() + .map(|&count| Value::Number(count.into())) + .collect(), + ); + data_point_json.insert( + "data_point_bucket_counts".to_string(), + data_point_bucket_counts, + ); + let data_point_explicit_bounds = Value::Array( + data_point + .explicit_bounds + .iter() + .map(|bound| { + serde_json::Number::from_f64(*bound) + .map(Value::Number) + .unwrap_or(Value::Null) + }) + .collect(), + ); + data_point_json.insert( + "data_point_explicit_bounds".to_string(), + data_point_explicit_bounds, + ); + insert_exemplars( + &mut data_point_json, + &data_point.exemplars, + flatten_exemplars, + ); - insert_data_point_flags(&mut data_point_json, data_point.flags); - insert_number_if_some(&mut data_point_json, "data_point_min", &data_point.min); - insert_number_if_some(&mut data_point_json, "data_point_max", &data_point.max); - insert_aggregation_temporality(&mut data_point_json, histogram.aggregation_temporality); - data_points_json.push(data_point_json); - } - data_points_json + insert_data_point_flags(&mut data_point_json, data_point.flags); + insert_number_if_some(&mut data_point_json, "data_point_min", &data_point.min); + insert_number_if_some(&mut data_point_json, "data_point_max", &data_point.max); + insert_aggregation_temporality(&mut data_point_json, histogram.aggregation_temporality); + data_point_json } /// otel metrics event has json object for buckets @@ -456,238 +440,287 @@ fn flatten_buckets(bucket: &Buckets) -> Map { bucket_json } -/// otel metrics event has json object for exponential histogram -/// each exponential histogram object has json array for data points -/// this function flatten the exponential histogram json object -/// and returns a `Vec` of `Map` for each data point -fn flatten_exp_histogram( +/// The own fields of the row of one exponential histogram data point +fn exp_histogram_data_point_row( exp_histogram: &ExponentialHistogram, + data_point: &ExponentialHistogramDataPoint, flatten_exemplars: bool, -) -> Vec> { - let mut data_points_json = Vec::with_capacity(exp_histogram.data_points.len()); - for data_point in &exp_histogram.data_points { - let mut data_point_json = Map::with_capacity(data_point.attributes.len() + 12); - insert_attributes(&mut data_point_json, &data_point.attributes); - data_point_json.insert( - "start_time_unix_nano".to_string(), - Value::String(convert_epoch_nano_to_timestamp( - data_point.start_time_unix_nano as i64, - )), - ); - data_point_json.insert( - "time_unix_nano".to_string(), - Value::String(convert_epoch_nano_to_timestamp( - data_point.time_unix_nano as i64, - )), - ); - data_point_json.insert( - "data_point_count".to_string(), - Value::Number(data_point.count.into()), - ); - insert_number_if_some(&mut data_point_json, "data_point_sum", &data_point.sum); - data_point_json.insert( - "data_point_scale".to_string(), - Value::Number(data_point.scale.into()), - ); - data_point_json.insert( - "data_point_zero_count".to_string(), - Value::Number(data_point.zero_count.into()), - ); - if let Some(positive) = &data_point.positive { - let positive_json = flatten_buckets(positive); - for (key, value) in positive_json { - data_point_json.insert(format!("positive_{key}"), value); - } +) -> Map { + let mut data_point_json = Map::with_capacity(data_point.attributes.len() + 12); + insert_attributes(&mut data_point_json, &data_point.attributes); + data_point_json.insert( + "start_time_unix_nano".to_string(), + Value::String(convert_epoch_nano_to_timestamp( + data_point.start_time_unix_nano as i64, + )), + ); + data_point_json.insert( + "time_unix_nano".to_string(), + Value::String(convert_epoch_nano_to_timestamp( + data_point.time_unix_nano as i64, + )), + ); + data_point_json.insert( + "data_point_count".to_string(), + Value::Number(data_point.count.into()), + ); + insert_number_if_some(&mut data_point_json, "data_point_sum", &data_point.sum); + data_point_json.insert( + "data_point_scale".to_string(), + Value::Number(data_point.scale.into()), + ); + data_point_json.insert( + "data_point_zero_count".to_string(), + Value::Number(data_point.zero_count.into()), + ); + if let Some(positive) = &data_point.positive { + let positive_json = flatten_buckets(positive); + for (key, value) in positive_json { + data_point_json.insert(format!("positive_{key}"), value); } - if let Some(negative) = &data_point.negative { - let negative_json = flatten_buckets(negative); - for (key, value) in negative_json { - data_point_json.insert(format!("negative_{key}"), value); - } + } + if let Some(negative) = &data_point.negative { + let negative_json = flatten_buckets(negative); + for (key, value) in negative_json { + data_point_json.insert(format!("negative_{key}"), value); } - insert_exemplars( - &mut data_point_json, - &data_point.exemplars, - flatten_exemplars, - ); - - insert_aggregation_temporality(&mut data_point_json, exp_histogram.aggregation_temporality); - data_points_json.push(data_point_json); } - data_points_json + insert_exemplars( + &mut data_point_json, + &data_point.exemplars, + flatten_exemplars, + ); + + insert_aggregation_temporality(&mut data_point_json, exp_histogram.aggregation_temporality); + data_point_json } -/// otel metrics event has json object for summary -/// each summary object has json array for data points -/// this function flatten the summary json object -/// and returns a `Vec` of `Map` for each data point -fn flatten_summary(summary: &Summary) -> Vec> { - let mut data_points_json = Vec::with_capacity(summary.data_points.len()); - for data_point in &summary.data_points { - let mut data_point_json = Map::with_capacity(data_point.attributes.len() + 6); - insert_attributes(&mut data_point_json, &data_point.attributes); - data_point_json.insert( - "start_time_unix_nano".to_string(), - Value::String(convert_epoch_nano_to_timestamp( - data_point.start_time_unix_nano as i64, - )), - ); - data_point_json.insert( - "time_unix_nano".to_string(), - Value::String(convert_epoch_nano_to_timestamp( - data_point.time_unix_nano as i64, - )), - ); - data_point_json.insert( - "data_point_count".to_string(), - Value::Number(data_point.count.into()), - ); - data_point_json.insert( - "data_point_sum".to_string(), - serde_json::Number::from_f64(data_point.sum) - .map(Value::Number) - .unwrap_or(Value::Null), - ); - data_point_json.insert( - "data_point_quantile_values".to_string(), - Value::Array( - data_point - .quantile_values - .iter() - .map(|quantile_value| { - let mut quantile_map = Map::with_capacity(2); - quantile_map.insert( - "quantile".to_string(), - serde_json::Number::from_f64(quantile_value.quantile) - .map(Value::Number) - .unwrap_or(Value::Null), - ); - quantile_map.insert( - "value".to_string(), - serde_json::Number::from_f64(quantile_value.value) - .map(Value::Number) - .unwrap_or(Value::Null), - ); - Value::Object(quantile_map) - }) - .collect(), - ), - ); +/// The own fields of the row of one summary data point +fn summary_data_point_row(data_point: &SummaryDataPoint) -> Map { + let mut data_point_json = Map::with_capacity(data_point.attributes.len() + 6); + insert_attributes(&mut data_point_json, &data_point.attributes); + data_point_json.insert( + "start_time_unix_nano".to_string(), + Value::String(convert_epoch_nano_to_timestamp( + data_point.start_time_unix_nano as i64, + )), + ); + data_point_json.insert( + "time_unix_nano".to_string(), + Value::String(convert_epoch_nano_to_timestamp( + data_point.time_unix_nano as i64, + )), + ); + data_point_json.insert( + "data_point_count".to_string(), + Value::Number(data_point.count.into()), + ); + data_point_json.insert( + "data_point_sum".to_string(), + serde_json::Number::from_f64(data_point.sum) + .map(Value::Number) + .unwrap_or(Value::Null), + ); + data_point_json.insert( + "data_point_quantile_values".to_string(), + Value::Array( + data_point + .quantile_values + .iter() + .map(|quantile_value| { + let mut quantile_map = Map::with_capacity(2); + quantile_map.insert( + "quantile".to_string(), + serde_json::Number::from_f64(quantile_value.quantile) + .map(Value::Number) + .unwrap_or(Value::Null), + ); + quantile_map.insert( + "value".to_string(), + serde_json::Number::from_f64(quantile_value.value) + .map(Value::Number) + .unwrap_or(Value::Null), + ); + Value::Object(quantile_map) + }) + .collect(), + ), + ); + data_point_json +} + +/// One row of a metric, handed to the caller of `metric_rows` +pub enum MetricRow { + /// The row of one data point + Point(Map), + /// The one row of a metric that has data but no data points + NoPoints(Map), +} + +/// Fields every row of one metric gets, merged over the data point's own fields +struct MetricFields { + name: Value, + description: Value, + unit: Value, + metric_type: Value, + metadata: Map, +} - data_points_json.push(data_point_json); +impl MetricFields { + fn apply(&self, mut dp: Map) -> Map { + dp.insert("metric_name".to_string(), self.name.clone()); + dp.insert("metric_description".to_string(), self.description.clone()); + dp.insert("metric_unit".to_string(), self.unit.clone()); + dp.insert("metric_type".to_string(), self.metric_type.clone()); + for (k, v) in &self.metadata { + dp.insert(k.clone(), v.clone()); + } + dp } - data_points_json } -/// this function flattens the `Metric` object -/// each metric object has json object for gauge, sum, histogram, exponential histogram, summary -/// this function flatten the metric json object -/// and returns a `Vec` of `Map` of the flattened json -/// this function is called recursively for each metric record object in the otel metrics event -pub fn flatten_metrics_record( +/// Hands the rows of one metric to `emit` one at a time: one per data point, each +/// built once the one before it was handed over, or one for a metric that has data +/// but no data points. A metric without data has no rows. +pub fn metric_rows( metrics_record: &Metric, flatten_exemplars: bool, -) -> Vec> { - let (mut data_points, metric_type) = match &metrics_record.data { - Some(metric::Data::Gauge(gauge)) => (flatten_gauge(gauge, flatten_exemplars), "gauge"), - Some(metric::Data::Sum(sum)) => (flatten_sum(sum, flatten_exemplars), "sum"), - Some(metric::Data::Histogram(histogram)) => { - (flatten_histogram(histogram, flatten_exemplars), "histogram") - } - Some(metric::Data::ExponentialHistogram(exp_histogram)) => ( - flatten_exp_histogram(exp_histogram, flatten_exemplars), - "exponential_histogram", - ), - Some(metric::Data::Summary(summary)) => (flatten_summary(summary), "summary"), - None => return Vec::new(), + mut emit: impl FnMut(MetricRow) -> Result<(), E>, +) -> Result<(), E> { + let Some(data) = &metrics_record.data else { + return Ok(()); + }; + let metric_type = match data { + metric::Data::Gauge(_) => "gauge", + metric::Data::Sum(_) => "sum", + metric::Data::Histogram(_) => "histogram", + metric::Data::ExponentialHistogram(_) => "exponential_histogram", + metric::Data::Summary(_) => "summary", }; // Build metric-level fields once - let metric_name = Value::String(metrics_record.name.clone()); - let metric_desc = Value::String(metrics_record.description.clone()); - let metric_unit = Value::String(metrics_record.unit.clone()); - let metric_type_val = Value::String(metric_type.to_string()); let mut metadata = Map::with_capacity(metrics_record.metadata.len()); insert_attributes(&mut metadata, &metrics_record.metadata); + let fields = MetricFields { + name: Value::String(metrics_record.name.clone()), + description: Value::String(metrics_record.description.clone()), + unit: Value::String(metrics_record.unit.clone()), + metric_type: Value::String(metric_type.to_string()), + metadata, + }; + + let points = match data { + metric::Data::Gauge(gauge) => { + for dp in &gauge.data_points { + emit(MetricRow::Point( + fields.apply(number_data_point_row(dp, flatten_exemplars)), + ))?; + } + gauge.data_points.len() + } + metric::Data::Sum(sum) => { + for dp in &sum.data_points { + emit(MetricRow::Point(fields.apply(sum_data_point_row( + sum, + dp, + flatten_exemplars, + ))))?; + } + sum.data_points.len() + } + metric::Data::Histogram(histogram) => { + for dp in &histogram.data_points { + emit(MetricRow::Point(fields.apply(histogram_data_point_row( + histogram, + dp, + flatten_exemplars, + ))))?; + } + histogram.data_points.len() + } + metric::Data::ExponentialHistogram(exp_histogram) => { + for dp in &exp_histogram.data_points { + emit(MetricRow::Point(fields.apply( + exp_histogram_data_point_row(exp_histogram, dp, flatten_exemplars), + )))?; + } + exp_histogram.data_points.len() + } + metric::Data::Summary(summary) => { + for dp in &summary.data_points { + emit(MetricRow::Point(fields.apply(summary_data_point_row(dp))))?; + } + summary.data_points.len() + } + }; - if data_points.is_empty() { + if points == 0 { + let MetricFields { + name, + description, + unit, + metric_type, + metadata, + } = fields; let mut single = Map::with_capacity(metadata.len() + 8); - single.insert("metric_name".to_string(), metric_name); - single.insert("metric_description".to_string(), metric_desc); - single.insert("metric_unit".to_string(), metric_unit); - single.insert("metric_type".to_string(), metric_type_val); - match &metrics_record.data { - Some(metric::Data::Sum(sum)) => { + single.insert("metric_name".to_string(), name); + single.insert("metric_description".to_string(), description); + single.insert("metric_unit".to_string(), unit); + single.insert("metric_type".to_string(), metric_type); + match data { + metric::Data::Sum(sum) => { insert_aggregation_temporality(&mut single, sum.aggregation_temporality); single.insert("is_monotonic".to_string(), Value::Bool(sum.is_monotonic)); } - Some(metric::Data::Histogram(histogram)) => { + metric::Data::Histogram(histogram) => { insert_aggregation_temporality(&mut single, histogram.aggregation_temporality); } - Some(metric::Data::ExponentialHistogram(exp_histogram)) => { + metric::Data::ExponentialHistogram(exp_histogram) => { insert_aggregation_temporality(&mut single, exp_histogram.aggregation_temporality); } _ => {} } single.extend(metadata); - return vec![single]; - } - - // Insert metric-level fields directly into each data point - for dp in &mut data_points { - dp.insert("metric_name".to_string(), metric_name.clone()); - dp.insert("metric_description".to_string(), metric_desc.clone()); - dp.insert("metric_unit".to_string(), metric_unit.clone()); - dp.insert("metric_type".to_string(), metric_type_val.clone()); - for (k, v) in &metadata { - dp.insert(k.clone(), v.clone()); - } + emit(MetricRow::NoPoints(single))?; } - - data_points + Ok(()) } -fn metric_data_point_count(metric: &Metric) -> usize { - match &metric.data { - Some(metric::Data::Gauge(gauge)) => gauge.data_points.len(), - Some(metric::Data::Sum(sum)) => sum.data_points.len(), - Some(metric::Data::Histogram(histogram)) => histogram.data_points.len(), - Some(metric::Data::ExponentialHistogram(exp_histogram)) => exp_histogram.data_points.len(), - Some(metric::Data::Summary(summary)) => summary.data_points.len(), - None => 0, - } +/// this function flattens the `Metric` object +/// each metric object has json object for gauge, sum, histogram, exponential histogram, summary +/// this function flatten the metric json object +/// and returns a `Vec` of `Map` of the flattened json +pub fn flatten_metrics_record( + metrics_record: &Metric, + flatten_exemplars: bool, +) -> Vec> { + let mut rows = Vec::new(); + let Ok(()) = + metric_rows::(metrics_record, flatten_exemplars, |row| { + rows.push(match row { + MetricRow::Point(row) | MetricRow::NoPoints(row) => row, + }); + Ok(()) + }); + rows } -/// Common function to process resource metrics and merge resource-level fields -#[allow(clippy::too_many_arguments)] -fn process_resource_metrics( - resource_metrics: &[T], - get_resource: fn(&T) -> Option<&opentelemetry_proto::tonic::resource::v1::Resource>, - get_scope_metrics: fn(&T) -> &[S], - get_schema_url: fn(&T) -> &str, - get_scope: fn(&S) -> Option<&opentelemetry_proto::tonic::common::v1::InstrumentationScope>, - get_scope_schema_url: fn(&S) -> &str, - get_metrics: fn(&S) -> &[M], - get_metric: fn(&M) -> &Metric, - tenant_id: &str, - flatten_exemplars: bool, -) -> Vec { - let _span = info_span!( - "process_resource_metrics", - resource_count = resource_metrics.len(), - ) - .entered(); - let mut vec_otel_json = Vec::new(); +/// Fields every row of one `ResourceMetrics` gets, and its Prometheus target identity +pub struct ResourceMetricFields { + fields: Map, + target_identity: Option<(String, String)>, +} - for resource_metric in resource_metrics { +impl ResourceMetricFields { + pub fn new(resource: Option<&Resource>, schema_url: &str) -> Self { // Build resource-level fields once per resource let mut resource_fields = Map::with_capacity( - get_resource(resource_metric) + resource .map(|resource| resource.attributes.len()) .unwrap_or_default() + 2, ); - if let Some(resource) = get_resource(resource_metric) { + if let Some(resource) = resource { insert_attributes(&mut resource_fields, &resource.attributes); resource_fields.insert( "resource_dropped_attributes_count".to_string(), @@ -696,7 +729,7 @@ fn process_resource_metrics( } resource_fields.insert( "resource_schema_url".to_string(), - Value::String(get_schema_url(resource_metric).to_string()), + Value::String(schema_url.to_string()), ); // Prometheus uses these labels as the foreign key between every @@ -705,86 +738,154 @@ fn process_resource_metrics( if let Some(identity) = &target_identity { insert_prometheus_target_identity(&mut resource_fields, identity); } - let mut target_timestamp: Option = None; + Self { + fields: resource_fields, + target_identity, + } + } - for scope_metric in get_scope_metrics(resource_metric) { - // Build envelope = resource + scope fields (once per scope) - let mut envelope = resource_fields.clone(); + /// Envelope = resource + scope fields, merged over every row of the scope + pub fn scope_envelope( + &self, + scope: Option<&InstrumentationScope>, + scope_schema_url: &str, + ) -> Map { + let mut envelope = self.fields.clone(); - if let Some(scope) = get_scope(scope_metric) { - envelope.insert("scope_name".to_string(), Value::String(scope.name.clone())); - envelope.insert( - "scope_version".to_string(), - Value::String(scope.version.clone()), - ); - insert_attributes(&mut envelope, &scope.attributes); - envelope.insert( - "scope_dropped_attributes_count".to_string(), - Value::Number(scope.dropped_attributes_count.into()), - ); - } + if let Some(scope) = scope { + envelope.insert("scope_name".to_string(), Value::String(scope.name.clone())); envelope.insert( - "scope_schema_url".to_string(), - Value::String(get_scope_schema_url(scope_metric).to_string()), + "scope_version".to_string(), + Value::String(scope.version.clone()), ); - // Scope attributes are merged after resource attributes. Reapply - // the derived identity so they cannot shadow job or instance. - if let Some(identity) = &target_identity { - insert_prometheus_target_identity(&mut envelope, identity); - } - - let metrics = get_metrics(scope_metric); - vec_otel_json.reserve( - metrics - .iter() - .map(|metric| metric_data_point_count(get_metric(metric)).max(1)) - .sum::(), + insert_attributes(&mut envelope, &scope.attributes); + envelope.insert( + "scope_dropped_attributes_count".to_string(), + Value::Number(scope.dropped_attributes_count.into()), ); - let date = chrono::Utc::now().date_naive().to_string(); - increment_metrics_collected_by_date(metrics.len() as u64, &date, tenant_id); - - // Flatten each metric's data points and merge envelope in one pass - for metric in metrics { - let data_points = flatten_metrics_record(get_metric(metric), flatten_exemplars); - for mut dp in data_points { - if let Some(Value::String(timestamp)) = dp.get("time_unix_nano") - && target_timestamp - .as_ref() - .is_none_or(|latest| timestamp > latest) - { - target_timestamp = Some(timestamp.clone()); - } - for (k, v) in &envelope { - dp.insert(k.clone(), v.clone()); - } - // Compute the physical-series hash AFTER envelope merge - // so resource/scope attributes participate in series - // identity (they're labels from the query layer's - // perspective). Computed once per data point — O(label - // count) per sample, ~200 ns at typical attribute counts. - let series_hash = compute_series_hash(&dp); - dp.insert( - SERIES_HASH_COLUMN.to_string(), - Value::Number(series_hash.into()), - ); - vec_otel_json.push(Value::Object(dp)); - } - } } + envelope.insert( + "scope_schema_url".to_string(), + Value::String(scope_schema_url.to_string()), + ); + // Scope attributes are merged after resource attributes. Reapply + // the derived identity so they cannot shadow job or instance. + if let Some(identity) = &self.target_identity { + insert_prometheus_target_identity(&mut envelope, identity); + } + envelope + } + /// The `target_info` row of this resource, at the latest data point + /// timestamp of its rows, if it has a Prometheus target identity + pub fn target_info(&self, latest: Option) -> Option> { // Emit one target_info sample per OTel resource, using its latest data // point timestamp so current metadata joins remain available. - if target_identity.is_some() - && let Some(timestamp) = target_timestamp + if self.target_identity.is_some() + && let Some(timestamp) = latest + { + Some(target_info_record(&self.fields, timestamp)) + } else { + None + } + } +} + +/// Hands the rows of every metric of one scope to `sink`, tracking in `latest` the +/// latest `time_unix_nano` of the rows for the resource's `target_info` row +pub fn metric_rows_into( + metric: &Metric, + envelope: &Map, + flatten_exemplars: bool, + latest: &mut Option, + sink: &mut S, +) -> Result<(), S::Error> { + metric_rows(metric, flatten_exemplars, |row| { + let (mut dp, point) = match row { + MetricRow::Point(dp) => (dp, true), + MetricRow::NoPoints(dp) => (dp, false), + }; + if let Some(Value::String(timestamp)) = dp.get("time_unix_nano") + && latest.as_ref().is_none_or(|latest| timestamp > latest) { - vec_otel_json.push(Value::Object(target_info_record( - &resource_fields, - timestamp, - ))); + *latest = Some(timestamp.clone()); + } + for (k, v) in envelope { + dp.insert(k.clone(), v.clone()); + } + // Compute the physical-series hash AFTER envelope merge + // so resource/scope attributes participate in series + // identity (they're labels from the query layer's + // perspective). Computed once per data point — O(label + // count) per sample, ~200 ns at typical attribute counts. + let series_hash = compute_series_hash(&dp); + dp.insert( + SERIES_HASH_COLUMN.to_string(), + Value::Number(series_hash.into()), + ); + if point { sink.point(dp) } else { sink.row(dp) } + })?; + sink.record_end(); + Ok(()) +} + +/// Hands the rows of every metric of `resource_metrics` to `sink`, one at a time, +/// with one `target_info` row after the rows of each resource that has a +/// Prometheus target identity +pub fn flatten_metrics_into( + resource_metrics: &[ResourceMetrics], + flatten_exemplars: bool, + sink: &mut S, +) -> Result<(), S::Error> { + for resource_metric in resource_metrics { + let resource = ResourceMetricFields::new( + resource_metric.resource.as_ref(), + &resource_metric.schema_url, + ); + let mut target_timestamp: Option = None; + for scope_metric in &resource_metric.scope_metrics { + let envelope = + resource.scope_envelope(scope_metric.scope.as_ref(), &scope_metric.schema_url); + for metric in &scope_metric.metrics { + metric_rows_into( + metric, + &envelope, + flatten_exemplars, + &mut target_timestamp, + sink, + )?; + } + } + if let Some(target) = resource.target_info(target_timestamp) { + sink.row(target)?; } } + Ok(()) +} - vec_otel_json +/// All rows of `resource_metrics` at once, counting the metrics for `tenant_id`. +/// Ingestion streams the rows instead, see `flatten_metrics_into`. +fn process_resource_metrics( + resource_metrics: &[ResourceMetrics], + tenant_id: &str, + flatten_exemplars: bool, +) -> Vec { + let _span = info_span!( + "process_resource_metrics", + resource_count = resource_metrics.len(), + ) + .entered(); + let mut rows = Vec::new(); + flatten_metrics_into(resource_metrics, flatten_exemplars, &mut rows) + .expect("metric rows are never refused"); + let metrics: usize = resource_metrics + .iter() + .flat_map(|resource_metric| &resource_metric.scope_metrics) + .map(|scope_metric| scope_metric.metrics.len()) + .sum(); + let date = chrono::Utc::now().date_naive().to_string(); + increment_metrics_collected_by_date(metrics as u64, &date, tenant_id); + rows } /// this function performs the custom flattening of the otel metrics @@ -800,18 +901,7 @@ pub fn flatten_otel_metrics_with_options( tenant_id: &str, flatten_exemplars: bool, ) -> Vec { - process_resource_metrics( - &message.resource_metrics, - |record| record.resource.as_ref(), - |record| &record.scope_metrics, - |record| &record.schema_url, - |scope_metric| scope_metric.scope.as_ref(), - |scope_metric| &scope_metric.schema_url, - |scope_metric| &scope_metric.metrics, - |metric| metric, - tenant_id, - flatten_exemplars, - ) + process_resource_metrics(&message.resource_metrics, tenant_id, flatten_exemplars) } /// Flattens OpenTelemetry metrics from protobuf format @@ -839,18 +929,7 @@ pub fn flatten_otel_metrics_protobuf_with_options( ); let _guard = span.enter(); - let result = process_resource_metrics( - &message.resource_metrics, - |record| record.resource.as_ref(), - |record| &record.scope_metrics, - |record| &record.schema_url, - |scope_metric| scope_metric.scope.as_ref(), - |scope_metric| &scope_metric.schema_url, - |scope_metric| &scope_metric.metrics, - |metric| metric, - tenant_id, - flatten_exemplars, - ); + let result = process_resource_metrics(&message.resource_metrics, tenant_id, flatten_exemplars); span.record("output_count", result.len()); result @@ -892,6 +971,7 @@ mod tests { use opentelemetry_proto::tonic::common::v1::{ AnyValue, InstrumentationScope, KeyValue, any_value, }; + use opentelemetry_proto::tonic::metrics::v1::Gauge; use opentelemetry_proto::tonic::metrics::v1::{ResourceMetrics, ScopeMetrics}; use opentelemetry_proto::tonic::resource::v1::Resource; @@ -921,18 +1001,7 @@ mod tests { } fn flatten_for_test(message: &MetricsData) -> Vec { - process_resource_metrics( - &message.resource_metrics, - |record| record.resource.as_ref(), - |record| &record.scope_metrics, - |record| &record.schema_url, - |scope_metric| scope_metric.scope.as_ref(), - |scope_metric| &scope_metric.schema_url, - |scope_metric| &scope_metric.metrics, - |metric| metric, - "test-tenant", - false, - ) + process_resource_metrics(&message.resource_metrics, "test-tenant", false) } #[test] @@ -1500,7 +1569,7 @@ mod tests { }; use opentelemetry_proto::tonic::resource::v1::Resource; - use super::super::{compute_series_hash, process_resource_metrics}; + use super::super::compute_series_hash; const DATA_POINTS_PER_METRIC: usize = 10; const METRICS_PER_SCOPE: usize = 50; @@ -1633,19 +1702,12 @@ mod tests { ExportMetricsServiceRequest { resource_metrics } } + /// What ingestion does with a decoded request before staging: the rows + /// handed over in chunks (collected here) fn flatten(request: &ExportMetricsServiceRequest) -> Vec { - process_resource_metrics( - &request.resource_metrics, - |record| record.resource.as_ref(), - |record| &record.scope_metrics, - |record| &record.schema_url, - |scope_metric| scope_metric.scope.as_ref(), - |scope_metric| &scope_metric.schema_url, - |scope_metric| &scope_metric.metrics, - |metric| metric, - "perfbench", - false, - ) + bench::chunked(|chunker| { + super::super::flatten_metrics_into(&request.resource_metrics, false, chunker) + }) } #[test] diff --git a/src/otel/sink.rs b/src/otel/sink.rs new file mode 100644 index 000000000..6dcc30149 --- /dev/null +++ b/src/otel/sink.rs @@ -0,0 +1,368 @@ +/* + * Parseable Server (C) 2022 - 2025 Parseable, Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + */ + +//! Rows of an OTLP request, handed over one at a time. +//! +//! The flatteners build one row per log record, span event or link (or span), and +//! metric data point, and hand each to a [`RowSink`] as soon as it is built. A +//! [`Chunker`] collects them into chunks limited by rows and by an estimate of the +//! memory the rows hold ([`row_bytes`]), and passes every full chunk on before the +//! next is built. So the rows of a request are never all held at once. + +use std::collections::HashSet; +use std::mem::size_of; + +use serde_json::{Map, Value}; + +use crate::utils::json::flatten::JsonFlattenError; + +/// Receives the rows of one request, in order, as they are built +pub trait RowSink { + type Error: From; + + /// Takes one finished row + fn row(&mut self, row: Map) -> Result<(), Self::Error>; + + /// Takes one finished row that is one metric data point + fn point(&mut self, row: Map) -> Result<(), Self::Error> { + self.row(row) + } + + /// Every row of one leaf record (a log record, a span or a metric) was handed over + fn record_end(&mut self) {} +} + +/// Collects every row, for callers that want them all at once (tests, benchmarks) +impl RowSink for Vec { + type Error = JsonFlattenError; + + fn row(&mut self, row: Map) -> Result<(), Self::Error> { + self.push(Value::Object(row)); + Ok(()) + } +} + +/// `size_of::()`: every value in a map or array takes this much in place +pub const VALUE_BYTES: usize = size_of::(); + +/// One entry of a row map (`serde_json::Map` is an `IndexMap`): its bucket holds the +/// hash, the key `String` and the `Value` (104 B), the hash table one index and one +/// control byte, and both grow by doubling, so on average about a third more +/// capacity is held than used +pub const ENTRY_BYTES: usize = 128; + +/// What the system allocator adds to one heap block (header and rounding), counted +/// so that rows of many tiny strings are not underestimated +pub const HEAP_BLOCK_BYTES: usize = 16; + +/// Estimated bytes of the heap block of a string with this capacity +#[inline] +pub fn heap_bytes(capacity: usize) -> usize { + if capacity == 0 { + 0 + } else { + capacity + HEAP_BLOCK_BYTES + } +} + +/// Estimate of the memory one row holds, including the cells of the column tables +/// that structural flattening later builds from its arrays of objects (one `Value` +/// per distinct key and element, see `flatten_array_objects`). It tracks the real +/// `Value` memory, not the length of the row as JSON: a field `"a":0` is 6 bytes of +/// JSON and about 150 bytes of memory. +pub fn row_bytes(row: &Map) -> usize { + VALUE_BYTES + map_bytes(row) +} + +fn map_bytes(map: &Map) -> usize { + let mut bytes = 0; + for (key, value) in map { + bytes += ENTRY_BYTES + heap_bytes(key.capacity()) + value_heap_bytes(value); + } + bytes +} + +/// Heap bytes owned by `value` (its own `VALUE_BYTES` are counted by its container) +fn value_heap_bytes(value: &Value) -> usize { + match value { + Value::Null | Value::Bool(_) | Value::Number(_) => 0, + Value::String(s) => heap_bytes(s.capacity()), + Value::Object(map) => map_bytes(map), + Value::Array(values) => array_bytes(values), + } +} + +fn array_bytes(values: &Vec) -> usize { + let mut bytes = heap_bytes(values.capacity() * VALUE_BYTES); + let mut objects = false; + for value in values { + objects |= value.is_object(); + bytes += value_heap_bytes(value); + } + if objects { + // Structural flattening turns the elements into one column per distinct key, + // with a cell for every element + let keys: HashSet<&str> = values + .iter() + .filter_map(Value::as_object) + .flat_map(|object| object.keys().map(String::as_str)) + .collect(); + bytes += keys.len() * (ENTRY_BYTES + values.len() * VALUE_BYTES); + } + bytes +} + +/// Limits of one chunk of rows +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ChunkLimits { + /// Rows of one chunk + pub rows: usize, + /// Estimated memory of the rows of one chunk, see [`row_bytes`] + pub bytes: usize, +} + +/// Default chunk limits, see `REPORT.md` of the change that introduced them for the +/// measurements. A chunk is full at 8192 rows (the default batch size of the +/// OpenTelemetry collector) or 16 MiB of estimated row memory, whichever comes first. +/// Rows of realistic requests hold 1-10 KiB each, so the memory limit usually decides. +pub const CHUNK_LIMITS: ChunkLimits = ChunkLimits { + rows: 8192, + bytes: 16 * 1024 * 1024, +}; + +/// What a [`Chunker`] passed on +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct Staged { + /// Chunks passed on + pub chunks: u64, + /// Rows passed on + pub rows: u64, + /// Leaf records all of whose rows were passed on + pub records: u64, + /// Data point rows passed on + pub points: u64, +} + +/// Collects rows into chunks and passes every full chunk to `stage`, dropping it +/// before the next row is taken. Call [`Chunker::finish`] to pass on the rest. +pub struct Chunker { + limits: ChunkLimits, + stage: F, + rows: Vec, + bytes: usize, + /// Records and data points whose rows are all in `rows`, not yet passed on + pending_records: u64, + pending_points: u64, + staged: Staged, +} + +impl Chunker +where + F: FnMut(Vec) -> Result<(), E>, + E: From, +{ + pub fn new(limits: ChunkLimits, stage: F) -> Self { + Self { + limits, + stage, + rows: Vec::new(), + bytes: 0, + pending_records: 0, + pending_points: 0, + staged: Staged::default(), + } + } + + /// What was passed on so far + pub fn staged(&self) -> Staged { + self.staged + } + + fn flush(&mut self) -> Result<(), E> { + let rows = std::mem::take(&mut self.rows); + let count = rows.len() as u64; + self.bytes = 0; + (self.stage)(rows)?; + self.staged.chunks += 1; + self.staged.rows += count; + self.staged.records += std::mem::take(&mut self.pending_records); + self.staged.points += std::mem::take(&mut self.pending_points); + Ok(()) + } + + /// Passes on the rows taken since the last full chunk, if any + pub fn finish(&mut self) -> Result<(), E> { + if !self.rows.is_empty() { + self.flush()?; + } + Ok(()) + } +} + +impl RowSink for Chunker +where + F: FnMut(Vec) -> Result<(), E>, + E: From, +{ + type Error = E; + + fn row(&mut self, row: Map) -> Result<(), E> { + self.bytes += row_bytes(&row); + self.rows.push(Value::Object(row)); + if self.rows.len() >= self.limits.rows || self.bytes >= self.limits.bytes { + self.flush()?; + } + Ok(()) + } + + fn point(&mut self, row: Map) -> Result<(), E> { + // Counted with the chunk it is in, which `row` may already have passed on + let flushed_before = self.staged.chunks; + self.row(row)?; + if self.staged.chunks == flushed_before { + self.pending_points += 1; + } else { + self.staged.points += 1; + } + Ok(()) + } + + fn record_end(&mut self) { + if self.rows.is_empty() { + // Its last row (if it had any) filled a chunk that was passed on + self.staged.records += 1; + } else { + self.pending_records += 1; + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn object(value: Value) -> Map { + match value { + Value::Object(map) => map, + _ => unreachable!(), + } + } + + #[test] + fn value_is_72_bytes() { + assert_eq!(VALUE_BYTES, 72); + } + + #[test] + fn chunks_are_cut_by_rows_and_by_bytes() { + let mut chunks: Vec = Vec::new(); + let mut chunker = Chunker::new( + ChunkLimits { + rows: 3, + bytes: usize::MAX, + }, + |rows| { + chunks.push(rows.len()); + Ok::<_, JsonFlattenError>(()) + }, + ); + for i in 0..7 { + chunker.row(object(json!({ "i": i }))).unwrap(); + chunker.record_end(); + } + chunker.finish().unwrap(); + let staged = chunker.staged(); + drop(chunker); + assert_eq!(chunks, [3, 3, 1]); + assert_eq!(staged.rows, 7); + assert_eq!(staged.records, 7); + assert_eq!(staged.chunks, 3); + + let row = object(json!({ "a": "x" })); + let one = row_bytes(&row); + let mut chunks: Vec = Vec::new(); + let mut chunker = Chunker::new( + ChunkLimits { + rows: usize::MAX, + bytes: 2 * one, + }, + |rows| { + chunks.push(rows.len()); + Ok::<_, JsonFlattenError>(()) + }, + ); + for _ in 0..5 { + chunker.row(row.clone()).unwrap(); + } + chunker.finish().unwrap(); + drop(chunker); + assert_eq!(chunks, [2, 2, 1]); + } + + #[test] + fn a_record_counts_once_all_its_rows_are_passed_on() { + let mut fail_at = 2; + let mut chunker = Chunker::new( + ChunkLimits { + rows: 2, + bytes: usize::MAX, + }, + |_| { + fail_at -= 1; + if fail_at == 0 { + Err(JsonFlattenError::CannotFlatten) + } else { + Ok(()) + } + }, + ); + // Record 1: rows 1-3 (second chunk fails); record 0: row 0 + chunker.point(object(json!({ "r": 0 }))).unwrap(); + chunker.record_end(); + chunker.point(object(json!({ "r": 1 }))).unwrap(); + assert_eq!(chunker.staged().records, 1); + assert_eq!(chunker.staged().points, 2); + chunker.point(object(json!({ "r": 2 }))).unwrap(); + assert!(chunker.point(object(json!({ "r": 3 }))).is_err()); + assert_eq!(chunker.staged().records, 1); + assert_eq!(chunker.staged().points, 2); + assert_eq!(chunker.staged().rows, 2); + } + + #[test] + fn records_without_rows_count_when_finished() { + let mut chunker = Chunker::new(CHUNK_LIMITS, |_| Ok::<_, JsonFlattenError>(())); + chunker.record_end(); + chunker.finish().unwrap(); + let staged = chunker.staged(); + assert_eq!(staged.records, 1); + assert_eq!(staged.chunks, 0); + } + + #[test] + fn row_bytes_counts_the_column_table_of_arrays_of_objects() { + let objects: Vec = (0..100).map(|i| json!({ format!("k{i}"): 1 })).collect(); + let row = object(json!({ "exemplars": objects })); + // 100 distinct keys x 100 elements + assert!(row_bytes(&row) > 100 * 100 * VALUE_BYTES); + let same: Vec = (0..100).map(|_| json!({ "k": 1 })).collect(); + let row = object(json!({ "exemplars": same })); + assert!(row_bytes(&row) < 100 * 3 * ENTRY_BYTES); + } +} diff --git a/src/otel/traces.rs b/src/otel/traces.rs index b0c142081..588ab1271 100644 --- a/src/otel/traces.rs +++ b/src/otel/traces.rs @@ -16,8 +16,10 @@ * */ use opentelemetry_proto::tonic::collector::trace::v1::ExportTraceServiceRequest; +use opentelemetry_proto::tonic::common::v1::InstrumentationScope; use opentelemetry_proto::tonic::common::v1::KeyValue; -use opentelemetry_proto::tonic::trace::v1::ScopeSpans; +use opentelemetry_proto::tonic::resource::v1::Resource; +use opentelemetry_proto::tonic::trace::v1::ResourceSpans; use opentelemetry_proto::tonic::trace::v1::Span; use opentelemetry_proto::tonic::trace::v1::Status; use opentelemetry_proto::tonic::trace::v1::TracesData; @@ -31,6 +33,7 @@ use crate::otel::otel_utils::flatten_attributes; use super::otel_utils::attribute_capacity; use super::otel_utils::convert_epoch_nano_to_timestamp; use super::otel_utils::insert_attributes; +use super::sink::RowSink; pub const OTEL_TRACES_KNOWN_FIELD_LIST: [&str; 32] = [ "scope_name", @@ -66,108 +69,133 @@ pub const OTEL_TRACES_KNOWN_FIELD_LIST: [&str; 32] = [ "span_status_description", "span_status_message", ]; -/// this function flattens the `ScopeSpans` object -/// and returns a `Vec` of `Map` of the flattened json -fn flatten_scope_span(scope_span: &ScopeSpans, tenant_id: &str) -> Vec> { - let mut vec_scope_span_json = Vec::with_capacity(scope_span.spans.len()); - let mut scope_span_json = Map::with_capacity( - 5 + scope_span - .scope - .as_ref() - .map_or(0, |scope| attribute_capacity(&scope.attributes)), +/// Fields every row of one `ScopeSpans` gets from its scope, when it has one +pub fn scope_span_fields(scope: Option<&InstrumentationScope>) -> Map { + let Some(scope) = scope else { + return Map::new(); + }; + let mut scope_span_json = Map::with_capacity(5 + attribute_capacity(&scope.attributes)); + scope_span_json.insert("scope_name".to_string(), Value::String(scope.name.clone())); + scope_span_json.insert( + "scope_version".to_string(), + Value::String(scope.version.clone()), ); - for span in &scope_span.spans { - let span_record_json = flatten_span_record(span); - vec_scope_span_json.extend(span_record_json); - } - - let date = chrono::Utc::now().date_naive().to_string(); - increment_traces_collected_by_date(scope_span.spans.len() as u64, &date, tenant_id); + insert_attributes(&mut scope_span_json, &scope.attributes); + scope_span_json.insert( + "scope_dropped_attributes_count".to_string(), + Value::Number(scope.dropped_attributes_count.into()), + ); + scope_span_json +} - if let Some(scope) = &scope_span.scope { - scope_span_json.insert("scope_name".to_string(), Value::String(scope.name.clone())); - scope_span_json.insert( - "scope_version".to_string(), - Value::String(scope.version.clone()), - ); - insert_attributes(&mut scope_span_json, &scope.attributes); - scope_span_json.insert( - "scope_dropped_attributes_count".to_string(), - Value::Number(scope.dropped_attributes_count.into()), +/// Fields every row of one `ResourceSpans` gets, after all others +pub fn resource_span_fields(resource: Option<&Resource>, schema_url: &str) -> Map { + let mut resource_span_json = Map::with_capacity( + 4 + resource.map_or(0, |resource| attribute_capacity(&resource.attributes)), + ); + if let Some(resource) = resource { + insert_attributes(&mut resource_span_json, &resource.attributes); + resource_span_json.insert( + "resource_dropped_attributes_count".to_string(), + Value::Number(resource.dropped_attributes_count.into()), ); - - for span_json in &mut vec_scope_span_json { - for (key, value) in &scope_span_json { - span_json.insert(key.clone(), value.clone()); - } - } } + resource_span_json.insert( + "resource_schema_url".to_string(), + Value::String(schema_url.to_string()), + ); + resource_span_json +} - for span_json in &mut vec_scope_span_json { - span_json.insert( +/// The fields a span row gets from its scope and resource, in the order they are +/// merged over the span's own fields +pub struct SpanParents<'a> { + pub scope_fields: &'a Map, + pub scope_schema_url: &'a str, + pub resource_fields: &'a Map, +} + +impl SpanParents<'_> { + fn finish(&self, mut row: Map) -> Map { + for (key, value) in self.scope_fields { + row.insert(key.clone(), value.clone()); + } + row.insert( "scope_schema_url".to_string(), - Value::String(scope_span.schema_url.clone()), + Value::String(self.scope_schema_url.to_string()), ); + row.extend(self.resource_fields.clone()); + row } - - vec_scope_span_json } -/// Common function to process resource spans and merge resource-level fields -fn process_resource_spans( - resource_spans: &[T], - get_resource: fn(&T) -> Option<&opentelemetry_proto::tonic::resource::v1::Resource>, - get_scope_spans: fn(&T) -> &[ScopeSpans], - get_schema_url: fn(&T) -> &str, - tenant_id: &str, -) -> Vec -where - T: std::fmt::Debug, -{ - let mut vec_otel_json = Vec::new(); - - for resource_span in resource_spans { - let resource = get_resource(resource_span); - let mut resource_span_json = Map::with_capacity( - 4 + resource.map_or(0, |resource| attribute_capacity(&resource.attributes)), - ); - - // Process resource attributes if present - if let Some(resource) = resource { - insert_attributes(&mut resource_span_json, &resource.attributes); - resource_span_json.insert( - "resource_dropped_attributes_count".to_string(), - Value::Number(resource.dropped_attributes_count.into()), - ); +/// Hands the rows of one span to `sink`: one per event, then one per link, each with +/// the span's fields merged over it, or the span's own row when it has neither. Each +/// event or link row is built only once the one before it was handed over. +pub fn span_rows( + span: &Span, + parents: &SpanParents<'_>, + sink: &mut S, +) -> Result<(), S::Error> { + let span_record_json = flatten_span_fields(span); + if span.events.is_empty() && span.links.is_empty() { + sink.row(parents.finish(span_record_json))?; + } else { + for event in &span.events { + let mut row = event_row(event, span.start_time_unix_nano); + for (key, value) in &span_record_json { + row.insert(key.clone(), value.clone()); + } + sink.row(parents.finish(row))?; } - - // Process scope spans - let scope_spans = get_scope_spans(resource_span); - let mut vec_resource_spans_json = Vec::with_capacity( - scope_spans - .iter() - .map(|scope_span| scope_span.spans.len()) - .sum(), - ); - for scope_span in scope_spans { - let scope_span_json = flatten_scope_span(scope_span, tenant_id); - vec_resource_spans_json.extend(scope_span_json); + for link in &span.links { + let mut row = link_row(link); + for (key, value) in &span_record_json { + row.insert(key.clone(), value.clone()); + } + sink.row(parents.finish(row))?; } + } + sink.record_end(); + Ok(()) +} - // Add resource schema URL - resource_span_json.insert( - "resource_schema_url".to_string(), - Value::String(get_schema_url(resource_span).to_string()), - ); - - // Merge resource-level fields into each span record - for mut resource_spans_json in vec_resource_spans_json { - resource_spans_json.extend(resource_span_json.clone()); - vec_otel_json.push(Value::Object(resource_spans_json)); +/// Hands the rows of every span of `resource_spans` to `sink`, one at a time +pub fn flatten_traces_into( + resource_spans: &[ResourceSpans], + sink: &mut S, +) -> Result<(), S::Error> { + for resource_span in resource_spans { + let resource_fields = + resource_span_fields(resource_span.resource.as_ref(), &resource_span.schema_url); + for scope_span in &resource_span.scope_spans { + let scope_fields = scope_span_fields(scope_span.scope.as_ref()); + let parents = SpanParents { + scope_fields: &scope_fields, + scope_schema_url: &scope_span.schema_url, + resource_fields: &resource_fields, + }; + for span in &scope_span.spans { + span_rows(span, &parents, sink)?; + } } } + Ok(()) +} - vec_otel_json +/// All rows of `resource_spans` at once, counting the spans for `tenant_id`. +/// Ingestion streams the rows instead, see `flatten_traces_into`. +fn collect_resource_spans(resource_spans: &[ResourceSpans], tenant_id: &str) -> Vec { + let mut rows = Vec::new(); + flatten_traces_into(resource_spans, &mut rows).expect("span rows are never refused"); + let spans: usize = resource_spans + .iter() + .flat_map(|resource_span| &resource_span.scope_spans) + .map(|scope_span| scope_span.spans.len()) + .sum(); + let date = chrono::Utc::now().date_naive().to_string(); + increment_traces_collected_by_date(spans as u64, &date, tenant_id); + rows } /// Flattens OpenTelemetry traces from protobuf format @@ -175,92 +203,77 @@ pub fn flatten_otel_traces_protobuf( message: &ExportTraceServiceRequest, tenant_id: &str, ) -> Vec { - process_resource_spans( - &message.resource_spans, - |rs| rs.resource.as_ref(), - |rs| &rs.scope_spans, - |rs| &rs.schema_url, - tenant_id, - ) + collect_resource_spans(&message.resource_spans, tenant_id) } /// this function performs the custom flattening of the otel traces event /// and returns a `Vec` of `Value::Object` of the flattened json pub fn flatten_otel_traces(message: &TracesData, tenant_id: &str) -> Vec { - process_resource_spans( - &message.resource_spans, - |rs| rs.resource.as_ref(), - |rs| &rs.scope_spans, - |rs| &rs.schema_url, - tenant_id, - ) + collect_resource_spans(&message.resource_spans, tenant_id) } -/// otel traces has json array of events -/// this function flattens the `Event` object -/// and returns a `Vec` of `Map` of the flattened json +/// The own fields of the row of one span event +fn event_row(event: &Event, span_start_time_unix_nano: u64) -> Map { + let mut event_json = Map::with_capacity(6 + attribute_capacity(&event.attributes)); + event_json.insert( + "event_time_unix_nano".to_string(), + Value::String(convert_epoch_nano_to_timestamp(event.time_unix_nano as i64).to_string()), + ); + // add epoch value of event time in json + event_json.insert( + "event_time_unix_nano_epoch".to_string(), + Value::Number(serde_json::Number::from(event.time_unix_nano)), + ); + event_json.insert("event_name".to_string(), Value::String(event.name.clone())); + + // Calculate event duration in nanoseconds from span start + let duration_nanos = event + .time_unix_nano + .saturating_sub(span_start_time_unix_nano); + event_json.insert( + "event_duration_ns".to_string(), + Value::Number(serde_json::Number::from(duration_nanos)), + ); + + insert_events_attributes(&mut event_json, &event.attributes); + event_json.insert( + "event_dropped_attributes_count".to_string(), + Value::Number(event.dropped_attributes_count.into()), + ); + event_json +} + +/// The own fields of the row of one span link +fn link_row(link: &Link) -> Map { + let mut link_json = Map::with_capacity(5 + attribute_capacity(&link.attributes)); + link_json.insert( + "link_span_id".to_string(), + Value::String(hex::encode(&link.span_id)), + ); + link_json.insert( + "link_trace_id".to_string(), + Value::String(hex::encode(&link.trace_id)), + ); + + insert_links_attributes(&mut link_json, &link.attributes); + link_json.insert( + "link_dropped_attributes_count".to_string(), + Value::Number(link.dropped_attributes_count.into()), + ); + link_json +} + +#[cfg(test)] fn flatten_events(events: &[Event], span_start_time_unix_nano: u64) -> Vec> { events .iter() - .map(|event| { - let mut event_json = Map::with_capacity(6 + attribute_capacity(&event.attributes)); - event_json.insert( - "event_time_unix_nano".to_string(), - Value::String( - convert_epoch_nano_to_timestamp(event.time_unix_nano as i64).to_string(), - ), - ); - // add epoch value of event time in json - event_json.insert( - "event_time_unix_nano_epoch".to_string(), - Value::Number(serde_json::Number::from(event.time_unix_nano)), - ); - event_json.insert("event_name".to_string(), Value::String(event.name.clone())); - - // Calculate event duration in nanoseconds from span start - let duration_nanos = event - .time_unix_nano - .saturating_sub(span_start_time_unix_nano); - event_json.insert( - "event_duration_ns".to_string(), - Value::Number(serde_json::Number::from(duration_nanos)), - ); - - insert_events_attributes(&mut event_json, &event.attributes); - event_json.insert( - "event_dropped_attributes_count".to_string(), - Value::Number(event.dropped_attributes_count.into()), - ); - event_json - }) + .map(|event| event_row(event, span_start_time_unix_nano)) .collect() } -/// otel traces has json array of links -/// this function flattens the `Link` object -/// and returns a `Vec` of `Map` of the flattened json +#[cfg(test)] fn flatten_links(links: &[Link]) -> Vec> { - links - .iter() - .map(|link| { - let mut link_json = Map::with_capacity(5 + attribute_capacity(&link.attributes)); - link_json.insert( - "link_span_id".to_string(), - Value::String(hex::encode(&link.span_id)), - ); - link_json.insert( - "link_trace_id".to_string(), - Value::String(hex::encode(&link.trace_id)), - ); - - insert_links_attributes(&mut link_json, &link.attributes); - link_json.insert( - "link_dropped_attributes_count".to_string(), - Value::Number(link.dropped_attributes_count.into()), - ); - link_json - }) - .collect() + links.iter().map(link_row).collect() } /// otel trace event has status @@ -337,11 +350,8 @@ fn flatten_kind(kind: i32) -> Map { kind_json } -/// this function flattens the `Span` object -/// and returns a `Vec` of `Map` of the flattened json -/// this function is called recursively for each span record object in the otel traces event -fn flatten_span_record(span_record: &Span) -> Vec> { - let mut span_records_json = Vec::new(); +/// The fields of one span that every row of it gets +fn flatten_span_fields(span_record: &Span) -> Map { let mut span_record_json = Map::with_capacity(40 + attribute_capacity(&span_record.attributes)); span_record_json.insert( "span_trace_id".to_string(), @@ -402,14 +412,10 @@ fn flatten_span_record(span_record: &Span) -> Vec> { "span_dropped_attributes_count".to_string(), Value::Number(span_record.dropped_attributes_count.into()), ); - let events_json = flatten_events(&span_record.events, span_record.start_time_unix_nano); - span_records_json.extend(events_json); span_record_json.insert( "span_dropped_events_count".to_string(), Value::Number(span_record.dropped_events_count.into()), ); - let links_json = flatten_links(&span_record.links); - span_records_json.extend(links_json); span_record_json.insert( "span_dropped_links_count".to_string(), @@ -418,19 +424,29 @@ fn flatten_span_record(span_record: &Span) -> Vec> { if let Some(status) = &span_record.status { span_record_json.extend(flatten_status(status)); } - // if span_record.events is null, code should still flatten other elements in the span record - this is handled in the if block - // else block handles the flattening the span record that includes events and links records in each span record - if span_records_json.is_empty() { - span_records_json = vec![span_record_json]; - } else { - for span_json in &mut span_records_json { - for (key, value) in &span_record_json { - span_json.insert(key.clone(), value.clone()); - } - } - } + span_record_json +} - span_records_json +/// The rows of one span without its scope and resource fields +#[cfg(test)] +fn flatten_span_record(span_record: &Span) -> Vec> { + let empty = Map::new(); + let parents = SpanParents { + scope_fields: &empty, + scope_schema_url: "", + resource_fields: &empty, + }; + let mut rows = Vec::new(); + span_rows(span_record, &parents, &mut rows).expect("span rows are never refused"); + rows.into_iter() + .map(|row| { + let Value::Object(mut row) = row else { + unreachable!("rows are objects") + }; + row.shift_remove("scope_schema_url"); + row + }) + .collect() } pub fn insert_events_attributes(map: &mut Map, attributes: &[KeyValue]) { @@ -454,7 +470,7 @@ mod tests { use super::*; use opentelemetry_proto::tonic::common::v1::{AnyValue, EntityRef, KeyValue}; use opentelemetry_proto::tonic::resource::v1::Resource; - use opentelemetry_proto::tonic::trace::v1::{ResourceSpans, TracesData}; + use opentelemetry_proto::tonic::trace::v1::{ResourceSpans, ScopeSpans, TracesData}; /// Helper function to create a sample trace ID fn sample_trace_id() -> Vec { @@ -1188,8 +1204,6 @@ mod tests { use opentelemetry_proto::tonic::trace::v1::span::{Event, Link}; use opentelemetry_proto::tonic::trace::v1::{ResourceSpans, ScopeSpans, Span, Status}; - use super::super::flatten_otel_traces_protobuf; - const SPANS_PER_SCOPE: usize = 250; const ITERS: usize = 20; @@ -1322,8 +1336,12 @@ mod tests { ExportTraceServiceRequest { resource_spans } } + /// What ingestion does with a decoded request before staging: the rows + /// handed over in chunks (collected here) fn flatten(request: &ExportTraceServiceRequest) -> Vec { - flatten_otel_traces_protobuf(request, "perfbench") + bench::chunked(|chunker| { + super::super::flatten_traces_into(&request.resource_spans, chunker) + }) } #[test] From 1c7a7a83e420b10a34509f4f84e2a30c1af6c69b Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Mon, 23 Nov 2026 22:58:50 -0600 Subject: [PATCH 04/31] feat(otel): stage an OTLP request in chunks, answering partial success after a client error Both encodings now flatten into a Chunker whose chunks are staged through the push_logs path; all chunks of a request share one stream lookup and one p_timestamp, and read the stream schema afresh. A request that fits one chunk is staged exactly as before. A sizing pass over the decoded message counts records, data points and rows without building them. Before any chunk is staged, errors are returned as before. After one was: a client error (4xx: schema conflict, field limit, flatten limit) returns 200 with the OTLP partial_success message in the request's encoding (rejected_log_records / rejected_data_points / rejected_spans = records not staged in full); a server error keeps its 5xx, and as the exporter then retries the whole request, the chunks already staged are staged twice. The *_collected counters count what was staged. Co-Authored-By: Claude Opus 5.5 --- src/handlers/http/ingest.rs | 16 +- src/handlers/http/modal/utils/ingest_utils.rs | 664 ++++++++++++++---- .../utils/ingest_utils/otel_protobuf_props.rs | 172 ++++- src/otel.rs | 1 + src/otel/expansion.rs | 505 +++++++++++++ src/otel/logs.rs | 5 +- src/otel/memory_tests.rs | 10 +- src/otel/metrics.rs | 14 +- src/otel/traces.rs | 5 +- 9 files changed, 1227 insertions(+), 165 deletions(-) create mode 100644 src/otel/expansion.rs diff --git a/src/handlers/http/ingest.rs b/src/handlers/http/ingest.rs index e9b01930e..9a0c1e786 100644 --- a/src/handlers/http/ingest.rs +++ b/src/handlers/http/ingest.rs @@ -34,7 +34,7 @@ use crate::event::format::known_schema::{self, KNOWN_SCHEMA_LIST}; use crate::event::format::{self, EventFormat, LogSource, LogSourceEntry}; use crate::event::{self, FORMAT_KEY, USER_AGENT_KEY}; use crate::handlers::http::modal::utils::ingest_utils::{ - ingest_helper, otel_success_response, process_otel_content, validate_stream_for_ingestion, + ingest_helper, otel_response, process_otel_content, validate_stream_for_ingestion, }; use crate::handlers::{ DatasetTag, EXTRACT_LOG_KEY, LOG_SOURCE_KEY, STREAM_NAME_HEADER_KEY, TELEMETRY_TYPE_KEY, @@ -312,9 +312,10 @@ pub async fn handle_otel_logs_ingestion( e })?; - process_otel_content(&req, body, &stream_name, &log_source, TelemetryType::Logs).await?; + let ingested = + process_otel_content(&req, body, &stream_name, &log_source, TelemetryType::Logs).await?; - Ok(otel_success_response(&req)) + Ok(otel_response(&req, TelemetryType::Logs, &ingested)) } // Handler for POST /v1/metrics to ingest OTEL metrics @@ -338,7 +339,7 @@ pub async fn handle_otel_metrics_ingestion( e })?; - process_otel_content( + let ingested = process_otel_content( &req, body, &stream_name, @@ -347,7 +348,7 @@ pub async fn handle_otel_metrics_ingestion( ) .await?; - Ok(otel_success_response(&req)) + Ok(otel_response(&req, TelemetryType::Metrics, &ingested)) } // Handler for POST /v1/traces to ingest OTEL traces @@ -371,9 +372,10 @@ pub async fn handle_otel_traces_ingestion( e })?; - process_otel_content(&req, body, &stream_name, &log_source, TelemetryType::Traces).await?; + let ingested = + process_otel_content(&req, body, &stream_name, &log_source, TelemetryType::Traces).await?; - Ok(otel_success_response(&req)) + Ok(otel_response(&req, TelemetryType::Traces, &ingested)) } // Handler for POST /api/v1/logstream/{logstream} diff --git a/src/handlers/http/modal/utils/ingest_utils.rs b/src/handlers/http/modal/utils/ingest_utils.rs index a142de13a..dd82a4b5b 100644 --- a/src/handlers/http/modal/utils/ingest_utils.rs +++ b/src/handlers/http/modal/utils/ingest_utils.rs @@ -25,7 +25,9 @@ use opentelemetry_proto::tonic::collector::{ trace::v1::ExportTraceServiceRequest, }; use opentelemetry_proto::tonic::{ - logs::v1::LogsData, metrics::v1::MetricsData, trace::v1::TracesData, + logs::v1::{LogsData, ResourceLogs}, + metrics::v1::{MetricsData, ResourceMetrics}, + trace::v1::{ResourceSpans, TracesData}, }; use prost::Message as _; use rayon::prelude::*; @@ -48,13 +50,19 @@ use crate::{ kinesis::{Message, flatten_kinesis_logs}, }, }, + metrics::{ + increment_logs_collected_by_date, increment_metrics_collected_by_date, + increment_traces_collected_by_date, + }, otel::{ - logs::{flatten_otel_logs, flatten_otel_protobuf as flatten_otel_logs_protobuf}, - metrics::{flatten_otel_metrics, flatten_otel_metrics_protobuf}, + expansion::{RequestSize, logs_size, metrics_size, traces_size}, + logs::flatten_logs_into, + metrics::flatten_metrics_into, otel_utils::deserialize_otel_json, - traces::{flatten_otel_traces, flatten_otel_traces_protobuf}, + sink::{CHUNK_LIMITS, Chunker, RowSink, Staged}, + traces::flatten_traces_into, }, - parseable::{DEFAULT_TENANT, PARSEABLE}, + parseable::{DEFAULT_TENANT, PARSEABLE, Stream}, storage::StreamType, utils::{ get_tenant_id_from_request, @@ -101,7 +109,7 @@ pub async fn process_otel_content( stream_name: &str, log_source: &LogSource, telemetry_type: TelemetryType, -) -> Result<(), PostError> { +) -> Result { let p_custom_fields = get_otel_custom_fields_from_header(req, log_source); let content_type = req .headers() @@ -126,18 +134,35 @@ pub async fn process_otel_content( let _ = s.send(r); }); - if let Err(e) = r.await.map_err(|e| PostError::CustomError(e.to_string()))? { - Err(e) - } else { - Ok(()) - } + r.await.map_err(|e| PostError::CustomError(e.to_string()))? +} + +/// How an OTEL export request that was not refused was ingested +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum OtelIngested { + /// Every record was staged + Full, + /// Only some records were staged: a client error stopped the request after + /// at least one chunk of its rows was staged + Partial { + /// Log records, data points or spans not staged + rejected: i64, + /// Why the rest was not staged + message: String, + }, } -/// Response for an OTEL export request that was ingested in full. OTLP/HTTP +/// Response for an OTEL export request that was not refused. OTLP/HTTP /// answers in the encoding of the request: for protobuf that is an /// `Export*ServiceResponse`, whose full-success form encodes to zero bytes. -/// JSON requests keep the empty response they always had. -pub fn otel_success_response(req: &HttpRequest) -> HttpResponse { +/// JSON requests keep the empty response they always had when ingested in +/// full. A partial success sets `partial_success` (OTLP/HTTP requires status +/// 200 for it), in the request's own encoding. +pub fn otel_response( + req: &HttpRequest, + telemetry_type: TelemetryType, + ingested: &OtelIngested, +) -> HttpResponse { let protobuf = req .headers() .get(CONTENT_TYPE) @@ -148,7 +173,71 @@ pub fn otel_success_response(req: &HttpRequest) -> HttpResponse { if protobuf { response.content_type(CONTENT_TYPE_PROTOBUF); } - response.finish() + match ingested { + OtelIngested::Full => response.finish(), + OtelIngested::Partial { rejected, message } => { + if !protobuf { + response.content_type(CONTENT_TYPE_JSON); + } + response.body(partial_success_body( + telemetry_type, + *rejected, + message, + protobuf, + )) + } + } +} + +/// The `Export*ServiceResponse` of a partial success, encoded +fn partial_success_body( + telemetry_type: TelemetryType, + rejected: i64, + message: &str, + protobuf: bool, +) -> Vec { + use opentelemetry_proto::tonic::collector::{ + logs::v1::{ExportLogsPartialSuccess, ExportLogsServiceResponse}, + metrics::v1::{ExportMetricsPartialSuccess, ExportMetricsServiceResponse}, + trace::v1::{ExportTracePartialSuccess, ExportTraceServiceResponse}, + }; + fn encode(message: M, protobuf: bool) -> Vec { + if protobuf { + message.encode_to_vec() + } else { + serde_json::to_vec(&message).expect("OTLP responses serialise") + } + } + let error_message = message.to_string(); + match telemetry_type { + TelemetryType::Metrics => encode( + ExportMetricsServiceResponse { + partial_success: Some(ExportMetricsPartialSuccess { + rejected_data_points: rejected, + error_message, + }), + }, + protobuf, + ), + TelemetryType::Traces => encode( + ExportTraceServiceResponse { + partial_success: Some(ExportTracePartialSuccess { + rejected_spans: rejected, + error_message, + }), + }, + protobuf, + ), + _ => encode( + ExportLogsServiceResponse { + partial_success: Some(ExportLogsPartialSuccess { + rejected_log_records: rejected, + error_message, + }), + }, + protobuf, + ), + } } /// Payload encodings accepted by the OTEL HTTP endpoints. @@ -187,7 +276,14 @@ fn handle_otel_ingestion( telemetry_type: TelemetryType, content_type: Option, tenant_id: Option, -) -> Result<(), PostError> { +) -> Result { + let target = OtelTarget { + stream_name: &stream_name, + log_source: &log_source, + p_custom_fields: &p_custom_fields, + telemetry_type, + tenant_id: &tenant_id, + }; match content_type { Some(content_type) => match classify_otel_content_type(&content_type) { Some(OtelContentType::Json) => { @@ -200,51 +296,182 @@ fn handle_otel_ingestion( return Err(PostError::SerdeError(e)); } }; - if let Err(e) = flatten_and_push_logs( - json, - &stream_name, - &log_source, - &p_custom_fields, - None, - telemetry_type, - &tenant_id, - ) { + ingest_otel_json(json, &target).inspect_err(|e| { error!("Ingestion failed for stream {stream_name}: {e}"); - return Err(e); - } + }) } - Some(OtelContentType::Protobuf) => { - if let Err(e) = flatten_and_push_otel_protobuf( - &body, - &stream_name, - &log_source, - &p_custom_fields, - telemetry_type, - &tenant_id, - ) { + Some(OtelContentType::Protobuf) => flatten_and_push_otel_protobuf(&body, &target) + .inspect_err(|e| { error!("Ingestion failed for stream {stream_name}: {e}"); - return Err(e); - } - } + }), None => { error!( "Ingestion failed for stream {stream_name}: Unsupported Content-Type: {content_type}. Expected application/json or application/x-protobuf" ); - return Err(PostError::Invalid(anyhow::anyhow!( + Err(PostError::Invalid(anyhow::anyhow!( "Ingestion failed for stream {stream_name}: Unsupported Content-Type: {content_type}. Expected application/json or application/x-protobuf" - ))); + ))) } }, None => { error!( "Ingestion failed for stream {stream_name}: Missing Content-Type header. Expected application/json or application/x-protobuf" ); - return Err(PostError::Invalid(anyhow::anyhow!( + Err(PostError::Invalid(anyhow::anyhow!( "Ingestion failed for stream {stream_name}: Missing Content-Type header. Expected application/json or application/x-protobuf" - ))); + ))) } } - Ok(()) +} + +/// Where the rows of one OTEL request are staged +struct OtelTarget<'a> { + stream_name: &'a str, + log_source: &'a LogSource, + p_custom_fields: &'a HashMap, + telemetry_type: TelemetryType, + tenant_id: &'a Option, +} + +/// The resources of a decoded OTLP request, from either encoding +#[derive(Debug, Clone, Copy)] +enum OtelResources<'a> { + Logs(&'a [ResourceLogs]), + Metrics(&'a [ResourceMetrics]), + Traces(&'a [ResourceSpans]), +} + +impl OtelResources<'_> { + /// Rows, row bytes and records of the request, without building a row + fn size(&self, flatten_exemplars: bool) -> RequestSize { + match self { + Self::Logs(resources) => logs_size(resources), + Self::Metrics(resources) => metrics_size(resources, flatten_exemplars), + Self::Traces(resources) => traces_size(resources), + } + } + + /// Hands the rows of the request to `sink`, one at a time + fn flatten_into( + &self, + budget: &mut FlattenBudget, + flatten_exemplars: bool, + sink: &mut S, + ) -> Result<(), S::Error> { + match self { + Self::Logs(resources) => flatten_logs_into(resources, budget, sink), + Self::Metrics(resources) => flatten_metrics_into(resources, flatten_exemplars, sink), + Self::Traces(resources) => flatten_traces_into(resources, sink), + } + } + + /// The records a partial success reports as rejected: log records, data + /// points or spans that were not staged in full + fn rejected(&self, size: &RequestSize, staged: &Staged) -> i64 { + let (total, staged) = match self { + Self::Metrics(_) => (size.points, staged.points), + Self::Logs(_) | Self::Traces(_) => (size.records, staged.records), + }; + total.saturating_sub(staged) as i64 + } + + /// Counts for `tenant_id` the leaf records (log records, spans, metrics) + /// whose rows were all staged + fn count_collected(&self, records: u64, tenant_id: &str) { + if records == 0 { + return; + } + let date = Utc::now().date_naive().to_string(); + match self { + Self::Logs(_) => increment_logs_collected_by_date(records, &date, tenant_id), + Self::Metrics(_) => increment_metrics_collected_by_date(records, &date, tenant_id), + Self::Traces(_) => increment_traces_collected_by_date(records, &date, tenant_id), + } + } +} + +/// Stages the rows of one decoded OTEL request in chunks (see `Chunker`), so +/// that its rows are never all held at once. +/// +/// Before any chunk is staged, errors are returned as they are. Once at least +/// one chunk is staged, the request stops at the first failing chunk: +/// - a client error (status 4xx, such as a schema conflict, the field count +/// limit or a flatten limit) becomes a partial success that reports every +/// record not staged in full as rejected, answered with status 200 as +/// OTLP/HTTP requires; +/// - a server error keeps its 5xx status. The exporter then retries the whole +/// request, so the rows of the chunks already staged are staged twice. +fn ingest_otel_resources( + resources: OtelResources<'_>, + target: &OtelTarget<'_>, +) -> Result { + let tenant_str = target.tenant_id.as_deref().unwrap_or(DEFAULT_TENANT); + // Verify the dataset fields count + verify_dataset_fields_count(target.stream_name, target.tenant_id)?; + let flatten_exemplars = PARSEABLE.options.otel_flatten_exemplars; + let size = resources.size(flatten_exemplars); + + // The JSON log bodies of every record of the request share one budget + let mut budget = FlattenBudget::new(FlattenLimits::from_config()); + let mut staging = Staging::new(target.stream_name, target.tenant_id)?; + let mut chunker = Chunker::new(CHUNK_LIMITS, |rows: Vec| { + staging.push( + Value::Array(rows), + target.log_source, + target.p_custom_fields, + None, + target.telemetry_type, + ) + }); + let result = resources + .flatten_into(&mut budget, flatten_exemplars, &mut chunker) + .and_then(|()| chunker.finish()); + let staged = chunker.staged(); + drop(chunker); + + if result.is_ok() || staged.chunks > 0 { + resources.count_collected(staged.records, tenant_str); + } + match result { + Ok(()) => Ok(OtelIngested::Full), + Err(error) + if staged.chunks > 0 + && actix_web::ResponseError::status_code(&error).is_client_error() => + { + let rejected = resources.rejected(&size, &staged); + warn!( + "Ingestion into stream {} stopped after {} rows: {error}. {rejected} records rejected", + target.stream_name, staged.rows + ); + Ok(OtelIngested::Partial { + rejected, + message: error.to_string(), + }) + } + Err(error) => Err(error), + } +} + +/// The OTEL arms of `handle_otel_ingestion` for a JSON body +fn ingest_otel_json(json: Value, target: &OtelTarget<'_>) -> Result { + let normalise = PARSEABLE.options.normalise_otel_payload; + match target.log_source { + LogSource::OtelLogs => { + let logs: LogsData = deserialize_otel_json(json, normalise)?; + ingest_otel_resources(OtelResources::Logs(&logs.resource_logs), target) + } + LogSource::OtelMetrics => { + let metrics: MetricsData = deserialize_otel_json(json, normalise)?; + ingest_otel_resources(OtelResources::Metrics(&metrics.resource_metrics), target) + } + LogSource::OtelTraces => { + let traces: TracesData = deserialize_otel_json(json, normalise)?; + ingest_otel_resources(OtelResources::Traces(&traces.resource_spans), target) + } + other => Err(PostError::Invalid(anyhow::anyhow!( + "OTLP ingestion requires an OTLP log source, got {other}" + ))), + } } /// An OTLP/HTTP export request decoded from its protobuf encoding. @@ -279,56 +506,53 @@ impl OtelProtobufRequest { } } - /// Flattens into the same rows the JSON encoding of this request produces. + /// The resources of the request, which flatten into the same rows the JSON + /// encoding of this request produces + fn resources(&self) -> OtelResources<'_> { + match self { + Self::Logs(message) => OtelResources::Logs(&message.resource_logs), + Self::Metrics(message) => OtelResources::Metrics(&message.resource_metrics), + Self::Traces(message) => OtelResources::Traces(&message.resource_spans), + } + } + + /// Flattens into the same rows the JSON encoding of this request produces, + /// all at once + #[cfg(test)] fn flatten( &self, tenant_id: &str, budget: &mut FlattenBudget, ) -> Result, JsonFlattenError> { match self { - Self::Logs(message) => flatten_otel_logs_protobuf(message, tenant_id, budget), - Self::Metrics(message) => Ok(flatten_otel_metrics_protobuf(message, tenant_id)), - Self::Traces(message) => Ok(flatten_otel_traces_protobuf(message, tenant_id)), + Self::Logs(message) => { + crate::otel::logs::flatten_otel_protobuf(message, tenant_id, budget) + } + Self::Metrics(message) => Ok(crate::otel::metrics::flatten_otel_metrics_protobuf( + message, tenant_id, + )), + Self::Traces(message) => Ok(crate::otel::traces::flatten_otel_traces_protobuf( + message, tenant_id, + )), } } } -/// Protobuf counterpart of the OTEL arms of `flatten_and_push_logs`: the typed -/// request is decoded straight from the body instead of going through a JSON -/// value tree, then shares flattening limits and the staging path with JSON. +/// Protobuf counterpart of `ingest_otel_json`: the typed request is decoded +/// straight from the body instead of going through a JSON value tree, then +/// shares flattening limits and the staging path with JSON. /// The body size is capped by the `PayloadConfig` of the OTEL routes. fn flatten_and_push_otel_protobuf( body: &[u8], - stream_name: &str, - log_source: &LogSource, - p_custom_fields: &HashMap, - telemetry_type: TelemetryType, - tenant_id: &Option, -) -> Result<(), PostError> { - let request = OtelProtobufRequest::decode(body, log_source).map_err(|e| { + target: &OtelTarget<'_>, +) -> Result { + let request = OtelProtobufRequest::decode(body, target.log_source).map_err(|e| { PostError::Invalid(anyhow::anyhow!( - "Ingestion failed for stream {stream_name}: {e}" + "Ingestion failed for stream {}: {e}", + target.stream_name )) })?; - let tenant_str = tenant_id.as_deref().unwrap_or(DEFAULT_TENANT); - // Verify the dataset fields count - verify_dataset_fields_count(stream_name, tenant_id)?; - // Shared by every record of this request - let mut budget = FlattenBudget::new(FlattenLimits::from_config()); - let records = request.flatten(tenant_str, &mut budget)?; - if !records.is_empty() { - push_logs( - stream_name, - Value::Array(records), - log_source, - p_custom_fields, - None, - telemetry_type, - tenant_id, - &mut budget, - )?; - } - Ok(()) + ingest_otel_resources(request.resources(), target) } #[instrument( @@ -353,9 +577,13 @@ pub fn flatten_and_push_logs( telemetry_type: TelemetryType, tenant_id: &Option, ) -> Result<(), PostError> { - let tenant_str = tenant_id.as_deref().unwrap_or(DEFAULT_TENANT); - // Verify the dataset fields count - verify_dataset_fields_count(stream_name, tenant_id)?; + if !matches!( + log_source, + LogSource::OtelLogs | LogSource::OtelTraces | LogSource::OtelMetrics + ) { + // Verify the dataset fields count (the OTEL arms do it themselves) + verify_dataset_fields_count(stream_name, tenant_id)?; + } // Shared by every event of this request let mut budget = FlattenBudget::new(FlattenLimits::from_config()); @@ -376,55 +604,18 @@ pub fn flatten_and_push_logs( &mut budget, )?; } - LogSource::OtelLogs => { - let logs: LogsData = - deserialize_otel_json(json, PARSEABLE.options.normalise_otel_payload)?; - let records = flatten_otel_logs(&logs, tenant_str, &mut budget)?; - if !records.is_empty() { - push_logs( - stream_name, - Value::Array(records), - log_source, - p_custom_fields, - None, - telemetry_type, - tenant_id, - &mut budget, - )?; - } - } - LogSource::OtelTraces => { - let traces: TracesData = - deserialize_otel_json(json, PARSEABLE.options.normalise_otel_payload)?; - let records = flatten_otel_traces(&traces, tenant_str); - if !records.is_empty() { - push_logs( - stream_name, - Value::Array(records), - log_source, - p_custom_fields, - None, - telemetry_type, - tenant_id, - &mut budget, - )?; - } - } - LogSource::OtelMetrics => { - let metrics: MetricsData = - deserialize_otel_json(json, PARSEABLE.options.normalise_otel_payload)?; - let records = flatten_otel_metrics(metrics, tenant_str); - if !records.is_empty() { - push_logs( - stream_name, - Value::Array(records), - log_source, - p_custom_fields, - None, - telemetry_type, - tenant_id, - &mut budget, - )?; + // Only reached through `handle_otel_ingestion`, which answers partial + // successes itself; here they fail the request + LogSource::OtelLogs | LogSource::OtelTraces | LogSource::OtelMetrics => { + let target = OtelTarget { + stream_name, + log_source, + p_custom_fields, + telemetry_type, + tenant_id, + }; + if let OtelIngested::Partial { message, .. } = ingest_otel_json(json, &target)? { + return Err(PostError::Invalid(anyhow::Error::msg(message))); } } _ => push_logs( @@ -469,22 +660,146 @@ pub fn push_logs( tenant_id: &Option, budget: &mut FlattenBudget, ) -> Result<(), PostError> { - // Snapshot at request entry. A subscriber attaching later receives ordered - // single-row slices from the grouped path. - let grouped = use_partitioned_ingest_batching( - PARSEABLE.options.partitioned_ingest_batching, - PARSEABLE.options.mode, - &crate::livetail::LIVETAIL, + Staging::new(stream_name, tenant_id)?.push_with_budget( + json, + log_source, + p_custom_fields, + time_partition, + telemetry_type, + budget, + ) +} + +/// The stream one request is staged into, looked up once, and what every part of +/// the request shares: its ingestion time (`p_timestamp`) and whether it uses the +/// grouped path. A request can be staged in several parts (chunks); each part +/// reads the stream's current schema, so it sees the fields the parts before it +/// added, as a later request would. +pub struct Staging<'a> { + stream_name: &'a str, + tenant_id: &'a Option, + stream: std::sync::Arc, + grouped: bool, + p_timestamp: chrono::DateTime, + /// Flattening budget of the parts, shared by all of them + budget: FlattenBudget, +} + +impl<'a> Staging<'a> { + pub fn new(stream_name: &'a str, tenant_id: &'a Option) -> Result { + // Snapshot at request entry. A subscriber attaching later receives ordered + // single-row slices from the grouped path. + let grouped = use_partitioned_ingest_batching( + PARSEABLE.options.partitioned_ingest_batching, + PARSEABLE.options.mode, + &crate::livetail::LIVETAIL, + stream_name, + ); + let stream = PARSEABLE.get_stream(stream_name, tenant_id)?; + Ok(Self { + stream_name, + tenant_id, + stream, + grouped, + p_timestamp: Utc::now(), + budget: FlattenBudget::new(FlattenLimits::from_config()), + }) + } + + /// Stages one part of the request, charging its flattening to the budget + /// all parts share + pub fn push( + &mut self, + json: Value, + log_source: &LogSource, + p_custom_fields: &HashMap, + time_partition: Option, + telemetry_type: TelemetryType, + ) -> Result<(), PostError> { + let Self { + stream_name, + tenant_id, + stream, + grouped, + p_timestamp, + budget, + } = self; + stage_json( + StageInto { + stream_name, + tenant_id, + stream, + grouped: *grouped, + p_timestamp: *p_timestamp, + }, + json, + log_source, + p_custom_fields, + time_partition, + telemetry_type, + budget, + ) + } + + fn push_with_budget( + self, + json: Value, + log_source: &LogSource, + p_custom_fields: &HashMap, + time_partition: Option, + telemetry_type: TelemetryType, + budget: &mut FlattenBudget, + ) -> Result<(), PostError> { + stage_json( + StageInto { + stream_name: self.stream_name, + tenant_id: self.tenant_id, + stream: &self.stream, + grouped: self.grouped, + p_timestamp: self.p_timestamp, + }, + json, + log_source, + p_custom_fields, + time_partition, + telemetry_type, + budget, + ) + } +} + +/// What `stage_json` takes from a `Staging` +struct StageInto<'a> { + stream_name: &'a str, + tenant_id: &'a Option, + stream: &'a Stream, + grouped: bool, + p_timestamp: chrono::DateTime, +} + +/// Stages one part of a request +fn stage_json( + into: StageInto<'_>, + json: Value, + log_source: &LogSource, + p_custom_fields: &HashMap, + time_partition: Option, + telemetry_type: TelemetryType, + budget: &mut FlattenBudget, +) -> Result<(), PostError> { + let StageInto { stream_name, - ); - let stream = PARSEABLE.get_stream(stream_name, tenant_id)?; + tenant_id, + stream, + grouped, + p_timestamp, + } = into; let time_partition_limit = stream.get_time_partition_limit(); let static_schema_flag = stream.get_static_schema_flag(); let custom_partition = stream.get_custom_partition(); let schema_version = stream.get_schema_version(); let schema = stream.get_schema_raw(); let infer_timestamp = stream.get_infer_timestamp(); - let p_timestamp = Utc::now(); let data = convert_array_to_object( json, @@ -815,6 +1130,7 @@ pub fn validate_stream_for_ingestion( #[cfg(test)] mod tests { use super::*; + use crate::otel::{logs::flatten_otel_logs, traces::flatten_otel_traces}; use actix_web::test::TestRequest; #[test] @@ -1152,7 +1468,7 @@ mod tests { } #[test] - fn otel_success_response_answers_in_the_request_encoding() { + fn otel_full_success_response_answers_in_the_request_encoding() { use actix_web::http::header::CONTENT_TYPE; for (request_type, response_type) in [ @@ -1171,7 +1487,11 @@ mod tests { if let Some(value) = request_type { req = req.insert_header((CONTENT_TYPE, value)); } - let resp = otel_success_response(&req.to_http_request()); + let resp = otel_response( + &req.to_http_request(), + TelemetryType::Logs, + &OtelIngested::Full, + ); assert_eq!(resp.status(), actix_web::http::StatusCode::OK); assert_eq!( resp.headers() @@ -1183,6 +1503,68 @@ mod tests { } } + #[actix_web::test] + async fn otel_partial_success_is_answered_in_the_request_encoding() { + use actix_web::body::MessageBody; + use actix_web::http::header::CONTENT_TYPE; + use opentelemetry_proto::tonic::collector::{ + logs::v1::ExportLogsServiceResponse, metrics::v1::ExportMetricsServiceResponse, + trace::v1::ExportTraceServiceResponse, + }; + + let partial = OtelIngested::Partial { + rejected: 7, + message: "schema conflict".to_string(), + }; + let body = |request_type: &str, telemetry_type| { + let req = TestRequest::default() + .insert_header((CONTENT_TYPE, request_type)) + .to_http_request(); + let resp = otel_response(&req, telemetry_type, &partial); + assert_eq!(resp.status(), actix_web::http::StatusCode::OK); + let content_type = resp + .headers() + .get(CONTENT_TYPE) + .map(|v| v.to_str().unwrap().to_string()); + ( + content_type, + resp.into_body().try_into_bytes().ok().unwrap(), + ) + }; + + let (content_type, bytes) = body("application/x-protobuf", TelemetryType::Logs); + assert_eq!(content_type.as_deref(), Some("application/x-protobuf")); + let partial_success = ExportLogsServiceResponse::decode(bytes) + .unwrap() + .partial_success + .unwrap(); + assert_eq!(partial_success.rejected_log_records, 7); + assert_eq!(partial_success.error_message, "schema conflict"); + + let (_, bytes) = body("application/x-protobuf", TelemetryType::Metrics); + let partial_success = ExportMetricsServiceResponse::decode(bytes) + .unwrap() + .partial_success + .unwrap(); + assert_eq!(partial_success.rejected_data_points, 7); + + let (_, bytes) = body("application/x-protobuf", TelemetryType::Traces); + let partial_success = ExportTraceServiceResponse::decode(bytes) + .unwrap() + .partial_success + .unwrap(); + assert_eq!(partial_success.rejected_spans, 7); + + let (content_type, bytes) = body("application/json", TelemetryType::Traces); + assert_eq!(content_type.as_deref(), Some("application/json")); + assert_eq!( + serde_json::from_slice::(&bytes).unwrap(), + serde_json::json!({ + "partialSuccess": { "rejectedSpans": 7, "errorMessage": "schema conflict" } + }) + ); + } + #[test] fn otel_protobuf_decode_rejects_non_otel_log_source() { let err = OtelProtobufRequest::decode(&[], &LogSource::Json).unwrap_err(); diff --git a/src/handlers/http/modal/utils/ingest_utils/otel_protobuf_props.rs b/src/handlers/http/modal/utils/ingest_utils/otel_protobuf_props.rs index 42dcec73f..b7d293a27 100644 --- a/src/handlers/http/modal/utils/ingest_utils/otel_protobuf_props.rs +++ b/src/handlers/http/modal/utils/ingest_utils/otel_protobuf_props.rs @@ -41,10 +41,13 @@ //! - `DST_SEED`, `DST_ITERS`: first seed and number of seeds of the DST scenario use super::*; +use crate::otel::logs::flatten_otel_logs; use crate::otel::metrics::{ flatten_otel_metrics_protobuf_with_options, flatten_otel_metrics_with_options, }; use crate::otel::otel_utils::flatten_attributes; +use crate::otel::sink::{ChunkLimits, Chunker}; +use crate::otel::traces::flatten_otel_traces; use crate::utils::json::flatten::FlattenCost; use opentelemetry_proto::tonic::common::v1::{ AnyValue, ArrayValue, InstrumentationScope, KeyValue, KeyValueList, any_value, @@ -1452,6 +1455,151 @@ fn otel_pb_wild_requests_flatten_and_agree_where_json_can_carry_them() { assert!(carried > 0 && not_carried > 0, "{carried} / {not_carried}"); } +// --------------------------------------------------------------------------- +// Chunked staging +// --------------------------------------------------------------------------- + +impl Req { + fn resources(&self) -> OtelResources<'_> { + match self { + Self::Logs(data) => OtelResources::Logs(&data.resource_logs), + Self::Metrics(data) => OtelResources::Metrics(&data.resource_metrics), + Self::Traces(data) => OtelResources::Traces(&data.resource_spans), + } + } + + fn resource_count(&self) -> usize { + match self { + Self::Logs(data) => data.resource_logs.len(), + Self::Metrics(data) => data.resource_metrics.len(), + Self::Traces(data) => data.resource_spans.len(), + } + } +} + +/// The request decoded from `body` in `encoding`, as ingestion decodes it +fn decode_as(request: &Req, protobuf: bool) -> Req { + let source = request.source(); + if protobuf { + Req::from_decoded(OtelProtobufRequest::decode(&request.encode_pb(), &source).unwrap()) + } else { + let json: Value = serde_json::from_slice(&request.encode_json()).unwrap(); + match request { + Req::Logs(_) => Req::Logs(deserialize_otel_json(json, false).unwrap()), + Req::Metrics(_) => Req::Metrics(deserialize_otel_json(json, false).unwrap()), + Req::Traces(_) => Req::Traces(deserialize_otel_json(json, false).unwrap()), + } + } +} + +/// Chunks of at most `rows` rows (and a byte limit small enough to cut chunks of a +/// row or two) give the same rows in the same order as one chunk, for both +/// encodings, and count every record and data point as staged. The sizing pass +/// counts the same records and data points, and the rows up to one `target_info` +/// row per resource. +fn chunking_keeps_rows( + mut request: Req, + rows: usize, + bytes: usize, + flatten_exemplars: bool, +) -> TestCaseResult { + fill_unset_timestamps(&mut request); + prop_assume!(json_representable(&request)); + let limits = ChunkLimits { rows, bytes }; + for protobuf in [true, false] { + let decoded = decode_as(&request, protobuf); + let resources = decoded.resources(); + let mut whole = Vec::new(); + resources + .flatten_into( + &mut FlattenBudget::new(FlattenLimits::DEFAULT), + flatten_exemplars, + &mut whole, + ) + .unwrap(); + let mut chunks: Vec> = Vec::new(); + let mut chunker = Chunker::new(limits, |rows| { + chunks.push(rows); + Ok::<_, JsonFlattenError>(()) + }); + resources + .flatten_into( + &mut FlattenBudget::new(FlattenLimits::DEFAULT), + flatten_exemplars, + &mut chunker, + ) + .unwrap(); + chunker.finish().unwrap(); + let staged = chunker.staged(); + drop(chunker); + + prop_assert!( + chunks + .iter() + .all(|chunk| !chunk.is_empty() && chunk.len() <= rows) + ); + prop_assert_eq!(staged.chunks as usize, chunks.len()); + let chunked: Vec = chunks.into_iter().flatten().collect(); + prop_assert_eq!( + serde_json::to_vec(&chunked).unwrap(), + serde_json::to_vec(&whole).unwrap(), + "chunked rows differ (protobuf: {})", + protobuf + ); + let size = resources.size(flatten_exemplars); + prop_assert_eq!(staged.rows as usize, whole.len()); + prop_assert_eq!(staged.records, size.records); + prop_assert_eq!(staged.points, size.points); + prop_assert!( + size.rows as usize >= whole.len() + && size.rows as usize <= whole.len() + decoded.resource_count(), + "sizing pass counted {} rows for {}", + size.rows, + whole.len() + ); + } + Ok(()) +} + +fn chunk_limits() -> impl Strategy { + ( + 1usize..5, + prop_oneof![Just(1usize), Just(4096), Just(usize::MAX)], + ) +} + +#[test] +fn otel_chunked_rows_match_one_chunk_logs() { + check( + "otel_chunked_rows_match_one_chunk_logs", + 64, + (logs_data(false), chunk_limits()), + |(logs, (rows, bytes))| chunking_keeps_rows(Req::Logs(logs), rows, bytes, false), + ); +} + +#[test] +fn otel_chunked_rows_match_one_chunk_traces() { + check( + "otel_chunked_rows_match_one_chunk_traces", + 64, + (traces_data(false), chunk_limits()), + |(traces, (rows, bytes))| chunking_keeps_rows(Req::Traces(traces), rows, bytes, false), + ); +} + +#[test] +fn otel_chunked_rows_match_one_chunk_metrics() { + check( + "otel_chunked_rows_match_one_chunk_metrics", + 64, + (metrics_data(false), chunk_limits(), any::()), + |(metrics, (rows, bytes), flatten_exemplars)| { + chunking_keeps_rows(Req::Metrics(metrics), rows, bytes, flatten_exemplars) + }, + ); +} + // --------------------------------------------------------------------------- // 2. Robustness of the decoder // --------------------------------------------------------------------------- @@ -1503,11 +1651,13 @@ fn decode_is_total( // Returns before the dataset field check, the first use of `PARSEABLE` let refused = flatten_and_push_otel_protobuf( body, - "otel_pb_props", - source, - &HashMap::new(), - telemetry_type, - &None, + &OtelTarget { + stream_name: "otel_pb_props", + log_source: source, + p_custom_fields: &HashMap::new(), + telemetry_type, + tenant_id: &None, + }, ) .expect_err("a body that does not decode is refused"); prop_assert!(matches!(refused, PostError::Invalid(_)), "{refused:?}"); @@ -2377,11 +2527,13 @@ fn run_scenario(seed: u64) -> Result)> { if encoding == Encoding::Protobuf { let refused = flatten_and_push_otel_protobuf( &body, - "dst", - &source, - &HashMap::new(), - request.telemetry_type(), - &None, + &OtelTarget { + stream_name: "dst", + log_source: &source, + p_custom_fields: &HashMap::new(), + telemetry_type: request.telemetry_type(), + tenant_id: &None, + }, ); if !matches!(&refused, Err(PostError::Invalid(e)) if e.to_string().ends_with(error.as_str())) { diff --git a/src/otel.rs b/src/otel.rs index d2fb9424c..39d52d764 100644 --- a/src/otel.rs +++ b/src/otel.rs @@ -16,6 +16,7 @@ * */ +pub mod expansion; pub mod logs; pub mod metrics; pub mod otel_utils; diff --git a/src/otel/expansion.rs b/src/otel/expansion.rs new file mode 100644 index 000000000..01087678c --- /dev/null +++ b/src/otel/expansion.rs @@ -0,0 +1,505 @@ +/* + * Parseable Server (C) 2022 - 2025 Parseable, Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + */ + +//! What an OTLP request expands to, computed from the decoded message without +//! building a row. +//! +//! Every row carries its own copy of the resource, scope, span and metric fields, +//! so a small request can expand to a very large number of row bytes: 15 KB of +//! resource attributes copied into each of 5 million two-byte log records is tens +//! of GiB. Chunking bounds the memory this takes at once, not what is written to +//! staging, so the request is refused before anything is staged when its rows +//! would hold more than [`max_expanded_bytes`]. The sizes are in the units of +//! [`super::sink::row_bytes`], and follow the flatteners field by field; they are +//! estimates (JSON log bodies are counted as their text, not as the fields parsed +//! from them, which the flatten budget charges). + +use std::collections::HashSet; + +use opentelemetry_proto::tonic::common::v1::{ + AnyValue, InstrumentationScope, KeyValue, any_value::Value as OtelValue, +}; +use opentelemetry_proto::tonic::logs::v1::{LogRecord, ResourceLogs}; +use opentelemetry_proto::tonic::metrics::v1::{ + Exemplar, Metric, ResourceMetrics, exponential_histogram_data_point::Buckets, metric, +}; +use opentelemetry_proto::tonic::resource::v1::Resource; +use opentelemetry_proto::tonic::trace::v1::{ + ResourceSpans, Span, + span::{Event, Link}, +}; + +use super::sink::{ENTRY_BYTES, VALUE_BYTES, heap_bytes}; + +/// Rows, estimated row bytes and leaf records of one request +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct RequestSize { + /// Rows the request expands to + pub rows: u64, + /// Estimated memory of all of its rows, see `row_bytes` + pub bytes: u64, + /// Log records, spans or metrics + pub records: u64, + /// Metric data points + pub points: u64, +} + +impl RequestSize { + /// Adds `rows` rows of `row` bytes each + fn add_rows(&mut self, rows: u64, row: usize) { + self.rows += rows; + self.bytes = self.bytes.saturating_add(rows.saturating_mul(row as u64)); + } + + /// Adds bytes that only one row holds + fn add_bytes(&mut self, bytes: usize) { + self.bytes = self.bytes.saturating_add(bytes as u64); + } +} + +/// Timestamps are formatted as `%Y-%m-%dT%H:%M:%S%.9fZ` +const TIMESTAMP_LEN: usize = 30; +/// Longest decimal `i64` +const INT_LEN: usize = 20; + +#[inline] +fn field(key_len: usize, value_heap: usize) -> usize { + ENTRY_BYTES + heap_bytes(key_len) + value_heap +} + +#[inline] +fn str_field(key: &str, value_len: usize) -> usize { + field(key.len(), heap_bytes(value_len)) +} + +#[inline] +fn num_field(key: &str) -> usize { + field(key.len(), 0) +} + +#[inline] +fn timestamp_field(key: &str) -> usize { + str_field(key, TIMESTAMP_LEN) +} + +#[inline] +fn hex_field(key: &str, bytes: usize) -> usize { + str_field(key, 2 * bytes) +} + +/// Fields `insert_attributes` adds for `attributes`, with `prefix` before each key +fn attributes_bytes(attributes: &[KeyValue], prefix: usize) -> usize { + attributes + .iter() + .filter_map(|attribute| { + let value = attribute.value.as_ref()?.value.as_ref()?; + Some(value_fields(attribute.key.len() + prefix, value, prefix)) + }) + .sum() +} + +/// Fields one OTLP value adds under a key of `key_len` bytes +fn value_fields(key_len: usize, value: &OtelValue, prefix: usize) -> usize { + match value { + OtelValue::StringValue(s) => field(key_len, heap_bytes(s.len())), + OtelValue::BoolValue(_) | OtelValue::DoubleValue(_) => field(key_len, 0), + OtelValue::IntValue(_) => field(key_len, heap_bytes(INT_LEN)), + OtelValue::BytesValue(b) => field(key_len, heap_bytes(b.len())), + // Serialised to a JSON string + OtelValue::ArrayValue(array) => field(key_len, heap_bytes(array_json_len(&array.values))), + // Every entry becomes a field of its own, under its own key + OtelValue::KvlistValue(list) => list + .values + .iter() + .filter_map(|entry| { + let value = entry.value.as_ref()?.value.as_ref()?; + Some(value_fields(entry.key.len() + prefix, value, prefix)) + }) + .sum(), + OtelValue::StringValueStrindex(_) => 0, + } +} + +/// Approximate length of the JSON text of an array value +fn array_json_len(values: &[AnyValue]) -> usize { + 2 + values + .iter() + .map(|value| { + 1 + match &value.value { + Some(OtelValue::StringValue(s)) => s.len() + 2, + Some(OtelValue::BytesValue(b)) => b.len() + 2, + Some(OtelValue::ArrayValue(array)) => array_json_len(&array.values), + Some(OtelValue::KvlistValue(list)) => list + .values + .iter() + .map(|entry| { + entry.key.len() + + 4 + + entry + .value + .as_ref() + .map_or(4, |value| array_json_len(std::slice::from_ref(value))) + }) + .sum::(), + _ => INT_LEN, + } + }) + .sum::() +} + +fn scope_bytes(scope: Option<&InstrumentationScope>) -> usize { + scope.map_or(0, |scope| { + str_field("scope_name", scope.name.len()) + + str_field("scope_version", scope.version.len()) + + attributes_bytes(&scope.attributes, 0) + + num_field("scope_dropped_attributes_count") + }) +} + +fn resource_bytes(resource: Option<&Resource>) -> usize { + resource.map_or(0, |resource| { + attributes_bytes(&resource.attributes, 0) + num_field("resource_dropped_attributes_count") + }) +} + +// --------------------------------------------------------------------------- +// Logs +// --------------------------------------------------------------------------- + +fn log_record_bytes(record: &LogRecord) -> usize { + timestamp_field("time_unix_nano") + + timestamp_field("observed_time_unix_nano") + + num_field("severity_number") + + str_field("severity_text", record.severity_text.len().max(11)) + + record + .body + .as_ref() + .and_then(|body| body.value.as_ref()) + .map_or(0, |body| value_fields("body".len(), body, 0)) + + attributes_bytes(&record.attributes, 0) + + str_field("p_log_category", 11) + + num_field("log_record_dropped_attributes_count") + + num_field("flags") + + hex_field("span_id", record.span_id.len()) + + hex_field("trace_id", record.trace_id.len()) +} + +/// Rows and row bytes of a logs request +pub fn logs_size(resource_logs: &[ResourceLogs]) -> RequestSize { + let mut size = RequestSize::default(); + for resource_log in resource_logs { + let resource = resource_bytes(resource_log.resource.as_ref()) + + str_field("schema_url", resource_log.schema_url.len()); + for scope_log in &resource_log.scope_logs { + let shared = VALUE_BYTES + + resource + + scope_bytes(scope_log.scope.as_ref()) + + str_field("scope_log_schema_url", scope_log.schema_url.len()); + let records = scope_log.log_records.len() as u64; + size.records += records; + size.add_rows(records, shared); + for record in &scope_log.log_records { + size.add_bytes(log_record_bytes(record)); + } + } + } + size +} + +// --------------------------------------------------------------------------- +// Traces +// --------------------------------------------------------------------------- + +fn span_bytes(span: &Span) -> usize { + hex_field("span_trace_id", span.trace_id.len()) + + hex_field("span_span_id", span.span_id.len()) + + str_field("span_trace_state", span.trace_state.len()) + + hex_field("span_parent_span_id", span.parent_span_id.len()) + + num_field("span_flags") + + str_field("span_flags_description", 26) + + str_field("span_name", span.name.len()) + + num_field("span_kind") + + str_field("span_kind_description", 11) + + timestamp_field("span_start_time_unix_nano") + + num_field("span_start_time_unix_nano_epoch") + + timestamp_field("span_end_time_unix_nano") + + num_field("span_end_time_unix_nano_epoch") + + num_field("span_duration_ns") + + attributes_bytes(&span.attributes, 0) + + num_field("span_dropped_attributes_count") + + num_field("span_dropped_events_count") + + num_field("span_dropped_links_count") + + span.status.as_ref().map_or(0, |status| { + str_field("span_status_message", status.message.len()) + + num_field("span_status_code") + + str_field("span_status_description", 5) + }) +} + +fn event_bytes(event: &Event) -> usize { + timestamp_field("event_time_unix_nano") + + num_field("event_time_unix_nano_epoch") + + str_field("event_name", event.name.len()) + + num_field("event_duration_ns") + + attributes_bytes(&event.attributes, "event_".len()) + + num_field("event_dropped_attributes_count") +} + +fn link_bytes(link: &Link) -> usize { + hex_field("link_span_id", link.span_id.len()) + + hex_field("link_trace_id", link.trace_id.len()) + + attributes_bytes(&link.attributes, "link_".len()) + + num_field("link_dropped_attributes_count") +} + +/// Rows and row bytes of a traces request +pub fn traces_size(resource_spans: &[ResourceSpans]) -> RequestSize { + let mut size = RequestSize::default(); + for resource_span in resource_spans { + let resource = resource_bytes(resource_span.resource.as_ref()) + + str_field("resource_schema_url", resource_span.schema_url.len()); + for scope_span in &resource_span.scope_spans { + let shared = VALUE_BYTES + + resource + + scope_bytes(scope_span.scope.as_ref()) + + str_field("scope_schema_url", scope_span.schema_url.len()); + size.records += scope_span.spans.len() as u64; + for span in &scope_span.spans { + let rows = (span.events.len() + span.links.len()).max(1) as u64; + size.add_rows(rows, shared + span_bytes(span)); + for event in &span.events { + size.add_bytes(event_bytes(event)); + } + for link in &span.links { + size.add_bytes(link_bytes(link)); + } + } + } + } + size +} + +// --------------------------------------------------------------------------- +// Metrics +// --------------------------------------------------------------------------- + +fn exemplar_fields(exemplar: &Exemplar) -> usize { + attributes_bytes(&exemplar.filtered_attributes, 0) + + timestamp_field("exemplar_time_unix_nano") + + hex_field("exemplar_span_id", exemplar.span_id.len()) + + hex_field("exemplar_trace_id", exemplar.trace_id.len()) + + exemplar + .value + .as_ref() + .map_or(0, |_| num_field("exemplar_value")) +} + +/// Bytes of the exemplars of one data point, including the column table that +/// structural flattening builds from them when they are kept nested +fn exemplars_bytes(exemplars: &[Exemplar], flatten_exemplars: bool) -> usize { + if exemplars.is_empty() { + return 0; + } + let fields: usize = exemplars.iter().map(exemplar_fields).sum(); + if flatten_exemplars { + return fields; + } + let mut keys: HashSet<&str> = HashSet::from([ + "exemplar_time_unix_nano", + "exemplar_span_id", + "exemplar_trace_id", + "exemplar_value", + ]); + for exemplar in exemplars { + keys.extend(exemplar.filtered_attributes.iter().map(|a| a.key.as_str())); + } + let n = exemplars.len(); + field("exemplars".len(), heap_bytes(n * VALUE_BYTES)) + + fields + + keys.len() * (ENTRY_BYTES + n * VALUE_BYTES) +} + +fn array_field(key: &str, len: usize) -> usize { + field(key.len(), heap_bytes(len * VALUE_BYTES)) +} + +fn buckets_bytes(prefix: &str, buckets: Option<&Buckets>) -> usize { + buckets.map_or(0, |buckets| { + field(prefix.len() + "_offset".len(), 0) + + field( + prefix.len() + "_bucket_count".len(), + heap_bytes(buckets.bucket_counts.len() * VALUE_BYTES), + ) + }) +} + +fn temporality_bytes() -> usize { + num_field("aggregation_temporality") + str_field("aggregation_temporality_description", 11) +} + +/// Own fields every data point row has, whatever its type +fn point_common(attributes: &[KeyValue]) -> usize { + attributes_bytes(attributes, 0) + + timestamp_field("start_time_unix_nano") + + timestamp_field("time_unix_nano") +} + +/// Rows and bytes of the data points of one metric, and the count of points +fn metric_points(metric: &Metric, flatten_exemplars: bool, row: usize, size: &mut RequestSize) { + let flags = num_field("data_point_flags") + str_field("data_point_flags_description", 22); + let mut points = |own: usize| { + size.add_rows(1, row); + size.add_bytes(own); + size.points += 1; + }; + let count = match &metric.data { + None => return, + Some(metric::Data::Gauge(gauge)) => { + for dp in &gauge.data_points { + points( + point_common(&dp.attributes) + + exemplars_bytes(&dp.exemplars, flatten_exemplars) + + flags + + num_field("data_point_value"), + ); + } + gauge.data_points.len() + } + Some(metric::Data::Sum(sum)) => { + for dp in &sum.data_points { + points( + point_common(&dp.attributes) + + exemplars_bytes(&dp.exemplars, flatten_exemplars) + + flags + + num_field("data_point_value") + + temporality_bytes() + + num_field("is_monotonic"), + ); + } + sum.data_points.len() + } + Some(metric::Data::Histogram(histogram)) => { + for dp in &histogram.data_points { + points( + point_common(&dp.attributes) + + num_field("data_point_count") + + num_field("data_point_sum") + + array_field("data_point_bucket_counts", dp.bucket_counts.len()) + + array_field("data_point_explicit_bounds", dp.explicit_bounds.len()) + + exemplars_bytes(&dp.exemplars, flatten_exemplars) + + flags + + num_field("data_point_min") + + num_field("data_point_max") + + temporality_bytes(), + ); + } + histogram.data_points.len() + } + Some(metric::Data::ExponentialHistogram(histogram)) => { + for dp in &histogram.data_points { + points( + point_common(&dp.attributes) + + num_field("data_point_count") + + num_field("data_point_sum") + + num_field("data_point_scale") + + num_field("data_point_zero_count") + + buckets_bytes("positive", dp.positive.as_ref()) + + buckets_bytes("negative", dp.negative.as_ref()) + + exemplars_bytes(&dp.exemplars, flatten_exemplars) + + temporality_bytes(), + ); + } + histogram.data_points.len() + } + Some(metric::Data::Summary(summary)) => { + for dp in &summary.data_points { + let n = dp.quantile_values.len(); + points( + point_common(&dp.attributes) + + num_field("data_point_count") + + num_field("data_point_sum") + + array_field("data_point_quantile_values", n) + // Two fields per quantile, then a column table of two keys + + n * 2 * field("quantile".len(), 0) + + if n > 0 { + 2 * (ENTRY_BYTES + n * VALUE_BYTES) + } else { + 0 + }, + ); + } + summary.data_points.len() + } + }; + if count == 0 { + // The one row of a metric that has data but no data points + size.add_rows(1, row); + size.add_bytes(temporality_bytes() + num_field("is_monotonic")); + } +} + +/// Rows and row bytes of a metrics request +pub fn metrics_size(resource_metrics: &[ResourceMetrics], flatten_exemplars: bool) -> RequestSize { + let mut size = RequestSize::default(); + for resource_metric in resource_metrics { + // Built once per resource, as the flattener does, since the identity is + // read from the flattened resource fields + let identity = super::metrics::ResourceMetricFields::new( + resource_metric.resource.as_ref(), + &resource_metric.schema_url, + ) + .has_target_identity(); + let resource = resource_bytes(resource_metric.resource.as_ref()) + + str_field("resource_schema_url", resource_metric.schema_url.len()) + + if identity { + str_field("job", 32) + str_field("instance", 32) + } else { + 0 + }; + let mut any_rows = false; + for scope_metric in &resource_metric.scope_metrics { + let envelope = resource + + scope_bytes(scope_metric.scope.as_ref()) + + str_field("scope_schema_url", scope_metric.schema_url.len()); + size.records += scope_metric.metrics.len() as u64; + for metric in &scope_metric.metrics { + let row = VALUE_BYTES + + envelope + + str_field("metric_name", metric.name.len()) + + str_field("metric_description", metric.description.len()) + + str_field("metric_unit", metric.unit.len()) + + str_field("metric_type", 21) + + attributes_bytes(&metric.metadata, 0) + + num_field(super::metrics::SERIES_HASH_COLUMN); + any_rows |= metric.data.is_some(); + metric_points(metric, flatten_exemplars, row, &mut size); + } + } + if identity && any_rows { + // target_info + size.add_rows( + 1, + VALUE_BYTES + + resource + + 6 * str_field("metric_description", 16) + + num_field(super::metrics::SERIES_HASH_COLUMN), + ); + } + } + size +} diff --git a/src/otel/logs.rs b/src/otel/logs.rs index c9a129215..cf3c52e12 100644 --- a/src/otel/logs.rs +++ b/src/otel/logs.rs @@ -1130,9 +1130,10 @@ mod tests { ExportLogsServiceRequest { resource_logs } } - /// What ingestion does with a decoded request before staging: the rows - /// handed over in chunks (collected here) + /// What ingestion does with a decoded request before staging: the sizing + /// pass, then the rows handed over in chunks (collected here) fn flatten(request: &ExportLogsServiceRequest) -> Vec { + std::hint::black_box(crate::otel::expansion::logs_size(&request.resource_logs)); let mut budget = FlattenBudget::new(FlattenLimits::DEFAULT); bench::chunked(|chunker| { super::super::flatten_logs_into(&request.resource_logs, &mut budget, chunker) diff --git a/src/otel/memory_tests.rs b/src/otel/memory_tests.rs index a5de0976f..91b7bcf0f 100644 --- a/src/otel/memory_tests.rs +++ b/src/otel/memory_tests.rs @@ -527,14 +527,22 @@ fn row_estimate_tracks_allocated_memory() { .iter() .map(|row| row_bytes(row.as_object().unwrap())) .sum(); + let sizing = crate::otel::expansion::logs_size(&request.resource_logs); let ratio = allocated.retained as f64 / estimate as f64; println!( - "MEMORY row estimate, {name}: {} rows, allocated {} B, estimated {} B, allocated/estimated {:.2}", + "MEMORY row estimate, {name}: {} rows, allocated {} B, estimated {} B, allocated/estimated {:.2}, sizing pass {} B ({:.2} of estimated)", rows.len(), allocated.retained, estimate, ratio, + sizing.bytes, + sizing.bytes as f64 / estimate as f64 ); assert!((0.5..=2.0).contains(&ratio), "{name}: {ratio:.2}"); + let sizing_ratio = sizing.bytes as f64 / estimate as f64; + assert!( + (0.5..=2.0).contains(&sizing_ratio), + "{name}: {sizing_ratio:.2}" + ); } } diff --git a/src/otel/metrics.rs b/src/otel/metrics.rs index 10e675352..0233a49d6 100644 --- a/src/otel/metrics.rs +++ b/src/otel/metrics.rs @@ -776,6 +776,12 @@ impl ResourceMetricFields { envelope } + /// Whether the rows of this resource get Prometheus `job` and `instance` + /// labels, and the resource a `target_info` row + pub fn has_target_identity(&self) -> bool { + self.target_identity.is_some() + } + /// The `target_info` row of this resource, at the latest data point /// timestamp of its rows, if it has a Prometheus target identity pub fn target_info(&self, latest: Option) -> Option> { @@ -1702,9 +1708,13 @@ mod tests { ExportMetricsServiceRequest { resource_metrics } } - /// What ingestion does with a decoded request before staging: the rows - /// handed over in chunks (collected here) + /// What ingestion does with a decoded request before staging: the sizing + /// pass, then the rows handed over in chunks (collected here) fn flatten(request: &ExportMetricsServiceRequest) -> Vec { + std::hint::black_box(crate::otel::expansion::metrics_size( + &request.resource_metrics, + false, + )); bench::chunked(|chunker| { super::super::flatten_metrics_into(&request.resource_metrics, false, chunker) }) diff --git a/src/otel/traces.rs b/src/otel/traces.rs index 588ab1271..74ea63b55 100644 --- a/src/otel/traces.rs +++ b/src/otel/traces.rs @@ -1336,9 +1336,10 @@ mod tests { ExportTraceServiceRequest { resource_spans } } - /// What ingestion does with a decoded request before staging: the rows - /// handed over in chunks (collected here) + /// What ingestion does with a decoded request before staging: the sizing + /// pass, then the rows handed over in chunks (collected here) fn flatten(request: &ExportTraceServiceRequest) -> Vec { + std::hint::black_box(crate::otel::expansion::traces_size(&request.resource_spans)); bench::chunked(|chunker| { super::super::flatten_traces_into(&request.resource_spans, chunker) }) From fce3183964913b5b9e59ab4bfef91e707577248a Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Mon, 23 Nov 2026 22:58:52 -0600 Subject: [PATCH 05/31] fix(otel): refuse an OTLP request whose rows would expand past 1024x the payload limit Chunking bounds memory, not what a request writes to staging: 500 resource attributes over 262,144 empty records (0.5 MiB) expand to 23.7 GiB of rows. The sizing pass now refuses, with 400 and before anything is staged, a request whose estimated rows exceed 1024 x P_MAX_EVENT_PAYLOAD_SIZE (10 GiB at the default). Realistic requests at the payload limit expand to at most 459x (short log records or bare gauge points under 30 Kubernetes resource attributes); every measured shape is accepted (realistic_tests). Co-Authored-By: Claude Opus 5.5 --- src/handlers/http/modal/utils/ingest_utils.rs | 20 +- src/otel.rs | 2 + src/otel/expansion.rs | 17 + src/otel/realistic_tests.rs | 581 ++++++++++++++++++ 4 files changed, 619 insertions(+), 1 deletion(-) create mode 100644 src/otel/realistic_tests.rs diff --git a/src/handlers/http/modal/utils/ingest_utils.rs b/src/handlers/http/modal/utils/ingest_utils.rs index dd82a4b5b..58f83d237 100644 --- a/src/handlers/http/modal/utils/ingest_utils.rs +++ b/src/handlers/http/modal/utils/ingest_utils.rs @@ -42,6 +42,7 @@ use crate::{ error::EventError, format::{EventFormat, LogSource, json}, }, + handlers::http::max_event_payload_size, handlers::{ CONTENT_TYPE_JSON, CONTENT_TYPE_PROTOBUF, EXTRACT_LOG_KEY, LOG_SOURCE_KEY, STREAM_NAME_HEADER_KEY, TelemetryType, @@ -55,7 +56,9 @@ use crate::{ increment_traces_collected_by_date, }, otel::{ - expansion::{RequestSize, logs_size, metrics_size, traces_size}, + expansion::{ + EXPANSION_FACTOR, RequestSize, logs_size, max_expanded_bytes, metrics_size, traces_size, + }, logs::flatten_logs_into, metrics::flatten_metrics_into, otel_utils::deserialize_otel_json, @@ -390,6 +393,20 @@ impl OtelResources<'_> { } } +/// Refuses a request whose rows would hold more than `max_expanded_bytes` of the +/// payload limit, before anything is staged +fn check_expansion(size: &RequestSize, max_payload: usize) -> Result<(), PostError> { + let max = max_expanded_bytes(max_payload); + if size.bytes > max { + return Err(PostError::Invalid(anyhow::anyhow!( + "The request would expand to {} rows holding about {} bytes, more than the {max} bytes allowed ({EXPANSION_FACTOR} times P_MAX_EVENT_PAYLOAD_SIZE). Split the batch into smaller requests, or send fewer resource, scope and span attributes per record", + size.rows, + size.bytes, + ))); + } + Ok(()) +} + /// Stages the rows of one decoded OTEL request in chunks (see `Chunker`), so /// that its rows are never all held at once. /// @@ -410,6 +427,7 @@ fn ingest_otel_resources( verify_dataset_fields_count(target.stream_name, target.tenant_id)?; let flatten_exemplars = PARSEABLE.options.otel_flatten_exemplars; let size = resources.size(flatten_exemplars); + check_expansion(&size, max_event_payload_size())?; // The JSON log bodies of every record of the request share one budget let mut budget = FlattenBudget::new(FlattenLimits::from_config()); diff --git a/src/otel.rs b/src/otel.rs index 39d52d764..423f68cc8 100644 --- a/src/otel.rs +++ b/src/otel.rs @@ -25,6 +25,8 @@ pub mod traces; #[cfg(test)] mod memory_tests; +#[cfg(test)] +mod realistic_tests; /// Shared driver for the release-profile micro-benchmarks. Each benchmark is an /// `#[ignore]`d test that never touches the `PARSEABLE` global, so it can be run diff --git a/src/otel/expansion.rs b/src/otel/expansion.rs index 01087678c..74523f766 100644 --- a/src/otel/expansion.rs +++ b/src/otel/expansion.rs @@ -72,6 +72,23 @@ impl RequestSize { } } +/// Estimated bytes of rows one request may expand to, for a payload limit of +/// `max_payload` bytes: `EXPANSION_FACTOR` row bytes per payload byte +pub fn max_expanded_bytes(max_payload: usize) -> u64 { + (max_payload as u64).saturating_mul(EXPANSION_FACTOR) +} + +/// Row bytes per payload byte a request may expand to. The most measured for a +/// request shaped like collector traffic is 459: short log records (a time, a +/// severity and a two-byte body) or bare gauge points under 30 Kubernetes resource +/// attributes; k8s logs, spans and metrics with ordinary records expand 40-110x +/// (`realistic_tests`). 1024 leaves 2.2x headroom over the worst of them, and +/// refuses the requests that copy kilobytes of shared fields into millions of +/// records of a few bytes (47,000 row bytes per body byte for 500 attributes over +/// empty records, `copied_fields_over_tiny_records_are_over_the_expansion_cap`), at 10 GiB of +/// rows for the default 10 MiB payload limit. +pub const EXPANSION_FACTOR: u64 = 1024; + /// Timestamps are formatted as `%Y-%m-%dT%H:%M:%S%.9fZ` const TIMESTAMP_LEN: usize = 30; /// Longest decimal `i64` diff --git a/src/otel/realistic_tests.rs b/src/otel/realistic_tests.rs new file mode 100644 index 000000000..c0522621d --- /dev/null +++ b/src/otel/realistic_tests.rs @@ -0,0 +1,581 @@ +/* + * Parseable Server (C) 2022 - 2025 Parseable, Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + */ + +//! Requests shaped like real collector traffic, at the default payload limit: +//! what they expand to per body byte (the numbers behind `EXPANSION_FACTOR`), +//! and that the expansion cap accepts every one of them. Nothing here touches +//! `PARSEABLE`. `OTLP_DUMP_DIR=` makes the ignored `dump_realistic_bodies` +//! write the bodies for end-to-end checks against a server. + +use opentelemetry_proto::tonic::collector::logs::v1::ExportLogsServiceRequest; +use opentelemetry_proto::tonic::collector::metrics::v1::ExportMetricsServiceRequest; +use opentelemetry_proto::tonic::collector::trace::v1::ExportTraceServiceRequest; +use opentelemetry_proto::tonic::common::v1::{AnyValue, InstrumentationScope, KeyValue, any_value}; +use opentelemetry_proto::tonic::logs::v1::{LogRecord, ResourceLogs, ScopeLogs}; +use opentelemetry_proto::tonic::metrics::v1::{ + Exemplar, ExponentialHistogram, ExponentialHistogramDataPoint, Gauge, Histogram, + HistogramDataPoint, Metric, NumberDataPoint, ResourceMetrics, ScopeMetrics, Sum, exemplar, + exponential_histogram_data_point::Buckets, metric, number_data_point, +}; +use opentelemetry_proto::tonic::resource::v1::Resource; +use opentelemetry_proto::tonic::trace::v1::{ResourceSpans, ScopeSpans, Span, Status, span}; +use prost::Message; + +use super::expansion::{RequestSize, logs_size, max_expanded_bytes, metrics_size, traces_size}; + +/// `P_MAX_EVENT_PAYLOAD_SIZE` default +const PAYLOAD: usize = 10 * 1024 * 1024; + +fn kv(key: &str, value: any_value::Value) -> KeyValue { + KeyValue { + key: key.into(), + value: Some(AnyValue { value: Some(value) }), + ..Default::default() + } +} + +fn s(key: &str, value: &str) -> KeyValue { + kv(key, any_value::Value::StringValue(value.into())) +} + +/// What the Kubernetes attributes processor and an SDK add to a resource +fn k8s_resource() -> Option { + Some(Resource { + attributes: vec![ + s("service.name", "checkout"), + s("service.namespace", "shop"), + s("service.version", "1.42.0"), + s( + "service.instance.id", + "6f1c0a52-8a4e-4c21-9a07-3b3c4e9b0d51", + ), + s("deployment.environment.name", "production"), + s("telemetry.sdk.name", "opentelemetry"), + s("telemetry.sdk.language", "java"), + s("telemetry.sdk.version", "1.44.1"), + s( + "telemetry.distro.name", + "opentelemetry-java-instrumentation", + ), + s("telemetry.distro.version", "2.10.0"), + s("host.name", "ip-10-0-12-34.eu-west-1.compute.internal"), + s("host.arch", "amd64"), + s("os.type", "linux"), + s("os.description", "Linux 6.1.112-124.190.amzn2023.x86_64"), + s("process.runtime.name", "OpenJDK Runtime Environment"), + s("process.runtime.version", "21.0.5+11-LTS"), + s("process.pid", "1"), + s( + "container.id", + "3c5a2d0f9b8e7a6c5d4e3f2a1b0c9d8e7f6a5b4c3d2e1f0a9b8c7d6e5f4a3b2c", + ), + s("container.name", "checkout"), + s("container.image.name", "registry.example.com/shop/checkout"), + s("container.image.tag", "1.42.0"), + s("k8s.cluster.name", "prod-eu-west-1"), + s("k8s.namespace.name", "shop"), + s("k8s.node.name", "ip-10-0-12-34.eu-west-1.compute.internal"), + s("k8s.pod.name", "checkout-7d9c8b6f5-x2x9q"), + s("k8s.pod.uid", "0b6e2c1a-4f3d-4e5b-8a9c-7d6e5f4a3b2c"), + s("k8s.deployment.name", "checkout"), + s("k8s.replicaset.name", "checkout-7d9c8b6f5"), + s("cloud.provider", "aws"), + s("cloud.region", "eu-west-1"), + ], + ..Default::default() + }) +} + +fn minimal_resource() -> Option { + Some(Resource { + attributes: vec![s("service.name", "checkout")], + ..Default::default() + }) +} + +fn scope(name: &str) -> Option { + Some(InstrumentationScope { + name: name.into(), + version: "2.10.0".into(), + ..Default::default() + }) +} + +const T0: u64 = 1_700_000_000_000_000_000; + +fn logs(resource: Option, records: Vec) -> ExportLogsServiceRequest { + ExportLogsServiceRequest { + resource_logs: vec![ResourceLogs { + resource, + scope_logs: vec![ScopeLogs { + scope: scope("com.example.checkout"), + log_records: records, + schema_url: String::new(), + }], + schema_url: "https://opentelemetry.io/schemas/1.24.0".into(), + }], + } +} + +fn app_log(i: usize) -> LogRecord { + LogRecord { + time_unix_nano: T0 + i as u64, + observed_time_unix_nano: T0 + 1 + i as u64, + severity_number: 9, + severity_text: "INFO".into(), + body: Some(AnyValue { + value: Some(any_value::Value::StringValue(format!( + "GET /api/v1/items/{i} completed with 200 in 12 ms" + ))), + }), + attributes: vec![ + s("code.function", "handle"), + s("thread.name", "http-nio-8080-exec-7"), + kv("http.response.status_code", any_value::Value::IntValue(200)), + ], + trace_id: vec![0xab; 16], + span_id: vec![0xcd; 8], + flags: 1, + ..Default::default() + } +} + +/// The smallest realistic log record: a time, a severity and a two-byte body +fn short_log(i: usize) -> LogRecord { + LogRecord { + time_unix_nano: T0 + i as u64, + severity_number: 9, + body: Some(AnyValue { + value: Some(any_value::Value::StringValue("ok".into())), + }), + ..Default::default() + } +} + +fn traces(resource: Option, spans: Vec) -> ExportTraceServiceRequest { + ExportTraceServiceRequest { + resource_spans: vec![ResourceSpans { + resource, + scope_spans: vec![ScopeSpans { + scope: scope("io.opentelemetry.tomcat-10.0"), + spans, + schema_url: String::new(), + }], + schema_url: String::new(), + }], + } +} + +fn server_span(i: usize) -> Span { + Span { + trace_id: vec![0xab; 16], + span_id: (i as u64).to_be_bytes().to_vec(), + parent_span_id: vec![0xef; 8], + name: "GET /api/v1/items/{id}".into(), + kind: 2, + start_time_unix_nano: T0 + i as u64, + end_time_unix_nano: T0 + 12_000_000 + i as u64, + attributes: vec![ + s("http.request.method", "GET"), + s("url.path", &format!("/api/v1/items/{i}")), + kv("http.response.status_code", any_value::Value::IntValue(200)), + s("server.address", "checkout.shop.svc.cluster.local"), + ], + status: Some(Status::default()), + ..Default::default() + } +} + +/// The smallest realistic span: ids, a name and its times +fn bare_span(i: usize) -> Span { + Span { + trace_id: vec![0xab; 16], + span_id: (i as u64).to_be_bytes().to_vec(), + name: "query".into(), + start_time_unix_nano: T0 + i as u64, + end_time_unix_nano: T0 + 1000 + i as u64, + ..Default::default() + } +} + +/// A span with an exception event and a link, as instrumentations record them +fn span_with_event(i: usize) -> Span { + Span { + events: vec![span::Event { + time_unix_nano: T0 + 5 + i as u64, + name: "exception".into(), + attributes: vec![ + s("exception.type", "java.io.IOException"), + s("exception.message", "Connection reset by peer"), + ], + ..Default::default() + }], + links: vec![span::Link { + trace_id: vec![0x12; 16], + span_id: vec![0x34; 8], + ..Default::default() + }], + ..server_span(i) + } +} + +fn metrics(resource: Option, metrics: Vec) -> ExportMetricsServiceRequest { + ExportMetricsServiceRequest { + resource_metrics: vec![ResourceMetrics { + resource, + scope_metrics: vec![ScopeMetrics { + scope: scope("io.opentelemetry.runtime-telemetry-java17"), + metrics, + schema_url: String::new(), + }], + schema_url: String::new(), + }], + } +} + +fn sum_points(points: usize) -> Vec { + vec![Metric { + name: "jvm.memory.used".into(), + description: "Measure of memory used.".into(), + unit: "By".into(), + data: Some(metric::Data::Sum(Sum { + data_points: (0..points) + .map(|i| NumberDataPoint { + attributes: vec![ + s("jvm.memory.pool.name", "G1 Eden Space"), + s("jvm.memory.type", "heap"), + ], + start_time_unix_nano: T0, + time_unix_nano: T0 + 60_000_000_000 + i as u64, + value: Some(number_data_point::Value::AsInt(123_456_789 + i as i64)), + ..Default::default() + }) + .collect(), + aggregation_temporality: 2, + is_monotonic: false, + })), + ..Default::default() + }] +} + +/// The smallest realistic data point: a time and a value +fn bare_gauge_points(points: usize) -> Vec { + vec![Metric { + name: "up".into(), + data: Some(metric::Data::Gauge(Gauge { + data_points: (0..points) + .map(|i| NumberDataPoint { + time_unix_nano: T0 + i as u64, + value: Some(number_data_point::Value::AsDouble(1.0)), + ..Default::default() + }) + .collect(), + })), + ..Default::default() + }] +} + +/// Explicit-bucket histograms with the SDK's 16 default bounds and one exemplar +fn histogram_points(points: usize) -> Vec { + vec![Metric { + name: "http.server.request.duration".into(), + unit: "s".into(), + data: Some(metric::Data::Histogram(Histogram { + data_points: (0..points) + .map(|i| HistogramDataPoint { + attributes: vec![ + s("http.request.method", "GET"), + s("http.route", "/api/v1/items/{id}"), + kv("http.response.status_code", any_value::Value::IntValue(200)), + ], + start_time_unix_nano: T0, + time_unix_nano: T0 + 60_000_000_000 + i as u64, + count: 1000, + sum: Some(12.5), + bucket_counts: (0..16).map(|b| b * 3).collect(), + explicit_bounds: vec![ + 0.0, 0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1.0, 2.5, 5.0, + 7.5, 10.0, + ], + exemplars: vec![Exemplar { + time_unix_nano: T0 + i as u64, + trace_id: vec![0xab; 16], + span_id: vec![0xcd; 8], + value: Some(exemplar::Value::AsDouble(0.012)), + ..Default::default() + }], + min: Some(0.001), + max: Some(1.2), + ..Default::default() + }) + .collect(), + aggregation_temporality: 2, + })), + ..Default::default() + }] +} + +/// Exponential histograms with 160 small buckets on each side (the SDK maximum) +fn exp_histogram_points(points: usize) -> Vec { + vec![Metric { + name: "http.server.duration".into(), + data: Some(metric::Data::ExponentialHistogram(ExponentialHistogram { + data_points: (0..points) + .map(|i| ExponentialHistogramDataPoint { + attributes: vec![s("http.route", "/api/v1/items")], + start_time_unix_nano: T0, + time_unix_nano: T0 + i as u64, + count: 1000, + sum: Some(12.5), + scale: 3, + positive: Some(Buckets { + offset: -10, + bucket_counts: (0..160).map(|b| b % 100).collect(), + }), + negative: Some(Buckets { + offset: -10, + bucket_counts: (0..160).map(|b| b % 7).collect(), + }), + ..Default::default() + }) + .collect(), + aggregation_temporality: 2, + })), + ..Default::default() + }] +} + +/// One realistic request, built to fill most of the payload limit +pub(crate) struct Shape { + pub name: &'static str, + pub signal: &'static str, + pub body: Vec, + pub size: RequestSize, +} + +/// Records of `one` bytes each that fit in `PAYLOAD`, with room for framing +fn fitting(one: usize) -> usize { + (PAYLOAD - 64 * 1024) / one +} + +fn shape( + name: &'static str, + signal: &'static str, + build: impl Fn(usize) -> M, + size: impl Fn(&M) -> RequestSize, +) -> Shape { + let probe = build(1000).encoded_len(); + let mut n = fitting(probe.div_ceil(1000)); + let mut request = build(n); + // Records can grow with their index + while request.encoded_len() > PAYLOAD - 16 * 1024 { + n = n * 99 / 100; + request = build(n); + } + let body = request.encode_to_vec(); + let size = size(&request); + Shape { + name, + signal, + body, + size, + } +} + +pub(crate) fn shapes() -> Vec { + let logs_size = |r: &ExportLogsServiceRequest| logs_size(&r.resource_logs); + let traces_size = |r: &ExportTraceServiceRequest| traces_size(&r.resource_spans); + let metrics_size = |r: &ExportMetricsServiceRequest| metrics_size(&r.resource_metrics, false); + vec![ + shape( + "logs, 30 k8s resource attributes", + "logs", + |n| logs(k8s_resource(), (0..n).map(app_log).collect()), + logs_size, + ), + shape( + "logs, service.name only", + "logs", + |n| logs(minimal_resource(), (0..n).map(app_log).collect()), + logs_size, + ), + shape( + "logs, short records (time, severity, body \"ok\")", + "logs", + |n| logs(None, (0..n).map(short_log).collect()), + logs_size, + ), + shape( + "logs, short records, 30 k8s resource attributes", + "logs", + |n| logs(k8s_resource(), (0..n).map(short_log).collect()), + logs_size, + ), + shape( + "traces, 30 k8s resource attributes", + "traces", + |n| traces(k8s_resource(), (0..n).map(server_span).collect()), + traces_size, + ), + shape( + "traces, service.name only", + "traces", + |n| traces(minimal_resource(), (0..n).map(server_span).collect()), + traces_size, + ), + shape( + "traces, bare spans (ids, name, times)", + "traces", + |n| traces(minimal_resource(), (0..n).map(bare_span).collect()), + traces_size, + ), + shape( + "traces, bare spans, 30 k8s resource attributes", + "traces", + |n| traces(k8s_resource(), (0..n).map(bare_span).collect()), + traces_size, + ), + shape( + "traces, an event and a link per span, k8s", + "traces", + |n| traces(k8s_resource(), (0..n).map(span_with_event).collect()), + traces_size, + ), + shape( + "metrics, sum points, 30 k8s resource attributes", + "metrics", + |n| metrics(k8s_resource(), sum_points(n)), + metrics_size, + ), + shape( + "metrics, sum points, service.name only", + "metrics", + |n| metrics(minimal_resource(), sum_points(n)), + metrics_size, + ), + shape( + "metrics, bare gauge points (time, value)", + "metrics", + |n| metrics(minimal_resource(), bare_gauge_points(n)), + metrics_size, + ), + shape( + "metrics, bare gauge points, 30 k8s resource attributes", + "metrics", + |n| metrics(k8s_resource(), bare_gauge_points(n)), + metrics_size, + ), + shape( + "metrics, histograms with an exemplar, k8s", + "metrics", + |n| metrics(k8s_resource(), histogram_points(n)), + metrics_size, + ), + shape( + "metrics, exponential histograms, 160 buckets", + "metrics", + |n| metrics(minimal_resource(), exp_histogram_points(n)), + metrics_size, + ), + ] +} + +/// Every realistic shape at the payload limit is under the expansion cap +#[test] +fn realistic_requests_at_the_payload_limit_are_under_the_expansion_cap() { + let cap = max_expanded_bytes(PAYLOAD); + let mut worst: f64 = 0.0; + for shape in shapes() { + let ratio = shape.size.bytes as f64 / shape.body.len() as f64; + worst = worst.max(ratio); + println!( + "EXPANSION {}: body {:.2} MiB, {} records, {} rows, {:.0} row bytes per row, {:.1} row bytes per body byte ({:.0}% of the cap)", + shape.name, + shape.body.len() as f64 / (1024.0 * 1024.0), + shape.size.records, + shape.size.rows, + shape.size.bytes as f64 / shape.size.rows as f64, + ratio, + 100.0 * shape.size.bytes as f64 / cap as f64 + ); + assert!(shape.size.bytes <= cap, "{} is refused", shape.name); + } + println!( + "EXPANSION worst {worst:.1} row bytes per body byte, cap {} per body byte", + cap / PAYLOAD as u64 + ); +} + +/// Copied fields that no collector sends: a 15 KB resource over empty records of +/// two bytes each, which expand to tens of GiB of rows, are refused +#[test] +fn copied_fields_over_tiny_records_are_over_the_expansion_cap() { + let resource = Some(Resource { + attributes: (0..500) + .map(|i| s(&format!("attribute.{i:03}"), "value-0123456789")) + .collect(), + ..Default::default() + }); + // Half a MiB of protobuf + let records = 1 << 18; + let request = logs(resource, vec![LogRecord::default(); records]); + let size = logs_size(&request.resource_logs); + println!( + "EXPANSION copied resource: {} records, {:.1} GiB of rows", + size.records, + size.bytes as f64 / (1u64 << 30) as f64 + ); + assert!(request.encoded_len() <= PAYLOAD); + assert!(size.bytes > max_expanded_bytes(PAYLOAD)); +} + +/// Writes the body of every shape to `OTLP_DUMP_DIR`, named after its signal +/// and position, for end-to-end checks against a server +#[test] +#[ignore = "writes request bodies for an end-to-end check"] +fn dump_realistic_bodies() { + let dir = std::env::var("OTLP_DUMP_DIR").expect("OTLP_DUMP_DIR"); + let mut index = String::new(); + for (i, shape) in shapes().into_iter().enumerate() { + let file = format!("{i:02}-{}.pb", shape.signal); + std::fs::write(format!("{dir}/{file}"), &shape.body).unwrap(); + index.push_str(&format!( + "{file}\t{}\t{}\t{}\t{}\n", + shape.signal, shape.size.records, shape.size.points, shape.name + )); + } + // Requests of 100 records, as an SDK or a collector with a small batch sends them + let small: [(&str, Vec); 3] = [ + ( + "logs", + logs(k8s_resource(), (0..100).map(app_log).collect()).encode_to_vec(), + ), + ( + "traces", + traces(k8s_resource(), (0..100).map(server_span).collect()).encode_to_vec(), + ), + ( + "metrics", + metrics(k8s_resource(), sum_points(100)).encode_to_vec(), + ), + ]; + for (signal, body) in small { + std::fs::write(format!("{dir}/small-{signal}.pb"), body).unwrap(); + } + std::fs::write(format!("{dir}/index.tsv"), index).unwrap(); +} From e35071e0854c5d0efd8d831fcd8dec20b9a386f8 Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Mon, 23 Nov 2026 22:58:55 -0600 Subject: [PATCH 06/31] fix(otel): size metric, exemplar, key-value list and array maps by the values inserted Data point, exemplar, metadata and resource maps of metrics, the temporary maps of flatten_attributes and key-value lists, and the Vec of array values were sized by the raw count of entries in the request, including entries without a value (two bytes each on the wire, skipped when rows are built). 50,000 of them reserved about 5.5 MB per map. They are now sized like attribute_capacity: entries with a value, capped at 128. Co-Authored-By: Claude Opus 5.5 --- src/otel/metrics.rs | 20 +++++++++----------- src/otel/otel_utils.rs | 16 +++++++++++++--- 2 files changed, 22 insertions(+), 14 deletions(-) diff --git a/src/otel/metrics.rs b/src/otel/metrics.rs index 0233a49d6..dd9c953ab 100644 --- a/src/otel/metrics.rs +++ b/src/otel/metrics.rs @@ -37,7 +37,7 @@ use crate::metrics::increment_metrics_collected_by_date; use crate::parseable::PARSEABLE; use super::otel_utils::{ - convert_epoch_nano_to_timestamp, insert_attributes, insert_number_if_some, + attribute_capacity, convert_epoch_nano_to_timestamp, insert_attributes, insert_number_if_some, }; use super::sink::RowSink; @@ -233,7 +233,8 @@ fn exemplar_value_to_json(value: &ExemplarValue) -> Value { /// names match the legacy flat columns, so switching representations via the /// flag changes only the shape, not the field names. fn exemplar_to_json(exemplar: &Exemplar) -> Value { - let mut exemplar_json = Map::with_capacity(exemplar.filtered_attributes.len() + 4); + let mut exemplar_json = + Map::with_capacity(attribute_capacity(&exemplar.filtered_attributes) + 4); insert_attributes(&mut exemplar_json, &exemplar.filtered_attributes); exemplar_json.insert( "exemplar_time_unix_nano".to_string(), @@ -302,7 +303,7 @@ fn number_data_point_row( data_point: &NumberDataPoint, flatten_exemplars: bool, ) -> Map { - let mut data_point_json = Map::with_capacity(data_point.attributes.len() + 8); + let mut data_point_json = Map::with_capacity(attribute_capacity(&data_point.attributes) + 8); insert_attributes(&mut data_point_json, &data_point.attributes); data_point_json.insert( "start_time_unix_nano".to_string(), @@ -363,7 +364,7 @@ fn histogram_data_point_row( data_point: &HistogramDataPoint, flatten_exemplars: bool, ) -> Map { - let mut data_point_json = Map::with_capacity(data_point.attributes.len() + 10); + let mut data_point_json = Map::with_capacity(attribute_capacity(&data_point.attributes) + 10); insert_attributes(&mut data_point_json, &data_point.attributes); data_point_json.insert( "start_time_unix_nano".to_string(), @@ -446,7 +447,7 @@ fn exp_histogram_data_point_row( data_point: &ExponentialHistogramDataPoint, flatten_exemplars: bool, ) -> Map { - let mut data_point_json = Map::with_capacity(data_point.attributes.len() + 12); + let mut data_point_json = Map::with_capacity(attribute_capacity(&data_point.attributes) + 12); insert_attributes(&mut data_point_json, &data_point.attributes); data_point_json.insert( "start_time_unix_nano".to_string(), @@ -497,7 +498,7 @@ fn exp_histogram_data_point_row( /// The own fields of the row of one summary data point fn summary_data_point_row(data_point: &SummaryDataPoint) -> Map { - let mut data_point_json = Map::with_capacity(data_point.attributes.len() + 6); + let mut data_point_json = Map::with_capacity(attribute_capacity(&data_point.attributes) + 6); insert_attributes(&mut data_point_json, &data_point.attributes); data_point_json.insert( "start_time_unix_nano".to_string(), @@ -599,7 +600,7 @@ pub fn metric_rows( }; // Build metric-level fields once - let mut metadata = Map::with_capacity(metrics_record.metadata.len()); + let mut metadata = Map::with_capacity(attribute_capacity(&metrics_record.metadata)); insert_attributes(&mut metadata, &metrics_record.metadata); let fields = MetricFields { name: Value::String(metrics_record.name.clone()), @@ -715,10 +716,7 @@ impl ResourceMetricFields { pub fn new(resource: Option<&Resource>, schema_url: &str) -> Self { // Build resource-level fields once per resource let mut resource_fields = Map::with_capacity( - resource - .map(|resource| resource.attributes.len()) - .unwrap_or_default() - + 2, + resource.map_or(0, |resource| attribute_capacity(&resource.attributes)) + 2, ); if let Some(resource) = resource { insert_attributes(&mut resource_fields, &resource.attributes); diff --git a/src/otel/otel_utils.rs b/src/otel/otel_utils.rs index 5b6ed5616..c5a388896 100644 --- a/src/otel/otel_utils.rs +++ b/src/otel/otel_utils.rs @@ -138,7 +138,15 @@ fn insert_json_from_value(map: &mut Map, key: &str, value: OtelVa /// This handles nested array values and key-value lists by recursively /// converting them to JSON fn collect_json_from_array_value(array_value: &ArrayValue) -> Value { - let mut json_array = Vec::with_capacity(array_value.values.len()); + // Sized by the values that will be pushed, as `attribute_capacity` does for maps + let mut json_array = Vec::with_capacity( + array_value + .values + .iter() + .filter(|value| value.value.is_some()) + .take(ATTRIBUTE_CAPACITY_HINT_MAX) + .count(), + ); for value in &array_value.values { if let Some(val) = &value.value { match val { @@ -180,7 +188,8 @@ fn collect_json_from_array_value(array_value: &ArrayValue) -> Value { /// The function iterates through the key-value pairs in the list /// and collects their JSON representations into a single Map fn collect_json_from_key_value_list(key_value_list: KeyValueList) -> Map { - let mut kv_list_json: Map = Map::with_capacity(key_value_list.values.len()); + let mut kv_list_json: Map = + Map::with_capacity(attribute_capacity(&key_value_list.values)); for key_value in key_value_list.values { if let Some(val) = key_value.value { if let Some(val) = val.value { @@ -219,7 +228,8 @@ pub fn value_to_string(value: serde_json::Value) -> String { } pub fn flatten_attributes(attributes: &[KeyValue]) -> Map { - let mut attributes_json: Map = Map::with_capacity(attributes.len()); + let mut attributes_json: Map = + Map::with_capacity(attribute_capacity(attributes)); for attribute in attributes { if let Some(value) = &attribute.value && let Some(value) = value.value.clone() From f42f8d1dc1cec2ac270a174941451d3d2b1ce5b5 Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Mon, 23 Nov 2026 22:58:58 -0600 Subject: [PATCH 07/31] fix(otel): bound the memory a JSON text log body is parsed into, before parsing it Bodies were parsed into Values before anything was charged: a 10 MiB body {"a":[0,0,...]} peaked at 586 MiB. Text that could parse into more than what is left of 64 MiB (four chunks) for the record is first scanned without allocating, which yields its type and the memory parsing takes; text that is not an object is no longer parsed at all (its parse was discarded anyway), and an object that would take more is refused (LogBodyTooLarge, a 400 limit error). Typical JSON parses into about 8 bytes per byte, so bodies of several MiB are still accepted; small bodies take the old path unchanged. Co-Authored-By: Claude Opus 5.5 --- src/otel/logs.rs | 149 +++++++++++++++++++++++++++++++++++--- src/utils/json/flatten.rs | 5 ++ 2 files changed, 144 insertions(+), 10 deletions(-) diff --git a/src/otel/logs.rs b/src/otel/logs.rs index cf3c52e12..9b9062737 100644 --- a/src/otel/logs.rs +++ b/src/otel/logs.rs @@ -19,7 +19,7 @@ use super::otel_utils::attribute_capacity; use super::otel_utils::collect_json_from_values; use super::otel_utils::convert_epoch_nano_to_timestamp; use super::otel_utils::insert_attributes; -use super::sink::RowSink; +use super::sink::{CHUNK_LIMITS, ENTRY_BYTES, RowSink, VALUE_BYTES, heap_bytes}; use crate::metrics::increment_logs_collected_by_date; use crate::utils::json::flatten::{ FlattenBudget, FlattenCost, JsonFlattenError, expand_generic_flattening, flatten_pipeline_cost, @@ -174,6 +174,143 @@ fn category_from_body(body_str: &str) -> &'static str { .map_or("UNSPECIFIED", |(_, label)| *label) } +/// Most memory the JSON text bodies of one log record may be parsed into: four +/// chunks of rows. JSON text of typical logs parses into about 8 bytes per byte, +/// so a body of several MiB of such text is accepted. +pub const MAX_PARSED_BODY_BYTES: usize = 4 * CHUNK_LIMITS.bytes; + +/// Most bytes one byte of JSON text parses into: `0,` in an array is a 72 byte +/// `Value`, in a `Vec` that may have grown to twice its length +const PARSED_BYTES_PER_TEXT_BYTE: usize = 2 * VALUE_BYTES; + +/// Parses every body that is the JSON text of an object, as the fields of the +/// record are extracted from those only. Bodies are measured before they are +/// parsed: a body whose text could parse into more than what is left of +/// `MAX_PARSED_BODY_BYTES` is first scanned without allocating, which finds its +/// type and the memory parsing it takes. Text that is not an object is not parsed. +fn parse_json_object_bodies( + body_json: &Map, +) -> Result>, JsonFlattenError> { + let mut held = 0usize; + let mut parsed = Vec::with_capacity(body_json.len()); + for value in body_json.values() { + let Value::String(text) = value else { + parsed.push(None); + continue; + }; + let most = text.len().saturating_mul(PARSED_BYTES_PER_TEXT_BYTE); + if held.saturating_add(most) > MAX_PARSED_BODY_BYTES { + match json_object_text_bytes(text) { + // Not the JSON text of an object: not parsed, as before + None => { + parsed.push(None); + continue; + } + Some(bytes) => { + held = held.saturating_add(bytes); + if held > MAX_PARSED_BODY_BYTES { + return Err(JsonFlattenError::LogBodyTooLarge(MAX_PARSED_BODY_BYTES)); + } + } + } + } else { + held += most; + } + parsed.push( + serde_json::from_str::(text) + .ok() + .filter(Value::is_object), + ); + } + Ok(parsed) +} + +/// Memory `serde_json::from_str::(text)` takes when `text` is the JSON +/// text of an object, found without allocating; `None` for any other text +fn json_object_text_bytes(text: &str) -> Option { + use serde::de::{Deserialize, Deserializer, MapAccess, SeqAccess, Visitor}; + + /// Heap bytes of one parsed value, and whether it is an object + struct Parsed { + bytes: usize, + object: bool, + } + + impl Parsed { + fn scalar(bytes: usize) -> Self { + Self { + bytes, + object: false, + } + } + } + + impl<'de> Deserialize<'de> for Parsed { + fn deserialize>(deserializer: D) -> Result { + deserializer.deserialize_any(ParsedVisitor) + } + } + + struct ParsedVisitor; + + impl<'de> Visitor<'de> for ParsedVisitor { + type Value = Parsed; + + fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { + formatter.write_str("any JSON value") + } + fn visit_bool(self, _: bool) -> Result { + Ok(Parsed::scalar(0)) + } + fn visit_i64(self, _: i64) -> Result { + Ok(Parsed::scalar(0)) + } + fn visit_u64(self, _: u64) -> Result { + Ok(Parsed::scalar(0)) + } + fn visit_f64(self, _: f64) -> Result { + Ok(Parsed::scalar(0)) + } + fn visit_unit(self) -> Result { + Ok(Parsed::scalar(0)) + } + fn visit_str(self, s: &str) -> Result { + Ok(Parsed::scalar(heap_bytes(s.len()))) + } + fn visit_seq>(self, mut seq: A) -> Result { + let mut len = 0usize; + let mut bytes = 0usize; + while let Some(element) = seq.next_element::()? { + len += 1; + bytes = bytes.saturating_add(element.bytes); + } + // The `Vec` grows by doubling + Ok(Parsed::scalar(bytes.saturating_add(heap_bytes( + len.next_power_of_two().saturating_mul(VALUE_BYTES), + )))) + } + fn visit_map>(self, mut map: A) -> Result { + let mut bytes = 0usize; + while let Some(key) = map.next_key::()? { + let value = map.next_value::()?; + bytes = bytes + .saturating_add(ENTRY_BYTES) + .saturating_add(key.bytes) + .saturating_add(value.bytes); + } + Ok(Parsed { + bytes, + object: true, + }) + } + } + + let mut deserializer = serde_json::Deserializer::from_str(text); + let parsed = Parsed::deserialize(&mut deserializer).ok()?; + deserializer.end().ok()?; + parsed.object.then_some(parsed.bytes) +} + /// this function flattens the `LogRecord` object /// and returns a `Map` of the flattened json /// this function is called recursively for each log record object in the otel logs @@ -210,15 +347,7 @@ pub fn flatten_log_record( let body = &log_record.body; let body_json = collect_json_from_values(body, "body"); // Values that are strings which can be parsed as JSON objects get their fields extracted - let parsed_bodies: Vec> = body_json - .values() - .map(|value| match value { - Value::String(s) => serde_json::from_str::(s) - .ok() - .filter(Value::is_object), - _ => None, - }) - .collect(); + let parsed_bodies = parse_json_object_bodies(&body_json)?; // The rows of every parsed body are merged into this record, but they are all built // first, so charge all of them before building any let limits = budget.limits(); diff --git a/src/utils/json/flatten.rs b/src/utils/json/flatten.rs index 2bb68c4fa..acb8911c1 100644 --- a/src/utils/json/flatten.rs +++ b/src/utils/json/flatten.rs @@ -117,6 +117,10 @@ pub enum JsonFlattenError { "Flattening the request would produce more than {0} bytes of JSON (P_MAX_FLATTEN_BYTES_PER_REQUEST). Split the batch into smaller requests, or reduce the number or size of nested arrays in its events" )] BytesPerRequestLimitExceeded(usize), + #[error( + "A log body of JSON text would take more than {0} bytes of memory once parsed. Send it as a key-value list body, or split it over several records" + )] + LogBodyTooLarge(usize), } impl JsonFlattenError { @@ -128,6 +132,7 @@ impl JsonFlattenError { Self::RowsPerEventLimitExceeded(_) | Self::RowsPerRequestLimitExceeded(_) | Self::BytesPerRequestLimitExceeded(_) + | Self::LogBodyTooLarge(_) ) } } From c1cf0975591bc43c476b89b241b03475187772fc Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Mon, 23 Nov 2026 22:59:00 -0600 Subject: [PATCH 08/31] fix(json): charge the null cells of column tables built from arrays of objects Structural flattening turns an array of objects into one column per distinct key with a cell for every element, null where an element lacks the key; each null is a 72-byte Value. 3,600 exemplars with distinct keys held 13M of them, 890 MiB. The elements are now flattened first, and the null cells are charged to the request's flatten budget at 72 bytes each before the columns are built, so such a table is refused at the 64 MiB default. flatten() takes the budget. Co-Authored-By: Claude Opus 5.5 --- src/handlers/http/kinesis.rs | 14 +- src/handlers/http/logstream.rs | 10 +- src/otel/logs.rs | 14 +- src/otel/memory_tests.rs | 17 +- src/utils/json/flatten.rs | 504 ++++++++++++++++++++++++++++++--- src/utils/json/mod.rs | 4 + 6 files changed, 507 insertions(+), 56 deletions(-) diff --git a/src/handlers/http/kinesis.rs b/src/handlers/http/kinesis.rs index 7625a41a3..239ed50ac 100644 --- a/src/handlers/http/kinesis.rs +++ b/src/handlers/http/kinesis.rs @@ -376,8 +376,18 @@ mod tests { .iter() .map(|row| { let mut row = row.clone(); - crate::utils::json::flatten::flatten(&mut row, "_", None, None, None, false) - .unwrap(); + crate::utils::json::flatten::flatten( + &mut row, + "_", + None, + None, + None, + false, + &mut crate::utils::json::flatten::FlattenBudget::new( + crate::utils::json::flatten::GENEROUS_LIMITS, + ), + ) + .unwrap(); serde_json::to_vec(&row).unwrap().len() }) .sum(); diff --git a/src/handlers/http/logstream.rs b/src/handlers/http/logstream.rs index 7105f572f..a845ef3e6 100644 --- a/src/handlers/http/logstream.rs +++ b/src/handlers/http/logstream.rs @@ -150,7 +150,15 @@ pub async fn detect_schema(Json(json): Json) -> Result 3_600 * 3_600 * 72); assert!(result.is_err()); assert!(allocated.peak < PEAK_BOUND, "peak {} B", allocated.peak); } diff --git a/src/utils/json/flatten.rs b/src/utils/json/flatten.rs index acb8911c1..77cbeb50e 100644 --- a/src/utils/json/flatten.rs +++ b/src/utils/json/flatten.rs @@ -147,6 +147,7 @@ pub fn flatten( time_partition_limit: Option, custom_partition: Option<&String>, validation_required: bool, + budget: &mut FlattenBudget, ) -> Result<(), JsonFlattenError> { match nested_value { Value::Object(nested_dict) => { @@ -161,7 +162,7 @@ pub fn flatten( } let original = std::mem::take(nested_dict); let mut map = Map::with_capacity(original.len()); - flatten_object(&mut map, None, original, separator)?; + flatten_object(&mut map, None, original, separator, budget)?; *nested_dict = map; } Value::Array(arr) => { @@ -174,6 +175,7 @@ pub fn flatten( time_partition_limit, custom_partition, validation_required, + budget, )?; } } @@ -316,6 +318,7 @@ fn flatten_object( parent_key: Option<&str>, nested_map: Map, separator: &str, + budget: &mut FlattenBudget, ) -> Result<(), JsonFlattenError> { for (key, mut value) in nested_map { let new_key = match parent_key { @@ -326,10 +329,10 @@ fn flatten_object( match &mut value { Value::Object(obj) => { let obj = std::mem::take(obj); - flatten_object(output_map, Some(&new_key), obj, separator)?; + flatten_object(output_map, Some(&new_key), obj, separator, budget)?; } Value::Array(arr) if arr.iter().any(Value::is_object) => { - flatten_array_objects(output_map, &new_key, arr, separator)?; + flatten_array_objects(output_map, &new_key, arr, separator, budget)?; } _ => { output_map.insert(new_key, value); @@ -339,21 +342,58 @@ fn flatten_object( Ok(()) } -// Flattens a nested JSON Array into the parent Map +// Flattens a nested JSON Array into the parent Map: one column (array) per distinct key of +// its objects, with a cell for every element, null where an element lacks the key. Every +// null cell is a `Value` of its own, so the cells added are charged to `budget` at that +// size before the columns are built: 3,600 objects with one distinct key each would +// otherwise hold 13 million cells, about 900 MiB. pub fn flatten_array_objects( output_map: &mut Map, parent_key: &str, arr: &mut [Value], separator: &str, + budget: &mut FlattenBudget, ) -> Result<(), JsonFlattenError> { - let mut columns: BTreeMap> = BTreeMap::new(); - - for (index, value) in arr.iter_mut().enumerate() { + // Each element flattened on its own first, to count the cells of the table + let mut elements: Vec>> = Vec::with_capacity(arr.len()); + let mut keys: BTreeMap<&str, ()> = BTreeMap::new(); + let mut present = 0usize; + for value in arr.iter_mut() { match value { Value::Object(nested_object) => { let mut output_map = Map::new(); let nested_object = std::mem::take(nested_object); - flatten_object(&mut output_map, Some(parent_key), nested_object, separator)?; + flatten_object( + &mut output_map, + Some(parent_key), + nested_object, + separator, + budget, + )?; + present += output_map.len(); + elements.push(Some(output_map)); + } + Value::Null => elements.push(None), + _ => return Err(JsonFlattenError::NonObjectInArray), + } + } + for element in elements.iter().flatten() { + keys.extend(element.keys().map(|key| (key.as_str(), ()))); + } + let nulls = keys + .len() + .saturating_mul(elements.len()) + .saturating_sub(present); + budget.charge_event(FlattenCost { + rows: 0, + bytes: nulls.saturating_mul(std::mem::size_of::()), + })?; + drop(keys); + + let mut columns: BTreeMap> = BTreeMap::new(); + for (index, element) in elements.into_iter().enumerate() { + match element { + Some(output_map) => { for (key, value) in output_map { let column = columns .entry(key) @@ -361,12 +401,11 @@ pub fn flatten_array_objects( column.push(value); } } - Value::Null => { + None => { for column in columns.values_mut() { column.push(Value::Null); } } - _ => return Err(JsonFlattenError::NonObjectInArray), } // Ensure all columns are extended with null values if they weren't updated in this iteration @@ -1528,7 +1567,10 @@ mod tests { Some(&key), std::num::NonZeroU32::new(1), None, - true + true, + &mut crate::utils::json::flatten::FlattenBudget::new( + crate::utils::json::flatten::GENEROUS_LIMITS + ) ), Err(JsonFlattenError::TimestampTooOld(_, 1, _)) )); @@ -1540,6 +1582,9 @@ mod tests { std::num::NonZeroU32::new(1), None, true, + &mut crate::utils::json::flatten::FlattenBudget::new( + crate::utils::json::flatten::GENEROUS_LIMITS, + ), ) .unwrap(); let mut old = json!({"ts": (now - chrono::Duration::hours(4)).to_rfc3339()}); @@ -1550,7 +1595,10 @@ mod tests { Some(&key), std::num::NonZeroU32::new(1), None, - true + true, + &mut crate::utils::json::flatten::FlattenBudget::new( + crate::utils::json::flatten::GENEROUS_LIMITS + ) ), Err(JsonFlattenError::TimestampTooOldRelative(_, 3, _, _)) )); @@ -1580,6 +1628,9 @@ mod tests { None, custom_partition, validation_required, + &mut crate::utils::json::flatten::FlattenBudget::new( + crate::utils::json::flatten::GENEROUS_LIMITS, + ), ) }; result @@ -1843,7 +1894,18 @@ mod tests { (json!({"a": {"b": 2}, "a_b": 1}), json!({"a_b": 1})), ] { let mut obj = input.clone(); - flatten(&mut obj, "_", None, None, None, false).unwrap(); + flatten( + &mut obj, + "_", + None, + None, + None, + false, + &mut crate::utils::json::flatten::FlattenBudget::new( + crate::utils::json::flatten::GENEROUS_LIMITS, + ), + ) + .unwrap(); if preserves_order { assert_eq!(obj, expected); } @@ -1857,7 +1919,18 @@ mod tests { #[test] fn flatten_drops_nested_empty_object() { let mut obj = json!({"a": {}, "b": {"c": {}}, "d": 1}); - flatten(&mut obj, "_", None, None, None, false).unwrap(); + flatten( + &mut obj, + "_", + None, + None, + None, + false, + &mut crate::utils::json::flatten::FlattenBudget::new( + crate::utils::json::flatten::GENEROUS_LIMITS, + ), + ) + .unwrap(); assert_eq!(obj, json!({"d": 1})); } @@ -1865,17 +1938,47 @@ mod tests { fn flatten_flat_object_still_validates() { let mut obj = json!({"a": "x.y", "b": 1}); assert!(matches!( - flatten(&mut obj, "_", None, None, Some(&"a".to_owned()), true), + flatten( + &mut obj, + "_", + None, + None, + Some(&"a".to_owned()), + true, + &mut crate::utils::json::flatten::FlattenBudget::new( + crate::utils::json::flatten::GENEROUS_LIMITS + ) + ), Err(JsonFlattenError::FieldContainsPeriod(_)) )); let mut obj = json!({"b": 1}); assert!(matches!( - flatten(&mut obj, "_", None, None, Some(&"a".to_owned()), true), + flatten( + &mut obj, + "_", + None, + None, + Some(&"a".to_owned()), + true, + &mut crate::utils::json::flatten::FlattenBudget::new( + crate::utils::json::flatten::GENEROUS_LIMITS + ) + ), Err(JsonFlattenError::FieldNotPartOfLog(_)) )); let mut obj = json!(1); assert!(matches!( - flatten(&mut obj, "_", None, None, None, false), + flatten( + &mut obj, + "_", + None, + None, + None, + false, + &mut crate::utils::json::flatten::FlattenBudget::new( + crate::utils::json::flatten::GENEROUS_LIMITS + ) + ), Err(JsonFlattenError::CannotFlatten) )); } @@ -1884,7 +1987,18 @@ mod tests { fn flatten_single_key_string() { let mut obj = json!({"key": "value"}); let expected = obj.clone(); - flatten(&mut obj, "_", None, None, None, false).unwrap(); + flatten( + &mut obj, + "_", + None, + None, + None, + false, + &mut crate::utils::json::flatten::FlattenBudget::new( + crate::utils::json::flatten::GENEROUS_LIMITS, + ), + ) + .unwrap(); assert_eq!(obj, expected); } @@ -1892,7 +2006,18 @@ mod tests { fn flatten_single_key_int() { let mut obj = json!({"key": 1}); let expected = obj.clone(); - flatten(&mut obj, "_", None, None, None, false).unwrap(); + flatten( + &mut obj, + "_", + None, + None, + None, + false, + &mut crate::utils::json::flatten::FlattenBudget::new( + crate::utils::json::flatten::GENEROUS_LIMITS, + ), + ) + .unwrap(); assert_eq!(obj, expected); } @@ -1900,7 +2025,18 @@ mod tests { fn flatten_multiple_key_value() { let mut obj = json!({"key1": 1, "key2": "value2"}); let expected = obj.clone(); - flatten(&mut obj, "_", None, None, None, false).unwrap(); + flatten( + &mut obj, + "_", + None, + None, + None, + false, + &mut crate::utils::json::flatten::FlattenBudget::new( + crate::utils::json::flatten::GENEROUS_LIMITS, + ), + ) + .unwrap(); assert_eq!(obj, expected); } @@ -1908,7 +2044,18 @@ mod tests { fn flatten_nested_single_key_value() { let mut obj = json!({"key": "value", "nested_key": {"key":"value"}}); let expected = json!({"key": "value", "nested_key.key": "value"}); - flatten(&mut obj, ".", None, None, None, false).unwrap(); + flatten( + &mut obj, + ".", + None, + None, + None, + false, + &mut crate::utils::json::flatten::FlattenBudget::new( + crate::utils::json::flatten::GENEROUS_LIMITS, + ), + ) + .unwrap(); assert_eq!(obj, expected); } @@ -1917,7 +2064,18 @@ mod tests { let mut obj = json!({"key": "value", "nested_key": {"key1":"value1", "key2": "value2"}}); let expected = json!({"key": "value", "nested_key.key1": "value1", "nested_key.key2": "value2"}); - flatten(&mut obj, ".", None, None, None, false).unwrap(); + flatten( + &mut obj, + ".", + None, + None, + None, + false, + &mut crate::utils::json::flatten::FlattenBudget::new( + crate::utils::json::flatten::GENEROUS_LIMITS, + ), + ) + .unwrap(); assert_eq!(obj, expected); } @@ -1925,7 +2083,18 @@ mod tests { fn nested_key_value_with_array() { let mut obj = json!({"key": "value", "nested_key": {"key1":[1,2,3]}}); let expected = json!({"key": "value", "nested_key.key1": [1,2,3]}); - flatten(&mut obj, ".", None, None, None, false).unwrap(); + flatten( + &mut obj, + ".", + None, + None, + None, + false, + &mut crate::utils::json::flatten::FlattenBudget::new( + crate::utils::json::flatten::GENEROUS_LIMITS, + ), + ) + .unwrap(); assert_eq!(obj, expected); } @@ -1933,7 +2102,18 @@ mod tests { fn nested_obj_array() { let mut obj = json!({"key": [{"a": "value0"}, {"a": "value1"}]}); let expected = json!({"key.a": ["value0", "value1"]}); - flatten(&mut obj, ".", None, None, None, false).unwrap(); + flatten( + &mut obj, + ".", + None, + None, + None, + false, + &mut crate::utils::json::flatten::FlattenBudget::new( + crate::utils::json::flatten::GENEROUS_LIMITS, + ), + ) + .unwrap(); assert_eq!(obj, expected); } @@ -1941,7 +2121,18 @@ mod tests { fn nested_obj_array_nulls() { let mut obj = json!({"key": [{"a": "value0"}, {"a": "value1", "b": "value1"}]}); let expected = json!({"key.a": ["value0", "value1"], "key.b": [null, "value1"]}); - flatten(&mut obj, ".", None, None, None, false).unwrap(); + flatten( + &mut obj, + ".", + None, + None, + None, + false, + &mut crate::utils::json::flatten::FlattenBudget::new( + crate::utils::json::flatten::GENEROUS_LIMITS, + ), + ) + .unwrap(); assert_eq!(obj, expected); } @@ -1949,7 +2140,18 @@ mod tests { fn nested_obj_array_nulls_reversed() { let mut obj = json!({"key": [{"a": "value0", "b": "value0"}, {"a": "value1"}]}); let expected = json!({"key.a": ["value0", "value1"], "key.b": ["value0", null]}); - flatten(&mut obj, ".", None, None, None, false).unwrap(); + flatten( + &mut obj, + ".", + None, + None, + None, + false, + &mut crate::utils::json::flatten::FlattenBudget::new( + crate::utils::json::flatten::GENEROUS_LIMITS, + ), + ) + .unwrap(); assert_eq!(obj, expected); } @@ -1957,7 +2159,18 @@ mod tests { fn nested_obj_array_nested_obj() { let mut obj = json!({"key": [{"a": {"p": 0}, "b": "value0"}, {"b": "value1"}]}); let expected = json!({"key.a.p": [0, null], "key.b": ["value0", "value1"]}); - flatten(&mut obj, ".", None, None, None, false).unwrap(); + flatten( + &mut obj, + ".", + None, + None, + None, + false, + &mut crate::utils::json::flatten::FlattenBudget::new( + crate::utils::json::flatten::GENEROUS_LIMITS, + ), + ) + .unwrap(); assert_eq!(obj, expected); } @@ -1965,14 +2178,38 @@ mod tests { fn nested_obj_array_nested_obj_array() { let mut obj = json!({"key": [{"a": [{"p": "value0", "q": "value0"}, {"p": "value1", "q": null}], "b": "value0"}, {"b": "value1"}]}); let expected = json!({"key.a.p": [["value0", "value1"], null], "key.a.q": [["value0", null], null], "key.b": ["value0", "value1"]}); - flatten(&mut obj, ".", None, None, None, false).unwrap(); + flatten( + &mut obj, + ".", + None, + None, + None, + false, + &mut crate::utils::json::flatten::FlattenBudget::new( + crate::utils::json::flatten::GENEROUS_LIMITS, + ), + ) + .unwrap(); assert_eq!(obj, expected); } #[test] fn flatten_mixed_object() { let mut obj = json!({"a": 42, "arr": ["1", {"key": "2"}, {"key": {"nested": "3"}}]}); - assert!(flatten(&mut obj, ".", None, None, None, false).is_err()); + assert!( + flatten( + &mut obj, + ".", + None, + None, + None, + false, + &mut crate::utils::json::flatten::FlattenBudget::new( + crate::utils::json::flatten::GENEROUS_LIMITS + ) + ) + .is_err() + ); } #[test] @@ -1986,7 +2223,14 @@ mod tests { }; let mut map = Map::new(); - flatten_array_objects(&mut map, "key", &mut arr, ".").unwrap(); + flatten_array_objects( + &mut map, + "key", + &mut arr, + ".", + &mut FlattenBudget::new(GENEROUS_LIMITS), + ) + .unwrap(); assert_eq!(map.len(), 2); assert_eq!(map.get("key.p").unwrap(), &json!([null, 2, null])); @@ -2000,7 +2244,14 @@ mod tests { }; let mut map = Map::new(); - flatten_array_objects(&mut map, "key", &mut arr, ".").unwrap(); + flatten_array_objects( + &mut map, + "key", + &mut arr, + ".", + &mut FlattenBudget::new(GENEROUS_LIMITS), + ) + .unwrap(); assert_eq!(map.len(), 2); assert_eq!(map.get("key.a").unwrap(), &json!([1, 2, null])); @@ -2014,7 +2265,14 @@ mod tests { }; let mut map = Map::new(); - flatten_array_objects(&mut map, "key", &mut arr, ".").unwrap(); + flatten_array_objects( + &mut map, + "key", + &mut arr, + ".", + &mut FlattenBudget::new(GENEROUS_LIMITS), + ) + .unwrap(); assert_eq!(map.len(), 3); assert_eq!(map.get("key.a").unwrap(), &json!([1, null, 3])); @@ -2033,7 +2291,14 @@ mod tests { }; let mut map = Map::new(); - flatten_array_objects(&mut map, "key", &mut arr, ".").unwrap(); + flatten_array_objects( + &mut map, + "key", + &mut arr, + ".", + &mut FlattenBudget::new(GENEROUS_LIMITS), + ) + .unwrap(); assert_eq!(map.len(), 3); assert_eq!(map.get("key.p").unwrap(), &json!([1, null, 3])); @@ -2052,7 +2317,14 @@ mod tests { }; let mut map = Map::new(); - flatten_array_objects(&mut map, "key", &mut arr, ".").unwrap(); + flatten_array_objects( + &mut map, + "key", + &mut arr, + ".", + &mut FlattenBudget::new(GENEROUS_LIMITS), + ) + .unwrap(); assert_eq!(map.len(), 3); assert_eq!(map.get("key.p").unwrap(), &json!([1, null, 3])); @@ -2065,22 +2337,74 @@ mod tests { let mut value = json!({ "a": 1, }); - assert!(flatten(&mut value, "_", None, None, Some(&"a".to_string()), true).is_ok()); + assert!( + flatten( + &mut value, + "_", + None, + None, + Some(&"a".to_string()), + true, + &mut crate::utils::json::flatten::FlattenBudget::new( + crate::utils::json::flatten::GENEROUS_LIMITS + ) + ) + .is_ok() + ); let mut value = json!({ "a": true, }); - assert!(flatten(&mut value, "_", None, None, Some(&"a".to_string()), true).is_ok()); + assert!( + flatten( + &mut value, + "_", + None, + None, + Some(&"a".to_string()), + true, + &mut crate::utils::json::flatten::FlattenBudget::new( + crate::utils::json::flatten::GENEROUS_LIMITS + ) + ) + .is_ok() + ); let mut value = json!({ "a": "yes", }); - assert!(flatten(&mut value, "_", None, None, Some(&"a".to_string()), true).is_ok()); + assert!( + flatten( + &mut value, + "_", + None, + None, + Some(&"a".to_string()), + true, + &mut crate::utils::json::flatten::FlattenBudget::new( + crate::utils::json::flatten::GENEROUS_LIMITS + ) + ) + .is_ok() + ); let mut value = json!({ "a": -1, }); - assert!(flatten(&mut value, "_", None, None, Some(&"a".to_string()), true).is_ok()); + assert!( + flatten( + &mut value, + "_", + None, + None, + Some(&"a".to_string()), + true, + &mut crate::utils::json::flatten::FlattenBudget::new( + crate::utils::json::flatten::GENEROUS_LIMITS + ) + ) + .is_ok() + ); } #[test] @@ -2089,7 +2413,18 @@ mod tests { "a": null, }); matches!( - flatten(&mut value, "_", None, None, Some(&"a".to_string()), true).unwrap_err(), + flatten( + &mut value, + "_", + None, + None, + Some(&"a".to_string()), + true, + &mut crate::utils::json::flatten::FlattenBudget::new( + crate::utils::json::flatten::GENEROUS_LIMITS + ) + ) + .unwrap_err(), JsonFlattenError::FieldEmptyOrNull(_) ); @@ -2097,7 +2432,18 @@ mod tests { "a": "", }); matches!( - flatten(&mut value, "_", None, None, Some(&"a".to_string()), true).unwrap_err(), + flatten( + &mut value, + "_", + None, + None, + Some(&"a".to_string()), + true, + &mut crate::utils::json::flatten::FlattenBudget::new( + crate::utils::json::flatten::GENEROUS_LIMITS + ) + ) + .unwrap_err(), JsonFlattenError::FieldEmptyOrNull(_) ); @@ -2105,7 +2451,18 @@ mod tests { "a": {"b": 1}, }); matches!( - flatten(&mut value, "_", None, None, Some(&"a".to_string()), true).unwrap_err(), + flatten( + &mut value, + "_", + None, + None, + Some(&"a".to_string()), + true, + &mut crate::utils::json::flatten::FlattenBudget::new( + crate::utils::json::flatten::GENEROUS_LIMITS + ) + ) + .unwrap_err(), JsonFlattenError::FieldIsObject(_) ); @@ -2113,7 +2470,18 @@ mod tests { "a": ["b", "c"], }); matches!( - flatten(&mut value, "_", None, None, Some(&"a".to_string()), true).unwrap_err(), + flatten( + &mut value, + "_", + None, + None, + Some(&"a".to_string()), + true, + &mut crate::utils::json::flatten::FlattenBudget::new( + crate::utils::json::flatten::GENEROUS_LIMITS + ) + ) + .unwrap_err(), JsonFlattenError::FieldIsArray(_) ); @@ -2121,7 +2489,18 @@ mod tests { "a": "b.c", }); matches!( - flatten(&mut value, "_", None, None, Some(&"a".to_string()), true).unwrap_err(), + flatten( + &mut value, + "_", + None, + None, + Some(&"a".to_string()), + true, + &mut crate::utils::json::flatten::FlattenBudget::new( + crate::utils::json::flatten::GENEROUS_LIMITS + ) + ) + .unwrap_err(), JsonFlattenError::FieldContainsPeriod(_) ); @@ -2129,7 +2508,18 @@ mod tests { "a": 1.0, }); matches!( - flatten(&mut value, "_", None, None, Some(&"a".to_string()), true).unwrap_err(), + flatten( + &mut value, + "_", + None, + None, + Some(&"a".to_string()), + true, + &mut crate::utils::json::flatten::FlattenBudget::new( + crate::utils::json::flatten::GENEROUS_LIMITS + ) + ) + .unwrap_err(), JsonFlattenError::FieldContainsPeriod(_) ); } @@ -2445,7 +2835,18 @@ mod tests { for row in rows { let mut row = row.clone(); if let Value::Object(_) = row { - flatten(&mut row, "_", None, None, None, false).unwrap(); + flatten( + &mut row, + "_", + None, + None, + None, + false, + &mut crate::utils::json::flatten::FlattenBudget::new( + crate::utils::json::flatten::GENEROUS_LIMITS, + ), + ) + .unwrap(); fields += row.as_object().unwrap().len(); } bytes += serde_json::to_vec(&row).unwrap().len(); @@ -2556,7 +2957,18 @@ mod tests { ] { let built = generic_flattening_with_limits(&value, GENEROUS_LIMITS).unwrap(); let mut flattened = Value::Array(built.clone()); - flatten(&mut flattened, "_", None, None, None, false).unwrap(); + flatten( + &mut flattened, + "_", + None, + None, + None, + false, + &mut crate::utils::json::flatten::FlattenBudget::new( + crate::utils::json::flatten::GENEROUS_LIMITS, + ), + ) + .unwrap(); assert_eq!(flattened, expected, "input: {value}"); let cost = flatten_pipeline_cost(&value, &GENEROUS_LIMITS).unwrap(); let expected = expected.as_array().unwrap(); diff --git a/src/utils/json/mod.rs b/src/utils/json/mod.rs index 1a7f72ee5..e0bb60fe9 100644 --- a/src/utils/json/mod.rs +++ b/src/utils/json/mod.rs @@ -85,6 +85,7 @@ fn flatten_json_body_inner( time_partition_limit, custom_partition, validation_required, + budget, )?; Ok(nested_value) } @@ -121,6 +122,7 @@ pub fn apply_generic_flattening_for_partition( time_partition_limit, custom_partition, true, + budget, )?; Ok(vec![nested_value]) } else { @@ -135,6 +137,7 @@ pub fn apply_generic_flattening_for_partition( time_partition_limit, custom_partition, true, + budget, )?; result.push(processed_item); } @@ -169,6 +172,7 @@ fn process_partitioned_element( time_partition_limit, custom_partition, true, + budget, )?; Ok(vec![nested_value]) } From f49a4baf32f80051b5036b36e414523e91c20ad8 Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Mon, 23 Nov 2026 23:02:04 -0600 Subject: [PATCH 09/31] test(otel): report the resident memory of the worst requests and of 10 MiB requests An ignored test, run alone on a release build, that decodes a request and hands its rows over in chunks, printing the resident memory decoding takes and the peak (VmHWM, reset through clear_refs) over the whole: the review's two worst cases and a 10 MiB Kubernetes-attributed request per signal. Co-Authored-By: Claude Opus 5.5 --- src/otel/memory_tests.rs | 130 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 130 insertions(+) diff --git a/src/otel/memory_tests.rs b/src/otel/memory_tests.rs index a9ac19a7f..81e92fa43 100644 --- a/src/otel/memory_tests.rs +++ b/src/otel/memory_tests.rs @@ -553,3 +553,133 @@ fn row_estimate_tracks_allocated_memory() { ); } } + +/// Resident and peak resident memory of this process in bytes, from +/// `/proc/self/statm` and `VmHWM` +#[cfg(target_os = "linux")] +fn resident() -> (usize, usize) { + let statm = std::fs::read_to_string("/proc/self/statm").unwrap(); + let pages: usize = statm.split_whitespace().nth(1).unwrap().parse().unwrap(); + let status = std::fs::read_to_string("/proc/self/status").unwrap(); + let hwm: usize = status + .lines() + .find_map(|line| line.strip_prefix("VmHWM:")) + .and_then(|kb| kb.trim().trim_end_matches(" kB").trim().parse().ok()) + .unwrap(); + (pages * 4096, hwm * 1024) +} + +/// Resident memory of decoding a request and handing its rows over in chunks. +/// Release build, run alone: +/// `cargo test --release --lib -- --ignored --exact otel::memory_tests::resident_memory_of_requests --nocapture` +#[test] +#[cfg(target_os = "linux")] +#[ignore = "measures the resident memory of the process; run it alone"] +fn resident_memory_of_requests() { + use prost::Message; + + fn measure_case(name: &str, signal: &str, body: &[u8]) { + // VmHWM is reset to the current resident size + std::fs::write("/proc/self/clear_refs", "5").unwrap(); + let (before, _) = resident(); + let mut rows = 0usize; + let mut stage = |chunk: Vec| { + rows += chunk.len(); + Ok::<_, JsonFlattenError>(()) + }; + let mut chunker = Chunker::new(CHUNK_LIMITS, &mut stage); + let (decoded, after_decode) = match signal { + "logs" => { + let request = ExportLogsServiceRequest::decode(body).unwrap(); + let decoded = resident().0; + crate::otel::logs::flatten_logs_into( + &request.resource_logs, + &mut FlattenBudget::new(FlattenLimits::DEFAULT), + &mut chunker, + ) + .unwrap(); + (decoded, resident().0) + } + "traces" => { + let request = ExportTraceServiceRequest::decode(body).unwrap(); + let decoded = resident().0; + crate::otel::traces::flatten_traces_into(&request.resource_spans, &mut chunker) + .unwrap(); + (decoded, resident().0) + } + _ => { + let request = ExportMetricsServiceRequest::decode(body).unwrap(); + let decoded = resident().0; + crate::otel::metrics::flatten_metrics_into( + &request.resource_metrics, + false, + &mut chunker, + ) + .unwrap(); + (decoded, resident().0) + } + }; + chunker.finish().unwrap(); + drop(chunker); + let (_, hwm) = resident(); + println!( + "RESIDENT {name}: body {:.1} MiB, {rows} rows, decoded +{:.0} MiB, peak +{:.0} MiB over the {:.0} MiB before (decode included), {:.0} MiB at the end", + mb(body.len()), + mb(decoded.saturating_sub(before)), + mb(hwm.saturating_sub(before)), + mb(before), + mb(after_decode) + ); + } + + // One case per process, so that memory freed by an earlier case does not hide + // what a later one takes: `RESIDENT_CASE` is `events`, `tiny`, or + // `:` (see `dump_realistic_bodies`) + let case = std::env::var("RESIDENT_CASE").expect("RESIDENT_CASE"); + match case.split_once(':') { + // The two worst cases of the review: 2,097,152 empty events of one span + // (4 MiB), and 1000 tiny resource attributes copied into 5000 rows + None if case == "events" => { + let body = one_span(Span { + events: vec![Event::default(); 1 << 21], + ..Default::default() + }) + .encode_to_vec(); + measure_case("2,097,152 empty events of one span", "traces", &body); + } + None if case == "tiny" => { + let body = ExportLogsServiceRequest { + resource_logs: vec![ResourceLogs { + resource: Some(Resource { + attributes: (0..1000) + .map(|i| kv(format!("k{i:03}"), any_value::Value::IntValue(0))) + .collect(), + ..Default::default() + }), + scope_logs: vec![ScopeLogs { + log_records: (0..5000u64) + .map(|i| LogRecord { + time_unix_nano: 1_700_000_000_000_000_000 + i, + observed_time_unix_nano: 1_700_000_000_000_000_000, + ..Default::default() + }) + .collect(), + ..Default::default() + }], + ..Default::default() + }], + } + .encode_to_vec(); + measure_case( + "1000 tiny resource attributes x 5000 records", + "logs", + &body, + ); + } + Some((signal, path)) => { + let body = std::fs::read(path).unwrap(); + measure_case(path, signal, &body); + } + None => panic!("unknown RESIDENT_CASE {case}"), + } +} From 8438ecb3b1c881498645e23b66a2e831a4b86168 Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Mon, 23 Nov 2026 23:24:24 -0600 Subject: [PATCH 10/31] style(otel): name the stage closure type of the memory tests, drop a test-only import Clippy: type_complexity in memory_tests.rs, and JsonFlattenError imported by ingest_utils.rs only for a cfg(test) function. Co-Authored-By: Claude Opus 5.5 --- src/handlers/http/modal/utils/ingest_utils.rs | 4 ++-- .../utils/ingest_utils/otel_protobuf_props.rs | 2 +- src/otel/memory_tests.rs | 20 +++++++------------ 3 files changed, 10 insertions(+), 16 deletions(-) diff --git a/src/handlers/http/modal/utils/ingest_utils.rs b/src/handlers/http/modal/utils/ingest_utils.rs index 58f83d237..7c6ace9ca 100644 --- a/src/handlers/http/modal/utils/ingest_utils.rs +++ b/src/handlers/http/modal/utils/ingest_utils.rs @@ -71,7 +71,7 @@ use crate::{ get_tenant_id_from_request, json::{ convert_array_to_object, - flatten::{FlattenBudget, FlattenLimits, JsonFlattenError, convert_to_array}, + flatten::{FlattenBudget, FlattenLimits, convert_to_array}, }, }, }; @@ -541,7 +541,7 @@ impl OtelProtobufRequest { &self, tenant_id: &str, budget: &mut FlattenBudget, - ) -> Result, JsonFlattenError> { + ) -> Result, crate::utils::json::flatten::JsonFlattenError> { match self { Self::Logs(message) => { crate::otel::logs::flatten_otel_protobuf(message, tenant_id, budget) diff --git a/src/handlers/http/modal/utils/ingest_utils/otel_protobuf_props.rs b/src/handlers/http/modal/utils/ingest_utils/otel_protobuf_props.rs index b7d293a27..d761be8af 100644 --- a/src/handlers/http/modal/utils/ingest_utils/otel_protobuf_props.rs +++ b/src/handlers/http/modal/utils/ingest_utils/otel_protobuf_props.rs @@ -48,7 +48,7 @@ use crate::otel::metrics::{ use crate::otel::otel_utils::flatten_attributes; use crate::otel::sink::{ChunkLimits, Chunker}; use crate::otel::traces::flatten_otel_traces; -use crate::utils::json::flatten::FlattenCost; +use crate::utils::json::flatten::{FlattenCost, JsonFlattenError}; use opentelemetry_proto::tonic::common::v1::{ AnyValue, ArrayValue, InstrumentationScope, KeyValue, KeyValueList, any_value, }; diff --git a/src/otel/memory_tests.rs b/src/otel/memory_tests.rs index 81e92fa43..59c530f34 100644 --- a/src/otel/memory_tests.rs +++ b/src/otel/memory_tests.rs @@ -58,6 +58,9 @@ fn kv(key: impl Into, value: any_value::Value) -> KeyValue { } } +/// Takes a chunk of rows, as staging does +type Stage<'a> = dyn FnMut(Vec) -> Result<(), JsonFlattenError> + 'a; + /// Rows handed over, and the most rows a chunk held #[derive(Debug, Default)] struct Handed { @@ -69,7 +72,7 @@ struct Handed { /// full, as staging does, and reports what that allocated fn hand_over( name: &str, - flatten: impl FnOnce(&mut dyn FnMut(Vec) -> Result<(), JsonFlattenError>) -> Result<(), E>, + flatten: impl FnOnce(&mut Stage) -> Result<(), E>, ) -> (Result, Allocated) { let (result, allocated) = measure(|| { let mut handed = Handed::default(); @@ -92,10 +95,7 @@ fn hand_over( fn traces( request: &ExportTraceServiceRequest, -) -> impl FnOnce( - &mut dyn FnMut(Vec) -> Result<(), JsonFlattenError>, -) -> Result<(), JsonFlattenError> -+ '_ { +) -> impl FnOnce(&mut Stage) -> Result<(), JsonFlattenError> + '_ { move |stage| { let mut chunker = Chunker::new(CHUNK_LIMITS, stage); crate::otel::traces::flatten_traces_into(&request.resource_spans, &mut chunker)?; @@ -105,10 +105,7 @@ fn traces( fn metrics( request: &ExportMetricsServiceRequest, -) -> impl FnOnce( - &mut dyn FnMut(Vec) -> Result<(), JsonFlattenError>, -) -> Result<(), JsonFlattenError> -+ '_ { +) -> impl FnOnce(&mut Stage) -> Result<(), JsonFlattenError> + '_ { move |stage| { let mut chunker = Chunker::new(CHUNK_LIMITS, stage); crate::otel::metrics::flatten_metrics_into(&request.resource_metrics, false, &mut chunker)?; @@ -119,10 +116,7 @@ fn metrics( fn logs<'a>( request: &'a ExportLogsServiceRequest, budget: &'a mut FlattenBudget, -) -> impl FnOnce( - &mut dyn FnMut(Vec) -> Result<(), JsonFlattenError>, -) -> Result<(), JsonFlattenError> -+ 'a { +) -> impl FnOnce(&mut Stage) -> Result<(), JsonFlattenError> + 'a { move |stage| { let mut chunker = Chunker::new(CHUNK_LIMITS, stage); crate::otel::logs::flatten_logs_into(&request.resource_logs, budget, &mut chunker)?; From fcc4f37b118f19c22e79e109a645a0eae7537f60 Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Mon, 23 Nov 2026 23:52:34 -0600 Subject: [PATCH 11/31] feat(otel): decode an OTLP protobuf request one leaf record at a time The request, resource and scope levels are small prost::Message impls that prost itself drives, so keys, wire-type checks, the recursion limit, unknown fields and error paths are prost's. Their singular fields (resource, scope, schema_url) are merged as prost merges them; their repeated children are kept as offsets into the body (zero-copy) with the DecodeContext prost would use, and decoded once the level is read whole, from the rest of the body as prost decodes them. A leaf record (LogRecord, Span, Metric) is decoded on its own with message::merge and handed to the stage-1 flatteners, then dropped. Each record's decoded size is estimated without allocating (decoded_size.rs, from the budget-opus branch, trimmed to leaf records) and a record over 16 x P_MAX_EVENT_PAYLOAD_SIZE is refused (400) before it is decoded. The body is read twice: a sizing pass (expansion cap, record totals), then the staged pass. A body that does not decode is refused before anything is staged, with the error whole-request decoding gives: on a decode error the sizing pass re-reads the body in wire order (first_error) to report the break prost meets first. JSON requests are still decoded whole. Differential properties against whole-request decoding: rows byte-identical for bodies re-encoded with shuffled fields, split singular fields, replaced schema_url and unknown fields of every wire type; identical errors for truncated and byte-damaged bodies. Co-Authored-By: Claude Opus 5.5 --- src/handlers/http/modal/utils/ingest_utils.rs | 190 +++-- .../utils/ingest_utils/otel_protobuf_props.rs | 445 +++++++++++- src/otel.rs | 2 + src/otel/decoded_size.rs | 482 +++++++++++++ src/otel/expansion.rs | 217 ++++-- src/otel/logs.rs | 2 +- src/otel/metrics.rs | 4 +- src/otel/protobuf_stream.rs | 661 ++++++++++++++++++ src/otel/traces.rs | 4 +- 9 files changed, 1879 insertions(+), 128 deletions(-) create mode 100644 src/otel/decoded_size.rs create mode 100644 src/otel/protobuf_stream.rs diff --git a/src/handlers/http/modal/utils/ingest_utils.rs b/src/handlers/http/modal/utils/ingest_utils.rs index 7c6ace9ca..be4af0565 100644 --- a/src/handlers/http/modal/utils/ingest_utils.rs +++ b/src/handlers/http/modal/utils/ingest_utils.rs @@ -62,6 +62,7 @@ use crate::{ logs::flatten_logs_into, metrics::flatten_metrics_into, otel_utils::deserialize_otel_json, + protobuf_stream::{Signal, StreamError, flatten_request, max_record_bytes, size_request}, sink::{CHUNK_LIMITS, Chunker, RowSink, Staged}, traces::flatten_traces_into, }, @@ -303,10 +304,17 @@ fn handle_otel_ingestion( error!("Ingestion failed for stream {stream_name}: {e}"); }) } - Some(OtelContentType::Protobuf) => flatten_and_push_otel_protobuf(&body, &target) - .inspect_err(|e| { - error!("Ingestion failed for stream {stream_name}: {e}"); - }), + Some(OtelContentType::Protobuf) => flatten_and_push_otel_protobuf( + body, + &target, + ProtobufOptions { + max_payload: max_event_payload_size(), + flatten_exemplars: PARSEABLE.options.otel_flatten_exemplars, + }, + ) + .inspect_err(|e| { + error!("Ingestion failed for stream {stream_name}: {e}"); + }), None => { error!( "Ingestion failed for stream {stream_name}: Unsupported Content-Type: {content_type}. Expected application/json or application/x-protobuf" @@ -355,7 +363,7 @@ impl OtelResources<'_> { } /// Hands the rows of the request to `sink`, one at a time - fn flatten_into( + fn flatten_into( &self, budget: &mut FlattenBudget, flatten_exemplars: bool, @@ -368,27 +376,11 @@ impl OtelResources<'_> { } } - /// The records a partial success reports as rejected: log records, data - /// points or spans that were not staged in full - fn rejected(&self, size: &RequestSize, staged: &Staged) -> i64 { - let (total, staged) = match self { - Self::Metrics(_) => (size.points, staged.points), - Self::Logs(_) | Self::Traces(_) => (size.records, staged.records), - }; - total.saturating_sub(staged) as i64 - } - - /// Counts for `tenant_id` the leaf records (log records, spans, metrics) - /// whose rows were all staged - fn count_collected(&self, records: u64, tenant_id: &str) { - if records == 0 { - return; - } - let date = Utc::now().date_naive().to_string(); + fn signal(&self) -> Signal { match self { - Self::Logs(_) => increment_logs_collected_by_date(records, &date, tenant_id), - Self::Metrics(_) => increment_metrics_collected_by_date(records, &date, tenant_id), - Self::Traces(_) => increment_traces_collected_by_date(records, &date, tenant_id), + Self::Logs(_) => Signal::Logs, + Self::Metrics(_) => Signal::Metrics, + Self::Traces(_) => Signal::Traces, } } } @@ -418,15 +410,18 @@ fn check_expansion(size: &RequestSize, max_payload: usize) -> Result<(), PostErr /// OTLP/HTTP requires; /// - a server error keeps its 5xx status. The exporter then retries the whole /// request, so the rows of the chunks already staged are staged twice. -fn ingest_otel_resources( - resources: OtelResources<'_>, +fn ingest_otel_rows( + signal: Signal, + size: RequestSize, target: &OtelTarget<'_>, + flatten: impl FnOnce( + &mut FlattenBudget, + &mut dyn RowSink, + ) -> Result<(), PostError>, ) -> Result { let tenant_str = target.tenant_id.as_deref().unwrap_or(DEFAULT_TENANT); // Verify the dataset fields count verify_dataset_fields_count(target.stream_name, target.tenant_id)?; - let flatten_exemplars = PARSEABLE.options.otel_flatten_exemplars; - let size = resources.size(flatten_exemplars); check_expansion(&size, max_event_payload_size())?; // The JSON log bodies of every record of the request share one budget @@ -441,14 +436,12 @@ fn ingest_otel_resources( target.telemetry_type, ) }); - let result = resources - .flatten_into(&mut budget, flatten_exemplars, &mut chunker) - .and_then(|()| chunker.finish()); + let result = flatten(&mut budget, &mut chunker).and_then(|()| chunker.finish()); let staged = chunker.staged(); drop(chunker); if result.is_ok() || staged.chunks > 0 { - resources.count_collected(staged.records, tenant_str); + count_collected(signal, staged.records, tenant_str); } match result { Ok(()) => Ok(OtelIngested::Full), @@ -456,7 +449,7 @@ fn ingest_otel_resources( if staged.chunks > 0 && actix_web::ResponseError::status_code(&error).is_client_error() => { - let rejected = resources.rejected(&size, &staged); + let rejected = rejected(signal, &size, &staged); warn!( "Ingestion into stream {} stopped after {} rows: {error}. {rejected} records rejected", target.stream_name, staged.rows @@ -470,6 +463,42 @@ fn ingest_otel_resources( } } +/// `ingest_otel_rows` for a request decoded whole (OTLP JSON) +fn ingest_otel_resources( + resources: OtelResources<'_>, + target: &OtelTarget<'_>, +) -> Result { + let flatten_exemplars = PARSEABLE.options.otel_flatten_exemplars; + let size = resources.size(flatten_exemplars); + ingest_otel_rows(resources.signal(), size, target, |budget, sink| { + resources.flatten_into(budget, flatten_exemplars, sink) + }) +} + +/// The records a partial success reports as rejected: log records, data points or +/// spans that were not staged in full +fn rejected(signal: Signal, size: &RequestSize, staged: &Staged) -> i64 { + let (total, staged) = match signal { + Signal::Metrics => (size.points, staged.points), + Signal::Logs | Signal::Traces => (size.records, staged.records), + }; + total.saturating_sub(staged) as i64 +} + +/// Counts for `tenant_id` the leaf records (log records, spans, metrics) whose rows +/// were all staged +fn count_collected(signal: Signal, records: u64, tenant_id: &str) { + if records == 0 { + return; + } + let date = Utc::now().date_naive().to_string(); + match signal { + Signal::Logs => increment_logs_collected_by_date(records, &date, tenant_id), + Signal::Metrics => increment_metrics_collected_by_date(records, &date, tenant_id), + Signal::Traces => increment_traces_collected_by_date(records, &date, tenant_id), + } +} + /// The OTEL arms of `handle_otel_ingestion` for a JSON body fn ingest_otel_json(json: Value, target: &OtelTarget<'_>) -> Result { let normalise = PARSEABLE.options.normalise_otel_payload; @@ -492,7 +521,9 @@ fn ingest_otel_json(json: Value, target: &OtelTarget<'_>) -> Result OtelResources<'_> { - match self { - Self::Logs(message) => OtelResources::Logs(&message.resource_logs), - Self::Metrics(message) => OtelResources::Metrics(&message.resource_metrics), - Self::Traces(message) => OtelResources::Traces(&message.resource_spans), - } - } - /// Flattens into the same rows the JSON encoding of this request produces, /// all at once #[cfg(test)] @@ -556,21 +578,75 @@ impl OtelProtobufRequest { } } -/// Protobuf counterpart of `ingest_otel_json`: the typed request is decoded -/// straight from the body instead of going through a JSON value tree, then -/// shares flattening limits and the staging path with JSON. -/// The body size is capped by the `PayloadConfig` of the OTEL routes. +/// What the protobuf path needs from the server configuration, read by the caller +/// so that a body that does not decode is refused before the configuration is +#[derive(Debug, Clone, Copy)] +struct ProtobufOptions { + /// `P_MAX_EVENT_PAYLOAD_SIZE`, which caps the decoded size of one record + max_payload: usize, + flatten_exemplars: bool, +} + +/// Protobuf counterpart of `ingest_otel_json`. The body is read one leaf record +/// at a time (`protobuf_stream`), twice: a sizing pass that refuses a body that +/// does not decode or would expand too far before anything is staged, then the +/// pass whose rows are staged. Each record is decoded in each pass and dropped, +/// so the decoded request is never held whole. The body size is capped by the +/// `PayloadConfig` of the OTEL routes. fn flatten_and_push_otel_protobuf( - body: &[u8], + body: web::Bytes, target: &OtelTarget<'_>, + options: ProtobufOptions, ) -> Result { - let request = OtelProtobufRequest::decode(body, target.log_source).map_err(|e| { - PostError::Invalid(anyhow::anyhow!( - "Ingestion failed for stream {}: {e}", - target.stream_name - )) - })?; - ingest_otel_resources(request.resources(), target) + let signal = match target.log_source { + LogSource::OtelLogs => Signal::Logs, + LogSource::OtelMetrics => Signal::Metrics, + LogSource::OtelTraces => Signal::Traces, + other => { + return Err(stream_error( + target, + OtelProtobufError::NotOtel(other.clone()).to_string(), + )); + } + }; + let max_record = max_record_bytes(options.max_payload); + let size = + size_request(body.clone(), signal, max_record, options.flatten_exemplars).map_err(|e| { + from_stream_error(target, e.map_consumer::(|never| match never {})) + })?; + ingest_otel_rows(signal, size, target, |budget, sink| { + flatten_request( + body, + signal, + max_record, + budget, + options.flatten_exemplars, + sink, + ) + .map_err(|e| from_stream_error(target, e)) + }) +} + +fn stream_error(target: &OtelTarget<'_>, error: String) -> PostError { + PostError::Invalid(anyhow::anyhow!( + "Ingestion failed for stream {}: {error}", + target.stream_name + )) +} + +/// A decode error or an oversized record is a client error (400): the same text +/// whole-request decoding gave for a body that does not decode +fn from_stream_error(target: &OtelTarget<'_>, error: StreamError) -> PostError { + match error { + StreamError::Decode(e) => stream_error(target, OtelProtobufError::Decode(e).to_string()), + StreamError::RecordTooLarge { leaf, limit } => stream_error( + target, + format!( + "one {leaf:?} of the request would take more than {limit} bytes of memory once decoded (16 times P_MAX_EVENT_PAYLOAD_SIZE). Split it into smaller records" + ), + ), + StreamError::Consumer(e) => e, + } } #[instrument( diff --git a/src/handlers/http/modal/utils/ingest_utils/otel_protobuf_props.rs b/src/handlers/http/modal/utils/ingest_utils/otel_protobuf_props.rs index d761be8af..057de0284 100644 --- a/src/handlers/http/modal/utils/ingest_utils/otel_protobuf_props.rs +++ b/src/handlers/http/modal/utils/ingest_utils/otel_protobuf_props.rs @@ -78,6 +78,12 @@ use std::sync::atomic::{AtomicUsize, Ordering}; const TENANT: &str = "tenant"; +/// The server defaults the protobuf path reads from the configuration +const PROTOBUF_OPTIONS: ProtobufOptions = ProtobufOptions { + max_payload: 10 * 1024 * 1024, + flatten_exemplars: false, +}; + // --------------------------------------------------------------------------- // Seeds and runners // --------------------------------------------------------------------------- @@ -1650,7 +1656,7 @@ fn decode_is_total( Err(error) => { // Returns before the dataset field check, the first use of `PARSEABLE` let refused = flatten_and_push_otel_protobuf( - body, + web::Bytes::copy_from_slice(body), &OtelTarget { stream_name: "otel_pb_props", log_source: source, @@ -1658,6 +1664,7 @@ fn decode_is_total( telemetry_type, tenant_id: &None, }, + PROTOBUF_OPTIONS, ) .expect_err("a body that does not decode is refused"); prop_assert!(matches!(refused, PostError::Invalid(_)), "{refused:?}"); @@ -2526,7 +2533,7 @@ fn run_scenario(seed: u64) -> Result)> { } if encoding == Encoding::Protobuf { let refused = flatten_and_push_otel_protobuf( - &body, + web::Bytes::copy_from_slice(&body), &OtelTarget { stream_name: "dst", log_source: &source, @@ -2534,6 +2541,7 @@ fn run_scenario(seed: u64) -> Result)> { telemetry_type: request.telemetry_type(), tenant_id: &None, }, + PROTOBUF_OPTIONS, ); if !matches!(&refused, Err(PostError::Invalid(e)) if e.to_string().ends_with(error.as_str())) { @@ -2693,3 +2701,436 @@ fn dst_otlp_mixed_encoding_seeds_differ() { .collect(); assert_eq!(digests.len(), 4); } + +// --------------------------------------------------------------------------- +// Streamed decoding (`protobuf_stream`) against whole-request decoding +// --------------------------------------------------------------------------- + +mod streamed { + use super::*; + use crate::otel::expansion::{logs_size, metrics_size, traces_size}; + use crate::otel::protobuf_stream::{Signal, StreamError, flatten_request, size_request}; + use prost::Message as ProstMessage; + use prost::encoding::{WireType, encode_key, encode_varint}; + + /// Wire edits applied while re-encoding a request field by field + struct Edits<'a>(&'a mut SplitMix64); + + impl Edits<'_> { + /// An unknown field (numbers 4-40 or a large one) of a random wire type + fn unknown(&mut self, out: &mut Vec) { + let tag = if self.0.percent(80) { + 4 + self.0.below(37) as u32 + } else { + 1 << 20 + }; + match self.0.below(5) { + 0 => { + encode_key(tag, WireType::Varint, out); + encode_varint(self.0.next_u64() >> self.0.below(64), out); + } + 1 => { + encode_key(tag, WireType::SixtyFourBit, out); + out.extend_from_slice(&self.0.next_u64().to_le_bytes()); + } + 2 => { + encode_key(tag, WireType::ThirtyTwoBit, out); + out.extend_from_slice(&(self.0.next_u64() as u32).to_le_bytes()); + } + 3 => { + let len = self.0.below(12) as usize; + encode_key(tag, WireType::LengthDelimited, out); + encode_varint(len as u64, out); + out.extend((0..len).map(|_| self.0.next_u64() as u8)); + } + _ => { + encode_key(tag, WireType::StartGroup, out); + if self.0.percent(50) { + encode_key(tag + 1, WireType::Varint, out); + encode_varint(7, out); + } + encode_key(tag, WireType::EndGroup, out); + } + } + } + + /// `fields` in a shuffled order, with unknown fields between them + fn level(&mut self, mut fields: Vec>) -> Vec { + for i in (1..fields.len()).rev() { + if self.0.percent(50) { + let j = self.0.below(i as u64 + 1) as usize; + fields.swap(i, j); + } + } + let mut out = Vec::new(); + for field in fields { + if self.0.percent(25) { + self.unknown(&mut out); + } + out.extend(field); + } + if self.0.percent(25) { + self.unknown(&mut out); + } + out + } + + fn len_field(tag: u32, body: &[u8]) -> Vec { + let mut out = Vec::new(); + encode_key(tag, WireType::LengthDelimited, &mut out); + encode_varint(body.len() as u64, &mut out); + out.extend_from_slice(body); + out + } + + /// A singular message field, sometimes split over two occurrences, which + /// prost merges: repeated fields concatenate, the last scalar wins + fn singular( + &mut self, + tag: u32, + msg: &M, + split: impl Fn(&M) -> (M, M), + ) -> Vec> { + if self.0.percent(30) { + let (first, second) = split(msg); + vec![ + Self::len_field(tag, &first.encode_to_vec()), + Self::len_field(tag, &second.encode_to_vec()), + ] + } else { + vec![Self::len_field(tag, &msg.encode_to_vec())] + } + } + + /// `schema_url`, sometimes after an earlier occurrence it replaces + fn schema_url(&mut self, url: &str) -> Vec> { + let mut fields = vec![]; + if self.0.percent(20) { + fields.push(Self::len_field(3, b"https://replaced.example")); + } + if !url.is_empty() || self.0.percent(20) { + fields.push(Self::len_field(3, url.as_bytes())); + } + fields + } + + /// A parent level: `resource`/`scope` (field 1), children (field 2), schema_url (3) + fn parent( + &mut self, + parent: Option<&P>, + split: impl Fn(&P) -> (P, P), + children: Vec>, + url: &str, + ) -> Vec { + let mut fields = vec![]; + if let Some(parent) = parent { + fields.extend(self.singular(1, parent, split)); + } + fields.extend(children.iter().map(|child| Self::len_field(2, child))); + fields.extend(self.schema_url(url)); + self.level(fields) + } + } + + fn split_resource(resource: &Resource) -> (Resource, Resource) { + let at = resource.attributes.len() / 2; + ( + Resource { + attributes: resource.attributes[..at].to_vec(), + dropped_attributes_count: 3, + ..Default::default() + }, + Resource { + attributes: resource.attributes[at..].to_vec(), + ..resource.clone() + }, + ) + } + + fn split_scope(scope: &InstrumentationScope) -> (InstrumentationScope, InstrumentationScope) { + let at = scope.attributes.len() / 2; + ( + InstrumentationScope { + name: "replaced".into(), + attributes: scope.attributes[..at].to_vec(), + ..Default::default() + }, + InstrumentationScope { + attributes: scope.attributes[at..].to_vec(), + ..scope.clone() + }, + ) + } + + /// The protobuf body of `request`, re-encoded field by field with `edits` + fn edited_body(request: &Req, rng: &mut SplitMix64) -> Vec { + let mut edits = Edits(rng); + let resources: Vec> = match request { + Req::Logs(data) => data + .resource_logs + .iter() + .map(|r| { + let scopes = r + .scope_logs + .iter() + .map(|s| { + let records = s + .log_records + .iter() + .map(ProstMessage::encode_to_vec) + .collect(); + edits.parent(s.scope.as_ref(), split_scope, records, &s.schema_url) + }) + .collect(); + edits.parent(r.resource.as_ref(), split_resource, scopes, &r.schema_url) + }) + .collect(), + Req::Traces(data) => data + .resource_spans + .iter() + .map(|r| { + let scopes = r + .scope_spans + .iter() + .map(|s| { + let spans = s.spans.iter().map(ProstMessage::encode_to_vec).collect(); + edits.parent(s.scope.as_ref(), split_scope, spans, &s.schema_url) + }) + .collect(); + edits.parent(r.resource.as_ref(), split_resource, scopes, &r.schema_url) + }) + .collect(), + Req::Metrics(data) => data + .resource_metrics + .iter() + .map(|r| { + let scopes = r + .scope_metrics + .iter() + .map(|s| { + let metrics = + s.metrics.iter().map(ProstMessage::encode_to_vec).collect(); + edits.parent(s.scope.as_ref(), split_scope, metrics, &s.schema_url) + }) + .collect(); + edits.parent(r.resource.as_ref(), split_resource, scopes, &r.schema_url) + }) + .collect(), + }; + let fields = resources.iter().map(|r| Edits::len_field(1, r)).collect(); + edits.level(fields) + } + + fn signal(request: &Req) -> Signal { + match request { + Req::Logs(_) => Signal::Logs, + Req::Metrics(_) => Signal::Metrics, + Req::Traces(_) => Signal::Traces, + } + } + + /// Rows and size of `body` decoded whole, or prost's error text + fn whole( + request: &Req, + body: &[u8], + flatten_exemplars: bool, + ) -> Result<(Vec, RequestSize), String> { + let decoded = + OtelProtobufRequest::decode(body, &request.source()).map_err(|e| e.to_string())?; + let decoded = Req::from_decoded(decoded); + let resources = decoded.resources(); + let mut rows = Vec::new(); + resources + .flatten_into( + &mut FlattenBudget::new(FlattenLimits::DEFAULT), + flatten_exemplars, + &mut rows, + ) + .map_err(|e| format!("flatten: {e}"))?; + let size = match &decoded { + Req::Logs(data) => logs_size(&data.resource_logs), + Req::Metrics(data) => metrics_size(&data.resource_metrics, flatten_exemplars), + Req::Traces(data) => traces_size(&data.resource_spans), + }; + Ok((serde_json::to_vec(&rows).unwrap(), size)) + } + + /// Rows and size of `body` read one record at a time, or the error text + fn streamed( + request: &Req, + body: &[u8], + flatten_exemplars: bool, + ) -> Result<(Vec, RequestSize), String> { + let text = |e: StreamError<_>| match e { + StreamError::Decode(e) => OtelProtobufError::Decode(e).to_string(), + StreamError::RecordTooLarge { .. } => "record too large".to_string(), + StreamError::Consumer(e) => format!("flatten: {e}"), + }; + let size = size_request( + web::Bytes::copy_from_slice(body), + signal(request), + usize::MAX, + flatten_exemplars, + ) + .map_err(|e| { + text(match e { + StreamError::Decode(e) => StreamError::Decode(e), + StreamError::RecordTooLarge { leaf, limit } => { + StreamError::RecordTooLarge { leaf, limit } + } + StreamError::Consumer(never) => match never {}, + }) + })?; + let mut rows: Vec = Vec::new(); + flatten_request( + web::Bytes::copy_from_slice(body), + signal(request), + usize::MAX, + &mut FlattenBudget::new(FlattenLimits::DEFAULT), + flatten_exemplars, + &mut rows, + ) + .map_err(text)?; + Ok((serde_json::to_vec(&rows).unwrap(), size)) + } + + fn streamed_matches_whole( + mut request: Req, + seed: u64, + flatten_exemplars: bool, + cut: Option, + ) -> TestCaseResult { + fill_unset_timestamps(&mut request); + let mut rng = SplitMix64(seed); + let mut body = edited_body(&request, &mut rng); + if let Some(cut) = cut { + body.truncate((cut % (body.len() as u64 + 1)) as usize); + } + let whole = whole(&request, &body, flatten_exemplars); + let streamed = streamed(&request, &body, flatten_exemplars); + prop_assert_eq!( + &whole, + &streamed, + "whole (left) and streamed (right) differ" + ); + Ok(()) + } + + fn requests() -> BoxedStrategy { + prop_oneof![ + logs_data(true).prop_map(Req::Logs), + traces_data(true).prop_map(Req::Traces), + metrics_data(true).prop_map(Req::Metrics), + ] + .boxed() + } + + #[test] + fn otel_pb_streamed_rows_match_whole_decoding() { + check( + "otel_pb_streamed_rows_match_whole_decoding", + 192, + (requests(), any::(), any::()), + |(request, seed, flatten_exemplars)| { + streamed_matches_whole(request, seed, flatten_exemplars, None) + }, + ); + } + + #[test] + fn otel_pb_streamed_errors_match_whole_decoding() { + check( + "otel_pb_streamed_errors_match_whole_decoding", + 192, + (requests(), any::(), any::()), + |(request, seed, cut)| streamed_matches_whole(request, seed, false, Some(cut)), + ); + } + + /// Single-byte damage: streamed and whole decoding accept and refuse the same + /// bodies, with the same rows, and give the same error (the sizing pass reports + /// the break prost meets first, see `first_error`) + #[test] + fn otel_pb_streamed_damaged_bodies_match_whole_decoding() { + let (refused, other_error) = (AtomicUsize::new(0), AtomicUsize::new(0)); + check( + "otel_pb_streamed_damaged_bodies_match_whole_decoding", + 192, + (requests(), any::(), any::(), any::()), + |(mut request, seed, at, byte)| { + fill_unset_timestamps(&mut request); + let mut body = edited_body(&request, &mut SplitMix64(seed)); + if !body.is_empty() { + let at = (at % body.len() as u64) as usize; + body[at] = byte; + } + match ( + whole(&request, &body, false), + streamed(&request, &body, false), + ) { + (Ok(whole), Ok(streamed)) => prop_assert_eq!(whole, streamed), + (Err(whole), Err(streamed)) => { + refused.fetch_add(1, Ordering::Relaxed); + if whole != streamed { + other_error.fetch_add(1, Ordering::Relaxed); + } + prop_assert_eq!(whole, streamed, "error texts differ"); + } + (whole, streamed) => prop_assert!( + false, + "whole {:?} and streamed {:?} disagree", + whole.map(|_| ()), + streamed.map(|_| ()) + ), + } + Ok(()) + }, + ); + println!( + "otel_pb_streamed_damaged_bodies: refused {} bodies, {} with another error text", + refused.into_inner(), + other_error.into_inner() + ); + } + + /// The cap on the decoded size of one record refuses the record before it is + /// decoded, and only a record over it + #[test] + fn oversized_records_are_refused_before_decoding() { + let span = Span { + events: vec![Event::default(); 1 << 16], + ..Default::default() + }; + let request = Req::Traces(TracesData { + resource_spans: vec![ResourceSpans { + scope_spans: vec![ScopeSpans { + spans: vec![span], + ..Default::default() + }], + ..Default::default() + }], + }); + let body = web::Bytes::from(request.encode_pb()); + let estimate = crate::otel::decoded_size::leaf_decoded_size( + &request_span_bytes(&request), + crate::otel::decoded_size::Leaf::Span, + ); + let (_, allocated) = crate::test_alloc::measure(|| { + size_request(body.clone(), Signal::Traces, estimate - 1, false) + }); + assert!(matches!( + size_request(body.clone(), Signal::Traces, estimate - 1, false), + Err(StreamError::RecordTooLarge { .. }) + )); + assert!(allocated.peak < 64 * 1024, "peak {} B", allocated.peak); + let size = size_request(body, Signal::Traces, estimate, false).unwrap(); + assert_eq!(size.rows, 1 << 16); + } + + fn request_span_bytes(request: &Req) -> Vec { + match request { + Req::Traces(data) => data.resource_spans[0].scope_spans[0].spans[0].encode_to_vec(), + _ => unreachable!(), + } + } +} diff --git a/src/otel.rs b/src/otel.rs index 423f68cc8..9d4128c15 100644 --- a/src/otel.rs +++ b/src/otel.rs @@ -16,10 +16,12 @@ * */ +pub mod decoded_size; pub mod expansion; pub mod logs; pub mod metrics; pub mod otel_utils; +pub mod protobuf_stream; pub mod sink; pub mod traces; diff --git a/src/otel/decoded_size.rs b/src/otel/decoded_size.rs new file mode 100644 index 000000000..cc1304e30 --- /dev/null +++ b/src/otel/decoded_size.rs @@ -0,0 +1,482 @@ +/* + * Parseable Server (C) 2022 - 2025 Parseable, Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + */ + +//! The memory an OTLP export request takes once decoded, estimated before it is decoded. +//! +//! Decoding allocates far more than the body holds for small messages: an empty span is +//! two bytes of protobuf and a `Span` of a few hundred bytes, an empty attribute two bytes +//! and a `KeyValue` of 64. A body inside the payload limit could ask for gigabytes. The +//! estimate walks the body against the OTLP schema without allocating, adding up the heap +//! memory the decoded request holds: every `Vec` of messages or numbers, at the capacity +//! that pushing its elements one by one grows it to, as prost does, and every string and +//! bytes field, which prost allocates at its length but at least 8 bytes (a message field +//! held inline, not in a `Vec`, is part of its parent's struct). For a body as prost +//! encodes it, that is exactly what decoding retains, allocator overhead aside; while +//! decoding, a `Vec` that grows holds its old and new buffers at once for a moment. +//! +//! The same walk runs over the `Value` tree of an OTLP JSON body before it is mapped to +//! the typed messages, so both encodings of a request are refused alike. A JSON body has +//! already been parsed by then; the walk bounds the typed copy made from it. It counts +//! the text of a hex or base64 field, more than the bytes it decodes to. + +use std::mem::size_of; + +use opentelemetry_proto::tonic::common::v1::{AnyValue, EntityRef, KeyValue}; +use opentelemetry_proto::tonic::logs::v1::{LogRecord, ResourceLogs, ScopeLogs}; +use opentelemetry_proto::tonic::metrics::v1::{ + Exemplar, ExponentialHistogramDataPoint, HistogramDataPoint, Metric, NumberDataPoint, + ResourceMetrics, ScopeMetrics, SummaryDataPoint, summary_data_point::ValueAtQuantile, +}; +use opentelemetry_proto::tonic::trace::v1::{ + ResourceSpans, ScopeSpans, Span, + span::{Event, Link}, +}; + +/// The leaf records the request is decoded one at a time in (see `protobuf_stream`) +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Leaf { + LogRecord, + Span, + Metric, +} + +/// Estimated bytes one leaf record takes once prost decodes `body` (its encoding, +/// without a length prefix) on its own: its struct and everything its fields allocate. +/// For a record prost encoded this equals what decoding retains; a record that repeats +/// a singular message field can retain up to twice its estimate (prost merges the +/// occurrences into one `Vec` that grows past the sum of their capacities). A record +/// whose framing breaks is counted up to the break, where decoding it fails too. +pub fn leaf_decoded_size(body: &[u8], leaf: Leaf) -> usize { + let (msg, own) = match leaf { + Leaf::LogRecord => (Msg::LogRecord, size_of::()), + Leaf::Span => (Msg::Span, size_of::()), + Leaf::Metric => (Msg::Metric, size_of::()), + }; + let mut size = own; + // A leaf is three messages deep in its request + let _ = scan(body, msg, 3, &mut size); + size +} + +/// Messages of the OTLP schema whose fields allocate when decoded. Leaf records are +/// sized on their own (`leaf_decoded_size`); the levels above them are walked by +/// prost in `protobuf_stream`, so their variants are only reached from each other. +#[allow(dead_code)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Msg { + LogsRequest, + ResourceLogs, + ScopeLogs, + LogRecord, + TracesRequest, + ResourceSpans, + ScopeSpans, + Span, + Event, + Link, + Status, + MetricsRequest, + ResourceMetrics, + ScopeMetrics, + Metric, + /// `Gauge`, `Sum`: their data points + NumberPoints, + Histogram, + ExponentialHistogram, + Summary, + NumberDataPoint, + HistogramDataPoint, + ExponentialHistogramDataPoint, + Buckets, + SummaryDataPoint, + ValueAtQuantile, + Exemplar, + Resource, + EntityRef, + Scope, + KeyValue, + AnyValue, + /// `ArrayValue`, `KeyValueList`: their values + ArrayValue, + KeyValueList, +} + +/// What a field allocates when decoded +#[derive(Debug, Clone, Copy)] +enum Kind { + /// A message: its struct if it is held in a `Vec`, and what its fields allocate + Message(Msg), + /// A string or bytes: its bytes, and a `String` if it is held in a `Vec` + Bytes, + /// A repeated 8-byte number, a `u64` or `f64` slot each + Numbers(Encoding), +} + +/// Wire encoding of the elements of a repeated number field +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Encoding { + Varint, + Fixed64, +} + +#[derive(Debug, Clone, Copy)] +struct Field { + kind: Kind, + /// For a repeated field, which of the `SLOTS` counters of its message counts its + /// elements; every repeated field of a message has its own + slot: Option, +} + +/// Repeated fields a message has at most (`HistogramDataPoint` has 4) +const SLOTS: usize = 4; + +const fn one(kind: Kind) -> Option { + Some(Field { kind, slot: None }) +} + +const fn many(slot: usize, kind: Kind) -> Option { + Some(Field { + kind, + slot: Some(slot), + }) +} + +impl Kind { + /// Bytes of one element of a `Vec` of this kind + fn element_size(self) -> usize { + match self { + Self::Message(msg) => msg.size(), + Self::Bytes => size_of::(), + Self::Numbers(_) => size_of::(), + } + } +} + +/// Bytes a `Vec` of `len` elements of `element_size` bytes holds once they were pushed one +/// by one: the standard library starts at 4 elements (8 for 1-byte elements, 1 for +/// elements over 1 KiB) and doubles +fn vec_capacity_bytes(len: usize, element_size: usize) -> usize { + if len == 0 || element_size == 0 { + return 0; + } + let first = match element_size { + 1 => 8, + 2..=1024 => 4, + _ => 1, + }; + len.checked_next_power_of_two() + .unwrap_or(usize::MAX) + .max(first) + .saturating_mul(element_size) +} + +/// Bytes prost allocates for a string or bytes field of `len` bytes +fn bytes_capacity(len: usize) -> usize { + vec_capacity_bytes(len.min(1), 1).max(len) +} + +/// Counts the elements of the repeated fields of one message, and adds the `Vec`s that +/// hold them once the message is done +#[derive(Default)] +struct Vecs { + lens: [usize; SLOTS], + element_sizes: [usize; SLOTS], +} + +impl Vecs { + fn push(&mut self, slot: usize, kind: Kind, elements: usize) { + self.lens[slot] = self.lens[slot].saturating_add(elements); + self.element_sizes[slot] = kind.element_size(); + } + + fn add_to(&self, size: &mut usize) { + for (&len, &element_size) in self.lens.iter().zip(&self.element_sizes) { + add(size, vec_capacity_bytes(len, element_size)); + } + } +} + +use Kind::{Bytes, Message as M, Numbers}; + +impl Msg { + /// Bytes of the struct a message held in a `Vec` adds + fn size(self) -> usize { + match self { + Self::LogsRequest | Self::TracesRequest | Self::MetricsRequest => 0, + Self::ResourceLogs => size_of::(), + Self::ScopeLogs => size_of::(), + Self::LogRecord => size_of::(), + Self::ResourceSpans => size_of::(), + Self::ScopeSpans => size_of::(), + Self::Span => size_of::(), + Self::Event => size_of::(), + Self::Link => size_of::(), + Self::ResourceMetrics => size_of::(), + Self::ScopeMetrics => size_of::(), + Self::Metric => size_of::(), + Self::NumberDataPoint => size_of::(), + Self::HistogramDataPoint => size_of::(), + Self::ExponentialHistogramDataPoint => size_of::(), + Self::SummaryDataPoint => size_of::(), + Self::ValueAtQuantile => size_of::(), + Self::Exemplar => size_of::(), + Self::EntityRef => size_of::(), + Self::KeyValue => size_of::(), + Self::AnyValue => size_of::(), + // Only ever held inline in their parent + Self::Status + | Self::NumberPoints + | Self::Histogram + | Self::ExponentialHistogram + | Self::Summary + | Self::Buckets + | Self::Resource + | Self::Scope + | Self::ArrayValue + | Self::KeyValueList => 0, + } + } + + /// The field with protobuf field number `number`, `None` for a field that allocates + /// nothing (a number, a bool, an enum) or that the schema does not have + fn field(self, number: u64) -> Option { + match (self, number) { + (Self::LogsRequest, 1) => many(0, M(Self::ResourceLogs)), + (Self::ResourceLogs, 1) => one(M(Self::Resource)), + (Self::ResourceLogs, 2) => many(0, M(Self::ScopeLogs)), + (Self::ScopeLogs, 1) => one(M(Self::Scope)), + (Self::ScopeLogs, 2) => many(0, M(Self::LogRecord)), + (Self::LogRecord, 3 | 9 | 10 | 12) => one(Bytes), + (Self::LogRecord, 5) => one(M(Self::AnyValue)), + (Self::LogRecord, 6) => many(0, M(Self::KeyValue)), + + (Self::TracesRequest, 1) => many(0, M(Self::ResourceSpans)), + (Self::ResourceSpans, 1) => one(M(Self::Resource)), + (Self::ResourceSpans, 2) => many(0, M(Self::ScopeSpans)), + (Self::ScopeSpans, 1) => one(M(Self::Scope)), + (Self::ScopeSpans, 2) => many(0, M(Self::Span)), + (Self::Span, 1..=5) => one(Bytes), + (Self::Span, 9) => many(0, M(Self::KeyValue)), + (Self::Span, 11) => many(1, M(Self::Event)), + (Self::Span, 13) => many(2, M(Self::Link)), + (Self::Span, 15) => one(M(Self::Status)), + (Self::Event, 2) => one(Bytes), + (Self::Event, 3) => many(0, M(Self::KeyValue)), + (Self::Link, 1..=3) => one(Bytes), + (Self::Link, 4) => many(0, M(Self::KeyValue)), + (Self::Status, 2) => one(Bytes), + + (Self::MetricsRequest, 1) => many(0, M(Self::ResourceMetrics)), + (Self::ResourceMetrics, 1) => one(M(Self::Resource)), + (Self::ResourceMetrics, 2) => many(0, M(Self::ScopeMetrics)), + (Self::ScopeMetrics, 1) => one(M(Self::Scope)), + (Self::ScopeMetrics, 2) => many(0, M(Self::Metric)), + (Self::Metric, 1..=3) => one(Bytes), + (Self::Metric, 5 | 7) => one(M(Self::NumberPoints)), + (Self::Metric, 9) => one(M(Self::Histogram)), + (Self::Metric, 10) => one(M(Self::ExponentialHistogram)), + (Self::Metric, 11) => one(M(Self::Summary)), + (Self::Metric, 12) => many(0, M(Self::KeyValue)), + (Self::NumberPoints, 1) => many(0, M(Self::NumberDataPoint)), + (Self::Histogram, 1) => many(0, M(Self::HistogramDataPoint)), + (Self::ExponentialHistogram, 1) => many(0, M(Self::ExponentialHistogramDataPoint)), + (Self::Summary, 1) => many(0, M(Self::SummaryDataPoint)), + (Self::NumberDataPoint, 7) => many(0, M(Self::KeyValue)), + (Self::NumberDataPoint, 5) => many(1, M(Self::Exemplar)), + (Self::HistogramDataPoint, 9) => many(0, M(Self::KeyValue)), + (Self::HistogramDataPoint, 6) => many(1, Numbers(Encoding::Fixed64)), + (Self::HistogramDataPoint, 7) => many(2, Numbers(Encoding::Fixed64)), + (Self::HistogramDataPoint, 8) => many(3, M(Self::Exemplar)), + (Self::ExponentialHistogramDataPoint, 1) => many(0, M(Self::KeyValue)), + (Self::ExponentialHistogramDataPoint, 8 | 9) => one(M(Self::Buckets)), + (Self::ExponentialHistogramDataPoint, 11) => many(1, M(Self::Exemplar)), + (Self::Buckets, 2) => many(0, Numbers(Encoding::Varint)), + (Self::SummaryDataPoint, 7) => many(0, M(Self::KeyValue)), + (Self::SummaryDataPoint, 6) => many(1, M(Self::ValueAtQuantile)), + (Self::Exemplar, 7) => many(0, M(Self::KeyValue)), + (Self::Exemplar, 4 | 5) => one(Bytes), + + ( + Self::ResourceLogs + | Self::ScopeLogs + | Self::ResourceSpans + | Self::ScopeSpans + | Self::ResourceMetrics + | Self::ScopeMetrics, + 3, + ) => one(Bytes), + (Self::Resource, 1) => many(0, M(Self::KeyValue)), + (Self::Resource, 3) => many(1, M(Self::EntityRef)), + (Self::EntityRef, 1 | 2) => one(Bytes), + (Self::EntityRef, 3) => many(0, Bytes), + (Self::EntityRef, 4) => many(1, Bytes), + (Self::Scope, 1 | 2) => one(Bytes), + (Self::Scope, 3) => many(0, M(Self::KeyValue)), + (Self::KeyValue, 1) => one(Bytes), + (Self::KeyValue, 2) => one(M(Self::AnyValue)), + (Self::AnyValue, 1 | 7) => one(Bytes), + (Self::AnyValue, 5) => one(M(Self::ArrayValue)), + (Self::AnyValue, 6) => one(M(Self::KeyValueList)), + (Self::ArrayValue, 1) => many(0, M(Self::AnyValue)), + (Self::KeyValueList, 1) => many(0, M(Self::KeyValue)), + _ => None, + } + } +} + +/// Deeper than prost decodes: a body nested this deep fails to decode before reaching it +const MAX_DEPTH: u32 = 128; + +/// The framing of the body is broken, or nested deeper than decoding allows +struct Malformed; + +fn varint(buf: &mut &[u8]) -> Result { + let mut value = 0u64; + for (index, &byte) in buf.iter().enumerate().take(10) { + value |= u64::from(byte & 0x7f) << (7 * index); + if byte < 0x80 { + *buf = &buf[index + 1..]; + return Ok(value); + } + } + Err(Malformed) +} + +fn take<'a>(buf: &mut &'a [u8], len: u64) -> Result<&'a [u8], Malformed> { + let len = usize::try_from(len).map_err(|_| Malformed)?; + if len > buf.len() { + return Err(Malformed); + } + let (taken, rest) = buf.split_at(len); + *buf = rest; + Ok(taken) +} + +const VARINT: u64 = 0; +const FIXED64: u64 = 1; +const LEN: u64 = 2; +const START_GROUP: u64 = 3; +const END_GROUP: u64 = 4; +const FIXED32: u64 = 5; + +/// Skips a field of wire type `wire`, the way decoding skips a field it does not know +fn skip(buf: &mut &[u8], wire: u64, number: u64, depth: u32) -> Result<(), Malformed> { + match wire { + VARINT => varint(buf).map(drop), + FIXED64 => take(buf, 8).map(drop), + LEN => { + let len = varint(buf)?; + take(buf, len).map(drop) + } + FIXED32 => take(buf, 4).map(drop), + START_GROUP => { + if depth >= MAX_DEPTH { + return Err(Malformed); + } + loop { + let (inner, inner_wire) = key(buf)?; + if inner_wire == END_GROUP { + return if inner == number { + Ok(()) + } else { + Err(Malformed) + }; + } + skip(buf, inner_wire, inner, depth + 1)?; + } + } + _ => Err(Malformed), + } +} + +fn key(buf: &mut &[u8]) -> Result<(u64, u64), Malformed> { + let key = varint(buf)?; + if key > u64::from(u32::MAX) || key >> 3 == 0 { + return Err(Malformed); + } + Ok((key >> 3, key & 7)) +} + +fn add(size: &mut usize, bytes: usize) { + *size = size.saturating_add(bytes); +} + +/// Adds what decoding `buf` as a `msg` allocates to `size`, up to where its framing breaks +fn scan(mut buf: &[u8], msg: Msg, depth: u32, size: &mut usize) -> Result<(), Malformed> { + let mut vecs = Vecs::default(); + // The `Vec`s of a message cut short count too: decoding allocated them before failing + let result = scan_fields(&mut buf, msg, depth, size, &mut vecs); + vecs.add_to(size); + result +} + +fn scan_fields( + buf: &mut &[u8], + msg: Msg, + depth: u32, + size: &mut usize, + vecs: &mut Vecs, +) -> Result<(), Malformed> { + while !buf.is_empty() { + let (number, wire) = key(buf)?; + match (msg.field(number), wire) { + (Some(Field { kind, slot }), LEN) => { + let len = varint(buf)?; + let body = take(buf, len)?; + let elements = match kind { + Kind::Message(child) => { + if depth >= MAX_DEPTH { + return Err(Malformed); + } + scan(body, child, depth + 1, size)?; + 1 + } + Kind::Bytes => { + add(size, bytes_capacity(body.len())); + 1 + } + // Packed + Kind::Numbers(Encoding::Varint) => { + body.iter().filter(|&&byte| byte < 0x80).count() + } + Kind::Numbers(Encoding::Fixed64) => body.len() / size_of::(), + }; + if let Some(slot) = slot { + vecs.push(slot, kind, elements); + } + } + // One unpacked element + ( + Some(Field { + kind: kind @ Kind::Numbers(encoding), + slot: Some(slot), + }), + VARINT | FIXED64, + ) => { + skip(buf, wire, number, depth)?; + if (encoding == Encoding::Varint) == (wire == VARINT) { + vecs.push(slot, kind, 1); + } + } + // A field that allocates nothing, a field the schema does not have, or a field + // of the wrong wire type, which fails decoding + _ => skip(buf, wire, number, depth)?, + } + } + Ok(()) +} diff --git a/src/otel/expansion.rs b/src/otel/expansion.rs index 74523f766..a3fd8749b 100644 --- a/src/otel/expansion.rs +++ b/src/otel/expansion.rs @@ -216,26 +216,50 @@ fn log_record_bytes(record: &LogRecord) -> usize { + hex_field("trace_id", record.trace_id.len()) } +/// Sizes a logs request one part at a time, in the order of the request +#[derive(Debug, Default)] +pub struct LogsSizer { + size: RequestSize, + resource: usize, + shared: usize, +} + +impl LogsSizer { + pub fn resource(&mut self, resource: Option<&Resource>, schema_url: &str) { + self.resource = resource_bytes(resource) + str_field("schema_url", schema_url.len()); + } + + pub fn scope(&mut self, scope: Option<&InstrumentationScope>, schema_url: &str) { + self.shared = VALUE_BYTES + + self.resource + + scope_bytes(scope) + + str_field("scope_log_schema_url", schema_url.len()); + } + + pub fn record(&mut self, record: &LogRecord) { + self.size.records += 1; + self.size.add_rows(1, self.shared); + self.size.add_bytes(log_record_bytes(record)); + } + + pub fn finish(self) -> RequestSize { + self.size + } +} + /// Rows and row bytes of a logs request pub fn logs_size(resource_logs: &[ResourceLogs]) -> RequestSize { - let mut size = RequestSize::default(); + let mut sizer = LogsSizer::default(); for resource_log in resource_logs { - let resource = resource_bytes(resource_log.resource.as_ref()) - + str_field("schema_url", resource_log.schema_url.len()); + sizer.resource(resource_log.resource.as_ref(), &resource_log.schema_url); for scope_log in &resource_log.scope_logs { - let shared = VALUE_BYTES - + resource - + scope_bytes(scope_log.scope.as_ref()) - + str_field("scope_log_schema_url", scope_log.schema_url.len()); - let records = scope_log.log_records.len() as u64; - size.records += records; - size.add_rows(records, shared); + sizer.scope(scope_log.scope.as_ref(), &scope_log.schema_url); for record in &scope_log.log_records { - size.add_bytes(log_record_bytes(record)); + sizer.record(record); } } } - size + sizer.finish() } // --------------------------------------------------------------------------- @@ -284,31 +308,57 @@ fn link_bytes(link: &Link) -> usize { + num_field("link_dropped_attributes_count") } +/// Sizes a traces request one part at a time, in the order of the request +#[derive(Debug, Default)] +pub struct TracesSizer { + size: RequestSize, + resource: usize, + shared: usize, +} + +impl TracesSizer { + pub fn resource(&mut self, resource: Option<&Resource>, schema_url: &str) { + self.resource = + resource_bytes(resource) + str_field("resource_schema_url", schema_url.len()); + } + + pub fn scope(&mut self, scope: Option<&InstrumentationScope>, schema_url: &str) { + self.shared = VALUE_BYTES + + self.resource + + scope_bytes(scope) + + str_field("scope_schema_url", schema_url.len()); + } + + pub fn span(&mut self, span: &Span) { + self.size.records += 1; + let rows = (span.events.len() + span.links.len()).max(1) as u64; + self.size.add_rows(rows, self.shared + span_bytes(span)); + for event in &span.events { + self.size.add_bytes(event_bytes(event)); + } + for link in &span.links { + self.size.add_bytes(link_bytes(link)); + } + } + + pub fn finish(self) -> RequestSize { + self.size + } +} + /// Rows and row bytes of a traces request pub fn traces_size(resource_spans: &[ResourceSpans]) -> RequestSize { - let mut size = RequestSize::default(); + let mut sizer = TracesSizer::default(); for resource_span in resource_spans { - let resource = resource_bytes(resource_span.resource.as_ref()) - + str_field("resource_schema_url", resource_span.schema_url.len()); + sizer.resource(resource_span.resource.as_ref(), &resource_span.schema_url); for scope_span in &resource_span.scope_spans { - let shared = VALUE_BYTES - + resource - + scope_bytes(scope_span.scope.as_ref()) - + str_field("scope_schema_url", scope_span.schema_url.len()); - size.records += scope_span.spans.len() as u64; + sizer.scope(scope_span.scope.as_ref(), &scope_span.schema_url); for span in &scope_span.spans { - let rows = (span.events.len() + span.links.len()).max(1) as u64; - size.add_rows(rows, shared + span_bytes(span)); - for event in &span.events { - size.add_bytes(event_bytes(event)); - } - for link in &span.links { - size.add_bytes(link_bytes(link)); - } + sizer.span(span); } } } - size + sizer.finish() } // --------------------------------------------------------------------------- @@ -470,53 +520,92 @@ fn metric_points(metric: &Metric, flatten_exemplars: bool, row: usize, size: &mu } } -/// Rows and row bytes of a metrics request -pub fn metrics_size(resource_metrics: &[ResourceMetrics], flatten_exemplars: bool) -> RequestSize { - let mut size = RequestSize::default(); - for resource_metric in resource_metrics { +/// Sizes a metrics request one part at a time, in the order of the request +#[derive(Debug, Default)] +pub struct MetricsSizer { + size: RequestSize, + flatten_exemplars: bool, + identity: bool, + resource: usize, + envelope: usize, + any_rows: bool, +} + +impl MetricsSizer { + pub fn new(flatten_exemplars: bool) -> Self { + Self { + flatten_exemplars, + ..Self::default() + } + } + + pub fn resource(&mut self, resource: Option<&Resource>, schema_url: &str) { // Built once per resource, as the flattener does, since the identity is // read from the flattened resource fields - let identity = super::metrics::ResourceMetricFields::new( - resource_metric.resource.as_ref(), - &resource_metric.schema_url, - ) - .has_target_identity(); - let resource = resource_bytes(resource_metric.resource.as_ref()) - + str_field("resource_schema_url", resource_metric.schema_url.len()) - + if identity { + self.identity = + super::metrics::ResourceMetricFields::new(resource, schema_url).has_target_identity(); + self.resource = resource_bytes(resource) + + str_field("resource_schema_url", schema_url.len()) + + if self.identity { str_field("job", 32) + str_field("instance", 32) } else { 0 }; - let mut any_rows = false; - for scope_metric in &resource_metric.scope_metrics { - let envelope = resource - + scope_bytes(scope_metric.scope.as_ref()) - + str_field("scope_schema_url", scope_metric.schema_url.len()); - size.records += scope_metric.metrics.len() as u64; - for metric in &scope_metric.metrics { - let row = VALUE_BYTES - + envelope - + str_field("metric_name", metric.name.len()) - + str_field("metric_description", metric.description.len()) - + str_field("metric_unit", metric.unit.len()) - + str_field("metric_type", 21) - + attributes_bytes(&metric.metadata, 0) - + num_field(super::metrics::SERIES_HASH_COLUMN); - any_rows |= metric.data.is_some(); - metric_points(metric, flatten_exemplars, row, &mut size); - } - } - if identity && any_rows { + self.any_rows = false; + } + + pub fn scope(&mut self, scope: Option<&InstrumentationScope>, schema_url: &str) { + self.envelope = + self.resource + scope_bytes(scope) + str_field("scope_schema_url", schema_url.len()); + } + + pub fn metric(&mut self, metric: &Metric) { + self.size.records += 1; + let row = VALUE_BYTES + + self.envelope + + str_field("metric_name", metric.name.len()) + + str_field("metric_description", metric.description.len()) + + str_field("metric_unit", metric.unit.len()) + + str_field("metric_type", 21) + + attributes_bytes(&metric.metadata, 0) + + num_field(super::metrics::SERIES_HASH_COLUMN); + self.any_rows |= metric.data.is_some(); + metric_points(metric, self.flatten_exemplars, row, &mut self.size); + } + + pub fn resource_end(&mut self) { + if self.identity && self.any_rows { // target_info - size.add_rows( + self.size.add_rows( 1, VALUE_BYTES - + resource + + self.resource + 6 * str_field("metric_description", 16) + num_field(super::metrics::SERIES_HASH_COLUMN), ); } } - size + + pub fn finish(self) -> RequestSize { + self.size + } +} + +/// Rows and row bytes of a metrics request +pub fn metrics_size(resource_metrics: &[ResourceMetrics], flatten_exemplars: bool) -> RequestSize { + let mut sizer = MetricsSizer::new(flatten_exemplars); + for resource_metric in resource_metrics { + sizer.resource( + resource_metric.resource.as_ref(), + &resource_metric.schema_url, + ); + for scope_metric in &resource_metric.scope_metrics { + sizer.scope(scope_metric.scope.as_ref(), &scope_metric.schema_url); + for metric in &scope_metric.metrics { + sizer.metric(metric); + } + } + sizer.resource_end(); + } + sizer.finish() } diff --git a/src/otel/logs.rs b/src/otel/logs.rs index 114ec315f..5002aaa85 100644 --- a/src/otel/logs.rs +++ b/src/otel/logs.rs @@ -506,7 +506,7 @@ pub fn log_record_row( /// Hands the row of every log record of `resource_logs` to `sink`, one at a time. /// The JSON bodies of every record are charged to `budget`, which all records of the /// request share, before their rows are built. -pub fn flatten_logs_into( +pub fn flatten_logs_into( resource_logs: &[ResourceLogs], budget: &mut FlattenBudget, sink: &mut S, diff --git a/src/otel/metrics.rs b/src/otel/metrics.rs index dd9c953ab..cf9bcc69e 100644 --- a/src/otel/metrics.rs +++ b/src/otel/metrics.rs @@ -797,7 +797,7 @@ impl ResourceMetricFields { /// Hands the rows of every metric of one scope to `sink`, tracking in `latest` the /// latest `time_unix_nano` of the rows for the resource's `target_info` row -pub fn metric_rows_into( +pub fn metric_rows_into( metric: &Metric, envelope: &Map, flatten_exemplars: bool, @@ -836,7 +836,7 @@ pub fn metric_rows_into( /// Hands the rows of every metric of `resource_metrics` to `sink`, one at a time, /// with one `target_info` row after the rows of each resource that has a /// Prometheus target identity -pub fn flatten_metrics_into( +pub fn flatten_metrics_into( resource_metrics: &[ResourceMetrics], flatten_exemplars: bool, sink: &mut S, diff --git a/src/otel/protobuf_stream.rs b/src/otel/protobuf_stream.rs new file mode 100644 index 000000000..cb4434a2b --- /dev/null +++ b/src/otel/protobuf_stream.rs @@ -0,0 +1,661 @@ +/* + * Parseable Server (C) 2022 - 2025 Parseable, Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + */ + +//! Decodes an OTLP/HTTP protobuf export request one leaf record (`LogRecord`, +//! `Span`, `Metric`) at a time, instead of decoding the whole request first. +//! +//! The request, resource and scope levels are messages of their own here, which +//! prost drives exactly as it drives the generated ones: the same keys, wire type +//! checks, recursion limit, unknown-field skipping and error messages (each error +//! gets the `Message.field` path the generated code would push). Their fields are +//! merged as prost merges them, so a singular field that occurs more than once +//! (`resource`, `scope`, `schema_url`) ends up as whole-request decoding leaves it, +//! whatever the field order. The repeated children of a level are not decoded +//! where they occur: their bytes are kept (`Bytes`, so not copied) with the decode +//! context prost would use for them, and decoded once the level is read whole, one +//! at a time. A leaf record is decoded by `prost::encoding::message::merge`, as +//! whole-request decoding decodes it, once its decoded size is known to be under +//! a cap ([`max_record_bytes`]). + +use bytes::{Buf, Bytes}; +use opentelemetry_proto::tonic::common::v1::InstrumentationScope; +use opentelemetry_proto::tonic::logs::v1::LogRecord; +use opentelemetry_proto::tonic::metrics::v1::Metric; +use opentelemetry_proto::tonic::resource::v1::Resource; +use opentelemetry_proto::tonic::trace::v1::Span; +use prost::encoding::{ + DecodeContext, WireType, check_wire_type, decode_varint, message, skip_field, string, +}; +use prost::{DecodeError, Message}; + +use std::convert::Infallible; +use std::marker::PhantomData; +use std::sync::atomic::{AtomicBool, Ordering}; + +use serde_json::Map; + +use super::decoded_size::{Leaf, leaf_decoded_size}; +use super::expansion::{LogsSizer, MetricsSizer, RequestSize, TracesSizer}; +use super::logs::{log_record_row, resource_log_fields, scope_log_fields}; +use super::metrics::{ResourceMetricFields, metric_rows_into}; +use super::sink::RowSink; +use super::traces::{SpanParents, resource_span_fields, scope_span_fields, span_rows}; +use crate::utils::json::flatten::FlattenBudget; + +/// Most memory one leaf record may take once decoded, for a payload limit of +/// `max_payload` bytes: 16 bytes per payload byte. Realistic records decode to +/// 2.4-4.2 bytes per byte, exponential histograms with small buckets to 12.5; a +/// span of 2 million empty events decodes to 32 bytes per byte. +pub fn max_record_bytes(max_payload: usize) -> usize { + max_payload.saturating_mul(16) +} + +/// Why a body could not be read, or what the consumer of its records refused +#[derive(Debug)] +pub enum StreamError { + /// The body is not a valid request; the error prost gives for it + Decode(DecodeError), + /// A leaf record would take more than `limit` bytes once decoded + RecordTooLarge { leaf: Leaf, limit: usize }, + /// The consumer refused a record + Consumer(E), +} + +impl StreamError { + /// The same error, with a refusal of the consumer mapped by `f` + pub fn map_consumer(self, f: impl FnOnce(E) -> F) -> StreamError { + match self { + Self::Decode(e) => StreamError::Decode(e), + Self::RecordTooLarge { leaf, limit } => StreamError::RecordTooLarge { leaf, limit }, + Self::Consumer(e) => StreamError::Consumer(f(e)), + } + } +} + +/// What a request is made of, in the order its records are read +pub enum Item { + /// A resource level starts: its `resource` and `schema_url` + Resource(Option, String), + /// A scope level of the current resource starts + Scope(Option, String), + /// A leaf record of the current scope + Record(L), + /// The current resource level ends + ResourceEnd, +} + +/// The names prost's error messages use for the levels of one signal +pub struct Names { + request: &'static str, + resources: &'static str, + resource_level: &'static str, + scopes: &'static str, + scope_level: &'static str, + records: &'static str, +} + +pub const LOGS: Names = Names { + request: "ExportLogsServiceRequest", + resources: "resource_logs", + resource_level: "ResourceLogs", + scopes: "scope_logs", + scope_level: "ScopeLogs", + records: "log_records", +}; + +pub const TRACES: Names = Names { + request: "ExportTraceServiceRequest", + resources: "resource_spans", + resource_level: "ResourceSpans", + scopes: "scope_spans", + scope_level: "ScopeSpans", + records: "spans", +}; + +pub const METRICS: Names = Names { + request: "ExportMetricsServiceRequest", + resources: "resource_metrics", + resource_level: "ResourceMetrics", + scopes: "scope_metrics", + scope_level: "ScopeMetrics", + records: "metrics", +}; + +/// A leaf record type and how it is measured +pub trait LeafRecord: Message + Default { + const LEAF: Leaf; +} + +impl LeafRecord for LogRecord { + const LEAF: Leaf = Leaf::LogRecord; +} + +impl LeafRecord for Span { + const LEAF: Leaf = Leaf::Span; +} + +impl LeafRecord for Metric { + const LEAF: Leaf = Leaf::Metric; +} + +/// A length-delimited child kept for later: where it starts in the body (at its +/// length prefix) and the context prost would decode it with there. It is decoded +/// from the rest of the body, as prost decodes it: a broken length inside it can +/// run past its end before decoding fails, and fails the way it fails in place. +struct Child { + start: usize, + prefix: usize, + len: usize, + ctx: DecodeContext, +} + +impl Child { + /// Steps over the child at the front of `buf` (the end of a body of `body_len` + /// bytes), failing like prost's `message::merge_repeated` on its framing + fn take( + wire_type: WireType, + buf: &mut impl Buf, + body_len: usize, + ctx: DecodeContext, + ) -> Result { + check_wire_type(WireType::LengthDelimited, wire_type)?; + let start = body_len - buf.remaining(); + let mut peek = buf.chunk(); + let contiguous = peek.len(); + let len = decode_varint(&mut peek)?; + let prefix = contiguous - peek.len(); + if len > (buf.remaining() - prefix) as u64 { + return Err(DecodeError::new("buffer underflow")); + } + buf.advance(prefix + len as usize); + Ok(Self { + start, + prefix, + len: len as usize, + ctx, + }) + } + + /// Decodes the child into `msg`, as prost decodes it where it occurs + fn merge(self, body: &Bytes, msg: &mut M) -> Result<(), DecodeError> { + message::merge( + WireType::LengthDelimited, + msg, + &mut body.slice(self.start..), + self.ctx, + ) + } + + /// The encoding of the child, without its length prefix + fn body<'b>(&self, body: &'b [u8]) -> &'b [u8] { + &body[self.start + self.prefix..self.start + self.prefix + self.len] + } +} + +fn push(mut error: DecodeError, message: &'static str, field: &'static str) -> DecodeError { + error.push(message, field); + error +} + +/// The request level: the resource levels, kept +struct RequestLevel { + names: &'static Names, + body_len: usize, + children: Vec, +} + +impl Message for RequestLevel { + fn encode_raw(&self, _buf: &mut impl bytes::BufMut) { + unreachable!("only decoded") + } + + fn merge_field( + &mut self, + tag: u32, + wire_type: WireType, + buf: &mut impl Buf, + ctx: DecodeContext, + ) -> Result<(), DecodeError> { + if tag == 1 { + let child = Child::take(wire_type, buf, self.body_len, ctx) + .map_err(|e| push(e, self.names.request, self.names.resources))?; + self.children.push(child); + Ok(()) + } else { + skip_field(wire_type, tag, buf, ctx) + } + } + + fn encoded_len(&self) -> usize { + 0 + } + + fn clear(&mut self) { + self.children.clear(); + } +} + +/// A resource or scope level: its singular fields, merged, and its children, kept +struct Level

{ + body_len: usize, + message: &'static str, + parent_field: &'static str, + children_field: &'static str, + parent: Option

, + schema_url: String, + children: Vec, +} + +impl

Level

{ + fn new( + body_len: usize, + message: &'static str, + parent_field: &'static str, + children_field: &'static str, + ) -> Self { + Self { + body_len, + message, + parent_field, + children_field, + parent: None, + schema_url: String::new(), + children: Vec::new(), + } + } +} + +impl Message for Level

{ + fn encode_raw(&self, _buf: &mut impl bytes::BufMut) { + unreachable!("only decoded") + } + + fn merge_field( + &mut self, + tag: u32, + wire_type: WireType, + buf: &mut impl Buf, + ctx: DecodeContext, + ) -> Result<(), DecodeError> { + match tag { + 1 => message::merge( + wire_type, + self.parent.get_or_insert_with(Default::default), + buf, + ctx, + ) + .map_err(|e| push(e, self.message, self.parent_field)), + 2 => { + let child = Child::take(wire_type, buf, self.body_len, ctx) + .map_err(|e| push(e, self.message, self.children_field))?; + self.children.push(child); + Ok(()) + } + 3 => string::merge(wire_type, &mut self.schema_url, buf, ctx) + .map_err(|e| push(e, self.message, "schema_url")), + _ => skip_field(wire_type, tag, buf, ctx), + } + } + + fn encoded_len(&self) -> usize { + 0 + } + + fn clear(&mut self) { + self.parent = None; + self.schema_url.clear(); + self.children.clear(); + } +} + +/// Reads the request `body` of the signal `names` belongs to and hands its items to +/// `consume` in order, one leaf record at a time. Records whose decoded size is over +/// `max_record` are refused before they are decoded. +pub fn read_request( + body: Bytes, + names: &'static Names, + max_record: usize, + mut consume: impl FnMut(Item) -> Result<(), E>, +) -> Result<(), StreamError> { + let body_len = body.len(); + let mut request = RequestLevel { + names, + body_len, + children: Vec::new(), + }; + request.merge(body.clone()).map_err(StreamError::Decode)?; + for resource_child in request.children { + let mut resource = + Level::::new(body_len, names.resource_level, "resource", names.scopes); + resource_child + .merge(&body, &mut resource) + .map_err(|e| StreamError::Decode(push(e, names.request, names.resources)))?; + consume(Item::Resource(resource.parent, resource.schema_url)) + .map_err(StreamError::Consumer)?; + for scope_child in resource.children { + let in_resource = |e| { + let e = push(e, names.resource_level, names.scopes); + StreamError::Decode(push(e, names.request, names.resources)) + }; + let mut scope = Level::::new( + body_len, + names.scope_level, + "scope", + names.records, + ); + scope_child.merge(&body, &mut scope).map_err(in_resource)?; + consume(Item::Scope(scope.parent, scope.schema_url)).map_err(StreamError::Consumer)?; + for record_child in scope.children { + if leaf_decoded_size(record_child.body(&body), L::LEAF) > max_record { + return Err(StreamError::RecordTooLarge { + leaf: L::LEAF, + limit: max_record, + }); + } + let mut record = L::default(); + record_child + .merge(&body, &mut record) + .map_err(|e| in_resource(push(e, names.scope_level, names.records)))?; + consume(Item::Record(record)).map_err(StreamError::Consumer)?; + } + } + consume(Item::ResourceEnd).map_err(StreamError::Consumer)?; + } + Ok(()) +} + +/// The signal of a protobuf body +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Signal { + Logs, + Metrics, + Traces, +} + +/// Rows, row bytes, records and data points of the request `body`, read one record +/// at a time (the sizing pass of the expansion cap, see `expansion`) +pub fn size_request( + body: Bytes, + signal: Signal, + max_record: usize, + flatten_exemplars: bool, +) -> Result> { + size_in_levels(body.clone(), signal, max_record, flatten_exemplars).map_err(|error| { + match error { + // Report the break whole-request decoding meets first + StreamError::Decode(_) => match signal { + Signal::Logs => first_error::(body, &LOGS, max_record), + Signal::Traces => first_error::(body, &TRACES, max_record), + Signal::Metrics => first_error::(body, &METRICS, max_record), + } + .unwrap_or(error), + error => error, + } + }) +} + +fn size_in_levels( + body: Bytes, + signal: Signal, + max_record: usize, + flatten_exemplars: bool, +) -> Result> { + match signal { + Signal::Logs => { + let mut sizer = LogsSizer::default(); + read_request::(body, &LOGS, max_record, |item| { + match item { + Item::Resource(resource, url) => sizer.resource(resource.as_ref(), &url), + Item::Scope(scope, url) => sizer.scope(scope.as_ref(), &url), + Item::Record(record) => sizer.record(&record), + Item::ResourceEnd => {} + } + Ok(()) + })?; + Ok(sizer.finish()) + } + Signal::Traces => { + let mut sizer = TracesSizer::default(); + read_request::(body, &TRACES, max_record, |item| { + match item { + Item::Resource(resource, url) => sizer.resource(resource.as_ref(), &url), + Item::Scope(scope, url) => sizer.scope(scope.as_ref(), &url), + Item::Record(span) => sizer.span(&span), + Item::ResourceEnd => {} + } + Ok(()) + })?; + Ok(sizer.finish()) + } + Signal::Metrics => { + let mut sizer = MetricsSizer::new(flatten_exemplars); + read_request::(body, &METRICS, max_record, |item| { + match item { + Item::Resource(resource, url) => sizer.resource(resource.as_ref(), &url), + Item::Scope(scope, url) => sizer.scope(scope.as_ref(), &url), + Item::Record(metric) => sizer.metric(&metric), + Item::ResourceEnd => sizer.resource_end(), + } + Ok(()) + })?; + Ok(sizer.finish()) + } + } +} + +/// Hands the rows of the request `body` to `sink`, decoding one record at a time: +/// the same rows, in the same order, as decoding the whole request and flattening it +pub fn flatten_request( + body: Bytes, + signal: Signal, + max_record: usize, + budget: &mut FlattenBudget, + flatten_exemplars: bool, + sink: &mut S, +) -> Result<(), StreamError> { + match signal { + Signal::Logs => { + let (mut resource_fields, mut scope_fields) = (Map::new(), Map::new()); + read_request::(body, &LOGS, max_record, |item| { + match item { + Item::Resource(resource, url) => { + resource_fields = resource_log_fields(resource.as_ref(), &url) + } + Item::Scope(scope, url) => { + scope_fields = scope_log_fields(scope.as_ref(), &url) + } + Item::Record(record) => { + sink.row(log_record_row( + &record, + &scope_fields, + &resource_fields, + budget, + )?)?; + sink.record_end(); + } + Item::ResourceEnd => {} + } + Ok(()) + }) + } + Signal::Traces => { + let (mut resource_fields, mut scope_fields) = (Map::new(), Map::new()); + let mut scope_url = String::new(); + read_request::(body, &TRACES, max_record, |item| { + match item { + Item::Resource(resource, url) => { + resource_fields = resource_span_fields(resource.as_ref(), &url) + } + Item::Scope(scope, url) => { + scope_fields = scope_span_fields(scope.as_ref()); + scope_url = url; + } + Item::Record(span) => span_rows( + &span, + &SpanParents { + scope_fields: &scope_fields, + scope_schema_url: &scope_url, + resource_fields: &resource_fields, + }, + sink, + )?, + Item::ResourceEnd => {} + } + Ok(()) + }) + } + Signal::Metrics => { + let mut resource: Option = None; + let mut envelope = Map::new(); + let mut latest: Option = None; + read_request::(body, &METRICS, max_record, |item| { + match item { + Item::Resource(r, url) => { + resource = Some(ResourceMetricFields::new(r.as_ref(), &url)); + latest = None; + } + Item::Scope(scope, url) => { + envelope = resource + .as_ref() + .expect("a scope is inside a resource") + .scope_envelope(scope.as_ref(), &url); + } + Item::Record(metric) => { + metric_rows_into(&metric, &envelope, flatten_exemplars, &mut latest, sink)? + } + Item::ResourceEnd => { + if let Some(target) = resource + .take() + .and_then(|resource| resource.target_info(latest.take())) + { + sink.row(target)?; + } + } + } + Ok(()) + }) + } + } +} + +/// One level of `first_error`'s walk: decodes everything in wire order, as prost +/// does, keeping nothing but one record at a time +struct WireOrder<'a, L> { + names: &'static Names, + depth: u8, + max_record: usize, + oversized: &'a AtomicBool, + leaf: PhantomData L>, +} + +impl WireOrder<'_, L> { + fn child(&self) -> WireOrder<'_, L> { + WireOrder { + names: self.names, + depth: self.depth + 1, + max_record: self.max_record, + oversized: self.oversized, + leaf: PhantomData, + } + } +} + +impl Message for WireOrder<'_, L> { + fn encode_raw(&self, _buf: &mut impl bytes::BufMut) { + unreachable!("only decoded") + } + + fn merge_field( + &mut self, + tag: u32, + wire_type: WireType, + buf: &mut impl Buf, + ctx: DecodeContext, + ) -> Result<(), DecodeError> { + let names = self.names; + match (self.depth, tag) { + (0, 1) => message::merge(wire_type, &mut self.child(), buf, ctx) + .map_err(|e| push(e, names.request, names.resources)), + (1, 1) => message::merge(wire_type, &mut Resource::default(), buf, ctx) + .map_err(|e| push(e, names.resource_level, "resource")), + (1, 2) => message::merge(wire_type, &mut self.child(), buf, ctx) + .map_err(|e| push(e, names.resource_level, names.scopes)), + (2, 1) => message::merge(wire_type, &mut InstrumentationScope::default(), buf, ctx) + .map_err(|e| push(e, names.scope_level, "scope")), + (2, 2) => { + // Measured where the framing allows, then decoded in place + let mut peek = buf.chunk(); + if wire_type == WireType::LengthDelimited + && let Ok(len) = decode_varint(&mut peek) + && len <= peek.len() as u64 + && leaf_decoded_size(&peek[..len as usize], L::LEAF) > self.max_record + { + self.oversized.store(true, Ordering::Relaxed); + return Err(DecodeError::new("record over the decoded size cap")); + } + message::merge(wire_type, &mut L::default(), buf, ctx) + .map_err(|e| push(e, names.scope_level, names.records)) + } + (1 | 2, 3) => { + let level = if self.depth == 1 { + names.resource_level + } else { + names.scope_level + }; + string::merge(wire_type, &mut String::new(), buf, ctx) + .map_err(|e| push(e, level, "schema_url")) + } + _ => skip_field(wire_type, tag, buf, ctx), + } + } + + fn encoded_len(&self) -> usize { + 0 + } + + fn clear(&mut self) {} +} + +/// The error whole-request decoding gives for `body`, found by decoding it in wire +/// order one record at a time (`read_request` reads each level whole before its +/// children, so where a body is broken in more than one place it can meet another +/// break first). `None` when the body decodes. +pub fn first_error( + body: Bytes, + names: &'static Names, + max_record: usize, +) -> Option> { + let oversized = AtomicBool::new(false); + let mut walk = WireOrder:: { + names, + depth: 0, + max_record, + oversized: &oversized, + leaf: PhantomData, + }; + walk.merge(body).err().map(|error| { + if oversized.load(Ordering::Relaxed) { + StreamError::RecordTooLarge { + leaf: L::LEAF, + limit: max_record, + } + } else { + StreamError::Decode(error) + } + }) +} diff --git a/src/otel/traces.rs b/src/otel/traces.rs index 74ea63b55..af16bd45f 100644 --- a/src/otel/traces.rs +++ b/src/otel/traces.rs @@ -132,7 +132,7 @@ impl SpanParents<'_> { /// Hands the rows of one span to `sink`: one per event, then one per link, each with /// the span's fields merged over it, or the span's own row when it has neither. Each /// event or link row is built only once the one before it was handed over. -pub fn span_rows( +pub fn span_rows( span: &Span, parents: &SpanParents<'_>, sink: &mut S, @@ -161,7 +161,7 @@ pub fn span_rows( } /// Hands the rows of every span of `resource_spans` to `sink`, one at a time -pub fn flatten_traces_into( +pub fn flatten_traces_into( resource_spans: &[ResourceSpans], sink: &mut S, ) -> Result<(), S::Error> { From f686bfb7912e477cdd2cf4cb5b96e817827af1d3 Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Tue, 24 Nov 2026 00:10:43 -0600 Subject: [PATCH 12/31] fix(otel): refuse a body that is not a protobuf request before reading the configuration The protobuf path read P_MAX_EVENT_PAYLOAD_SIZE and the exemplar option before decoding, so a garbage body no longer failed before the global configuration was touched (test_process_otel_content_protobuf_variants_reach_protobuf_decoding then exited the unfiltered test run). The request level is now checked first, with prost's error, and the options are read after. Imports that only the test-only whole-request decoder uses are cfg(test). Co-Authored-By: Claude Opus 5.5 --- src/handlers/http/modal/utils/ingest_utils.rs | 30 ++++++++++------- .../utils/ingest_utils/otel_protobuf_props.rs | 4 +-- src/otel/protobuf_stream.rs | 33 +++++++++++++++++++ 3 files changed, 54 insertions(+), 13 deletions(-) diff --git a/src/handlers/http/modal/utils/ingest_utils.rs b/src/handlers/http/modal/utils/ingest_utils.rs index be4af0565..744940306 100644 --- a/src/handlers/http/modal/utils/ingest_utils.rs +++ b/src/handlers/http/modal/utils/ingest_utils.rs @@ -20,6 +20,7 @@ use actix_web::http::header::{CONTENT_TYPE, USER_AGENT}; use actix_web::mime::Mime; use actix_web::{HttpRequest, HttpResponse, web}; use chrono::Utc; +#[cfg(test)] use opentelemetry_proto::tonic::collector::{ logs::v1::ExportLogsServiceRequest, metrics::v1::ExportMetricsServiceRequest, trace::v1::ExportTraceServiceRequest, @@ -29,6 +30,7 @@ use opentelemetry_proto::tonic::{ metrics::v1::{MetricsData, ResourceMetrics}, trace::v1::{ResourceSpans, TracesData}, }; +#[cfg(test)] use prost::Message as _; use rayon::prelude::*; use serde_json::Value; @@ -62,7 +64,10 @@ use crate::{ logs::flatten_logs_into, metrics::flatten_metrics_into, otel_utils::deserialize_otel_json, - protobuf_stream::{Signal, StreamError, flatten_request, max_record_bytes, size_request}, + protobuf_stream::{ + Signal, StreamError, check_request_level, flatten_request, max_record_bytes, + size_request, + }, sink::{CHUNK_LIMITS, Chunker, RowSink, Staged}, traces::flatten_traces_into, }, @@ -304,17 +309,15 @@ fn handle_otel_ingestion( error!("Ingestion failed for stream {stream_name}: {e}"); }) } - Some(OtelContentType::Protobuf) => flatten_and_push_otel_protobuf( - body, - &target, - ProtobufOptions { + Some(OtelContentType::Protobuf) => { + flatten_and_push_otel_protobuf(body, &target, || ProtobufOptions { max_payload: max_event_payload_size(), flatten_exemplars: PARSEABLE.options.otel_flatten_exemplars, - }, - ) - .inspect_err(|e| { - error!("Ingestion failed for stream {stream_name}: {e}"); - }), + }) + .inspect_err(|e| { + error!("Ingestion failed for stream {stream_name}: {e}"); + }) + } None => { error!( "Ingestion failed for stream {stream_name}: Unsupported Content-Type: {content_type}. Expected application/json or application/x-protobuf" @@ -596,7 +599,7 @@ struct ProtobufOptions { fn flatten_and_push_otel_protobuf( body: web::Bytes, target: &OtelTarget<'_>, - options: ProtobufOptions, + options: impl FnOnce() -> ProtobufOptions, ) -> Result { let signal = match target.log_source { LogSource::OtelLogs => Signal::Logs, @@ -609,6 +612,11 @@ fn flatten_and_push_otel_protobuf( )); } }; + // A body that is not a request at all is refused before the configuration is read + check_request_level(body.clone(), signal).map_err(|e| { + from_stream_error(target, e.map_consumer::(|never| match never {})) + })?; + let options = options(); let max_record = max_record_bytes(options.max_payload); let size = size_request(body.clone(), signal, max_record, options.flatten_exemplars).map_err(|e| { diff --git a/src/handlers/http/modal/utils/ingest_utils/otel_protobuf_props.rs b/src/handlers/http/modal/utils/ingest_utils/otel_protobuf_props.rs index 057de0284..efdfb6532 100644 --- a/src/handlers/http/modal/utils/ingest_utils/otel_protobuf_props.rs +++ b/src/handlers/http/modal/utils/ingest_utils/otel_protobuf_props.rs @@ -1664,7 +1664,7 @@ fn decode_is_total( telemetry_type, tenant_id: &None, }, - PROTOBUF_OPTIONS, + || PROTOBUF_OPTIONS, ) .expect_err("a body that does not decode is refused"); prop_assert!(matches!(refused, PostError::Invalid(_)), "{refused:?}"); @@ -2541,7 +2541,7 @@ fn run_scenario(seed: u64) -> Result)> { telemetry_type: request.telemetry_type(), tenant_id: &None, }, - PROTOBUF_OPTIONS, + || PROTOBUF_OPTIONS, ); if !matches!(&refused, Err(PostError::Invalid(e)) if e.to_string().ends_with(error.as_str())) { diff --git a/src/otel/protobuf_stream.rs b/src/otel/protobuf_stream.rs index cb4434a2b..fe62d7ec7 100644 --- a/src/otel/protobuf_stream.rs +++ b/src/otel/protobuf_stream.rs @@ -379,6 +379,29 @@ pub fn read_request( Ok(()) } +/// Reads only the request level of `body`: the framing of its resource levels and +/// its unknown fields. Needs no limit, so a body that is not a request of the signal +/// at all can be refused before anything else is looked at. On an error, reports +/// the one whole-request decoding gives (`first_error`, here without a cap on the +/// records it decodes on the way, one at a time). +pub fn check_request_level(body: Bytes, signal: Signal) -> Result<(), StreamError> { + let names = signal.names(); + let mut request = RequestLevel { + names, + body_len: body.len(), + children: Vec::new(), + }; + match request.merge(body.clone()) { + Ok(()) => Ok(()), + Err(error) => Err(match signal { + Signal::Logs => first_error::(body, names, usize::MAX), + Signal::Traces => first_error::(body, names, usize::MAX), + Signal::Metrics => first_error::(body, names, usize::MAX), + } + .unwrap_or(StreamError::Decode(error))), + } +} + /// The signal of a protobuf body #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Signal { @@ -387,6 +410,16 @@ pub enum Signal { Traces, } +impl Signal { + fn names(self) -> &'static Names { + match self { + Self::Logs => &LOGS, + Self::Metrics => &METRICS, + Self::Traces => &TRACES, + } + } +} + /// Rows, row bytes, records and data points of the request `body`, read one record /// at a time (the sizing pass of the expansion cap, see `expansion`) pub fn size_request( From 47b78aaa3301fbeaaef06b245d1542d6a91e6c52 Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Tue, 24 Nov 2026 00:56:48 -0600 Subject: [PATCH 13/31] feat(otel): read an OTLP protobuf request in one pass, capping its rows as they are staged The sizing pass is gone, for both encodings. It decoded every protobuf record once to total the request's rows and refuse it whole above the expansion cap, then the staging pass decoded every record again (+3-6 % instructions per realistic request; one span of 2 million empty events was held twice). - Expansion cap: a running total of the estimated row bytes (`row_bytes`) of the chunks handed to staging; the chunk that would pass 1024x the payload limit is refused like any other client error, so after staging began it is a partial success, the same in both encodings. `src/otel/expansion.rs` is removed; the factor lives with the chunker. - Protobuf: `outline` walks the request, resource and scope levels without decoding a record (a body broken there is still refused with prost's exact text before anything is staged, and before the configuration is read for a body with no record), then every leaf record is decoded once. A record that does not decode or is over the decoded-size cap, met after chunks were staged, is a partial success. - Rejected counts stay exact without costing the success path: log records and spans are counted by the outline; data points are read from the wire only after a failure (`metric_points`, following prost's oneof merging), an undecodable metric counted up to its break. - The decoded-size scan runs only on records long enough to reach the cap: at most 128 (log records), 208 (spans) or 416 (metrics) estimated bytes per wire byte beyond the record's struct, twice the largest repeated element, with the argument in `bytes_per_wire_byte` and crafted and random checks. - Differential properties follow the new semantics: decode whole and stream alike, or stream the rows of the records before the first that prost can not decode (checked against a shallow decoding of the levels above the records), or refuse with nothing staged when those levels are broken. Co-Authored-By: Claude Opus 5.5 --- src/handlers/http/modal/utils/ingest_utils.rs | 336 +++-- .../utils/ingest_utils/otel_protobuf_props.rs | 1258 +++++++++++++++-- src/otel.rs | 8 +- src/otel/decoded_size.rs | 323 ++++- src/otel/expansion.rs | 611 -------- src/otel/logs.rs | 5 +- src/otel/memory_tests.rs | 16 +- src/otel/metrics.rs | 8 +- src/otel/protobuf_stream.rs | 641 +++++---- src/otel/realistic_tests.rs | 250 ++-- src/otel/sink.rs | 43 +- src/otel/traces.rs | 5 +- 12 files changed, 2208 insertions(+), 1296 deletions(-) delete mode 100644 src/otel/expansion.rs diff --git a/src/handlers/http/modal/utils/ingest_utils.rs b/src/handlers/http/modal/utils/ingest_utils.rs index 744940306..147070a1d 100644 --- a/src/handlers/http/modal/utils/ingest_utils.rs +++ b/src/handlers/http/modal/utils/ingest_utils.rs @@ -58,17 +58,17 @@ use crate::{ increment_traces_collected_by_date, }, otel::{ - expansion::{ - EXPANSION_FACTOR, RequestSize, logs_size, max_expanded_bytes, metrics_size, traces_size, - }, logs::flatten_logs_into, metrics::flatten_metrics_into, otel_utils::deserialize_otel_json, protobuf_stream::{ - Signal, StreamError, check_request_level, flatten_request, max_record_bytes, - size_request, + Outline, Signal, StreamError, count_points, flatten_request, max_record_bytes, outline, + refusal, + }, + sink::{ + CHUNK_LIMITS, ChunkLimits, Chunker, EXPANSION_FACTOR, RowSink, Staged, + max_expanded_bytes, }, - sink::{CHUNK_LIMITS, Chunker, RowSink, Staged}, traces::flatten_traces_into, }, parseable::{DEFAULT_TENANT, PARSEABLE, Stream}, @@ -356,12 +356,37 @@ enum OtelResources<'a> { } impl OtelResources<'_> { - /// Rows, row bytes and records of the request, without building a row - fn size(&self, flatten_exemplars: bool) -> RequestSize { + /// What a partial success counts as rejected, for the whole request: log + /// records, data points or spans + fn total(&self) -> u64 { + let count = |n: usize| n as u64; match self { - Self::Logs(resources) => logs_size(resources), - Self::Metrics(resources) => metrics_size(resources, flatten_exemplars), - Self::Traces(resources) => traces_size(resources), + Self::Logs(resources) => resources + .iter() + .flat_map(|r| &r.scope_logs) + .map(|s| count(s.log_records.len())) + .sum(), + Self::Metrics(resources) => resources + .iter() + .flat_map(|r| &r.scope_metrics) + .flat_map(|s| &s.metrics) + .map(|metric| { + use opentelemetry_proto::tonic::metrics::v1::metric::Data; + count(match &metric.data { + Some(Data::Gauge(m)) => m.data_points.len(), + Some(Data::Sum(m)) => m.data_points.len(), + Some(Data::Histogram(m)) => m.data_points.len(), + Some(Data::ExponentialHistogram(m)) => m.data_points.len(), + Some(Data::Summary(m)) => m.data_points.len(), + None => 0, + }) + }) + .sum(), + Self::Traces(resources) => resources + .iter() + .flat_map(|r| &r.scope_spans) + .map(|s| count(s.spans.len())) + .sum(), } } @@ -388,49 +413,115 @@ impl OtelResources<'_> { } } -/// Refuses a request whose rows would hold more than `max_expanded_bytes` of the -/// payload limit, before anything is staged -fn check_expansion(size: &RequestSize, max_payload: usize) -> Result<(), PostError> { - let max = max_expanded_bytes(max_payload); - if size.bytes > max { - return Err(PostError::Invalid(anyhow::anyhow!( - "The request would expand to {} rows holding about {} bytes, more than the {max} bytes allowed ({EXPANSION_FACTOR} times P_MAX_EVENT_PAYLOAD_SIZE). Split the batch into smaller requests, or send fewer resource, scope and span attributes per record", - size.rows, - size.bytes, - ))); - } - Ok(()) +/// The refusal of a request whose rows hold more than `max` estimated bytes in all +fn expansion_error(max: u64) -> PostError { + PostError::Invalid(anyhow::anyhow!( + "The rows of the request take more than the {max} bytes allowed ({EXPANSION_FACTOR} times P_MAX_EVENT_PAYLOAD_SIZE). Split the batch into smaller requests, or send fewer resource, scope and span attributes per record" + )) +} + +/// Limits of staging one OTEL request +#[derive(Debug, Clone, Copy)] +struct StageLimits { + chunk: ChunkLimits, + /// Estimated row bytes the request may stage in all, see `max_expanded_bytes` + max_expanded: u64, + flatten: FlattenLimits, +} + +/// Flattens one OTEL request and hands its rows to `stage` in chunks (see +/// `Chunker`), so that they are never all held at once. The rows passed on are +/// counted against `limits.max_expanded` as they go: the chunk that would pass +/// it is refused with `expansion_error`, like any other chunk `stage` refuses. +/// Stops at the first error. Needs no server state. +fn stage_otel_rows( + limits: StageLimits, + flatten: impl FnOnce( + &mut FlattenBudget, + &mut dyn RowSink, + ) -> Result<(), PostError>, + mut stage: impl FnMut(Vec) -> Result<(), PostError>, +) -> (Result<(), PostError>, Staged) { + // The JSON log bodies of every record of the request share one budget + let mut budget = FlattenBudget::new(limits.flatten); + let mut expanded = 0u64; + let mut chunker = Chunker::new(limits.chunk, |rows: Vec, bytes: usize| { + expanded = expanded.saturating_add(bytes as u64); + if expanded > limits.max_expanded { + return Err(expansion_error(limits.max_expanded)); + } + stage(rows) + }); + let result = flatten(&mut budget, &mut chunker).and_then(|()| chunker.finish()); + let staged = chunker.staged(); + (result, staged) } -/// Stages the rows of one decoded OTEL request in chunks (see `Chunker`), so -/// that its rows are never all held at once. +/// The answer to an OTEL request that `stage_otel_rows` staged as `staged`. /// /// Before any chunk is staged, errors are returned as they are. Once at least -/// one chunk is staged, the request stops at the first failing chunk: -/// - a client error (status 4xx, such as a schema conflict, the field count -/// limit or a flatten limit) becomes a partial success that reports every -/// record not staged in full as rejected, answered with status 200 as -/// OTLP/HTTP requires; +/// one chunk is staged, the request stopped at the first failing chunk: +/// - a client error (status 4xx: a schema conflict, the field count limit, a +/// flatten limit, the expansion cap, a protobuf record that does not decode +/// or is too large) becomes a partial success that reports every record not +/// staged in full as rejected, answered with status 200 as OTLP/HTTP requires. +/// `total` gives the rejected unit for the whole request (log records, data +/// points or spans), and is only asked for here; /// - a server error keeps its 5xx status. The exporter then retries the whole /// request, so the rows of the chunks already staged are staged twice. +fn otel_outcome( + signal: Signal, + stream_name: &str, + result: Result<(), PostError>, + staged: &Staged, + total: impl FnOnce() -> u64, +) -> Result { + match result { + Ok(()) => Ok(OtelIngested::Full), + Err(error) + if staged.chunks > 0 + && actix_web::ResponseError::status_code(&error).is_client_error() => + { + let staged_units = match signal { + Signal::Metrics => staged.points, + Signal::Logs | Signal::Traces => staged.records, + }; + let rejected = total().saturating_sub(staged_units) as i64; + warn!( + "Ingestion into stream {stream_name} stopped after {} rows: {error}. {rejected} records rejected", + staged.rows + ); + Ok(OtelIngested::Partial { + rejected, + message: error.to_string(), + }) + } + Err(error) => Err(error), + } +} + +/// Stages the rows of one OTEL request in chunks into its stream, see +/// `stage_otel_rows` and `otel_outcome` fn ingest_otel_rows( signal: Signal, - size: RequestSize, target: &OtelTarget<'_>, flatten: impl FnOnce( &mut FlattenBudget, &mut dyn RowSink, ) -> Result<(), PostError>, + total: impl FnOnce() -> u64, ) -> Result { let tenant_str = target.tenant_id.as_deref().unwrap_or(DEFAULT_TENANT); // Verify the dataset fields count verify_dataset_fields_count(target.stream_name, target.tenant_id)?; - check_expansion(&size, max_event_payload_size())?; - // The JSON log bodies of every record of the request share one budget - let mut budget = FlattenBudget::new(FlattenLimits::from_config()); + let limits = StageLimits { + chunk: CHUNK_LIMITS, + max_expanded: max_expanded_bytes(max_event_payload_size()), + flatten: FlattenLimits::from_config(), + }; let mut staging = Staging::new(target.stream_name, target.tenant_id)?; - let mut chunker = Chunker::new(CHUNK_LIMITS, |rows: Vec| { + let (result, staged) = stage_otel_rows(limits, flatten, |rows| { staging.push( Value::Array(rows), target.log_source, @@ -439,31 +530,10 @@ fn ingest_otel_rows( target.telemetry_type, ) }); - let result = flatten(&mut budget, &mut chunker).and_then(|()| chunker.finish()); - let staged = chunker.staged(); - drop(chunker); - if result.is_ok() || staged.chunks > 0 { count_collected(signal, staged.records, tenant_str); } - match result { - Ok(()) => Ok(OtelIngested::Full), - Err(error) - if staged.chunks > 0 - && actix_web::ResponseError::status_code(&error).is_client_error() => - { - let rejected = rejected(signal, &size, &staged); - warn!( - "Ingestion into stream {} stopped after {} rows: {error}. {rejected} records rejected", - target.stream_name, staged.rows - ); - Ok(OtelIngested::Partial { - rejected, - message: error.to_string(), - }) - } - Err(error) => Err(error), - } + otel_outcome(signal, target.stream_name, result, &staged, total) } /// `ingest_otel_rows` for a request decoded whole (OTLP JSON) @@ -472,20 +542,12 @@ fn ingest_otel_resources( target: &OtelTarget<'_>, ) -> Result { let flatten_exemplars = PARSEABLE.options.otel_flatten_exemplars; - let size = resources.size(flatten_exemplars); - ingest_otel_rows(resources.signal(), size, target, |budget, sink| { - resources.flatten_into(budget, flatten_exemplars, sink) - }) -} - -/// The records a partial success reports as rejected: log records, data points or -/// spans that were not staged in full -fn rejected(signal: Signal, size: &RequestSize, staged: &Staged) -> i64 { - let (total, staged) = match signal { - Signal::Metrics => (size.points, staged.points), - Signal::Logs | Signal::Traces => (size.records, staged.records), - }; - total.saturating_sub(staged) as i64 + ingest_otel_rows( + resources.signal(), + target, + |budget, sink| resources.flatten_into(budget, flatten_exemplars, sink), + || resources.total(), + ) } /// Counts for `tenant_id` the leaf records (log records, spans, metrics) whose rows @@ -591,16 +653,34 @@ struct ProtobufOptions { } /// Protobuf counterpart of `ingest_otel_json`. The body is read one leaf record -/// at a time (`protobuf_stream`), twice: a sizing pass that refuses a body that -/// does not decode or would expand too far before anything is staged, then the -/// pass whose rows are staged. Each record is decoded in each pass and dropped, -/// so the decoded request is never held whole. The body size is capped by the -/// `PayloadConfig` of the OTEL routes. +/// at a time (`protobuf_stream`): `outline` first walks the levels above the +/// records, so a body broken there is refused before anything is staged (and +/// before the configuration is read), then every record is decoded once, its rows +/// handed over in chunks, and dropped. So the decoded request is never held whole. +/// A record that does not decode, or would be too large once decoded, is a client +/// error met while staging: a partial success once chunks were staged. The body +/// size is capped by the `PayloadConfig` of the OTEL routes. fn flatten_and_push_otel_protobuf( body: web::Bytes, target: &OtelTarget<'_>, options: impl FnOnce() -> ProtobufOptions, ) -> Result { + let (signal, outline, options) = outline_otel_protobuf(&body, target, options)?; + ingest_otel_rows( + signal, + target, + |budget, sink| flatten_otel_protobuf(&body, signal, &options, target, budget, sink), + || protobuf_total(&body, signal, &outline), + ) +} + +/// The signal and outline of a protobuf body, and the options to read it with, +/// read only once the body is known to be a request (see `refusal`) +fn outline_otel_protobuf( + body: &web::Bytes, + target: &OtelTarget<'_>, + options: impl FnOnce() -> ProtobufOptions, +) -> Result<(Signal, Outline, ProtobufOptions), PostError> { let signal = match target.log_source { LogSource::OtelLogs => Signal::Logs, LogSource::OtelMetrics => Signal::Metrics, @@ -612,27 +692,89 @@ fn flatten_and_push_otel_protobuf( )); } }; - // A body that is not a request at all is refused before the configuration is read - check_request_level(body.clone(), signal).map_err(|e| { - from_stream_error(target, e.map_consumer::(|never| match never {})) - })?; - let options = options(); - let max_record = max_record_bytes(options.max_payload); - let size = - size_request(body.clone(), signal, max_record, options.flatten_exemplars).map_err(|e| { - from_stream_error(target, e.map_consumer::(|never| match never {})) - })?; - ingest_otel_rows(signal, size, target, |budget, sink| { - flatten_request( - body, - signal, - max_record, - budget, - options.flatten_exemplars, - sink, - ) - .map_err(|e| from_stream_error(target, e)) - }) + match outline(body, signal) { + Ok(outline) => Ok((signal, outline, options())), + Err(error) => { + let error = refusal(body, signal, error, || { + max_record_bytes(options().max_payload) + }); + Err(from_stream_error(target, error.widen())) + } + } +} + +/// Hands the rows of a protobuf body that passed `outline` to `sink` +fn flatten_otel_protobuf( + body: &web::Bytes, + signal: Signal, + options: &ProtobufOptions, + target: &OtelTarget<'_>, + budget: &mut FlattenBudget, + sink: &mut dyn RowSink, +) -> Result<(), PostError> { + flatten_request( + body, + signal, + max_record_bytes(options.max_payload), + budget, + options.flatten_exemplars, + sink, + ) + .map_err(|e| from_stream_error(target, e)) +} + +/// `flatten_and_push_otel_protobuf` without the server: the rows are handed to +/// `stage` under `limits` instead of being staged into a stream. For tests, +/// which must not touch `PARSEABLE`. +#[cfg(test)] +fn stage_otel_protobuf( + body: web::Bytes, + target: &OtelTarget<'_>, + options: ProtobufOptions, + limits: StageLimits, + stage: impl FnMut(Vec) -> Result<(), PostError>, +) -> (Result, Staged) { + let (signal, outline, options) = match outline_otel_protobuf(&body, target, || options) { + Ok(read) => read, + Err(error) => return (Err(error), Staged::default()), + }; + let (result, staged) = stage_otel_rows( + limits, + |budget, sink| flatten_otel_protobuf(&body, signal, &options, target, budget, sink), + stage, + ); + let outcome = otel_outcome(signal, target.stream_name, result, &staged, || { + protobuf_total(&body, signal, &outline) + }); + (outcome, staged) +} + +/// `ingest_otel_resources` without the server, see `stage_otel_protobuf` +#[cfg(test)] +fn stage_otel_resources( + resources: OtelResources<'_>, + flatten_exemplars: bool, + limits: StageLimits, + stage: impl FnMut(Vec) -> Result<(), PostError>, +) -> (Result, Staged) { + let (result, staged) = stage_otel_rows( + limits, + |budget, sink| resources.flatten_into(budget, flatten_exemplars, sink), + stage, + ); + let outcome = otel_outcome(resources.signal(), "test", result, &staged, || { + resources.total() + }); + (outcome, staged) +} + +/// What a partial success of a protobuf request counts as rejected, for the whole +/// request: its records from the outline, or its data points read from the wire +fn protobuf_total(body: &web::Bytes, signal: Signal, outline: &Outline) -> u64 { + match signal { + Signal::Metrics => count_points(body), + Signal::Logs | Signal::Traces => outline.records, + } } fn stream_error(target: &OtelTarget<'_>, error: String) -> PostError { diff --git a/src/handlers/http/modal/utils/ingest_utils/otel_protobuf_props.rs b/src/handlers/http/modal/utils/ingest_utils/otel_protobuf_props.rs index efdfb6532..0f68bc307 100644 --- a/src/handlers/http/modal/utils/ingest_utils/otel_protobuf_props.rs +++ b/src/handlers/http/modal/utils/ingest_utils/otel_protobuf_props.rs @@ -84,6 +84,15 @@ const PROTOBUF_OPTIONS: ProtobufOptions = ProtobufOptions { flatten_exemplars: false, }; +/// The staging limits of the server defaults +fn test_limits() -> StageLimits { + StageLimits { + chunk: CHUNK_LIMITS, + max_expanded: max_expanded_bytes(PROTOBUF_OPTIONS.max_payload), + flatten: FlattenLimits::DEFAULT, + } +} + // --------------------------------------------------------------------------- // Seeds and runners // --------------------------------------------------------------------------- @@ -1474,11 +1483,42 @@ impl Req { } } - fn resource_count(&self) -> usize { + /// Leaf records: log records, spans or metrics + fn record_count(&self) -> u64 { + let n: usize = match self { + Self::Logs(data) => data + .resource_logs + .iter() + .flat_map(|r| &r.scope_logs) + .map(|s| s.log_records.len()) + .sum(), + Self::Metrics(data) => data + .resource_metrics + .iter() + .flat_map(|r| &r.scope_metrics) + .map(|s| s.metrics.len()) + .sum(), + Self::Traces(data) => data + .resource_spans + .iter() + .flat_map(|r| &r.scope_spans) + .map(|s| s.spans.len()) + .sum(), + }; + n as u64 + } + + /// Metric data points + fn point_count(&self) -> u64 { match self { - Self::Logs(data) => data.resource_logs.len(), - Self::Metrics(data) => data.resource_metrics.len(), - Self::Traces(data) => data.resource_spans.len(), + Self::Metrics(data) => data + .resource_metrics + .iter() + .flat_map(|r| &r.scope_metrics) + .flat_map(|s| &s.metrics) + .map(|m| metric_points(m) as u64) + .sum(), + Self::Logs(_) | Self::Traces(_) => 0, } } } @@ -1500,9 +1540,10 @@ fn decode_as(request: &Req, protobuf: bool) -> Req { /// Chunks of at most `rows` rows (and a byte limit small enough to cut chunks of a /// row or two) give the same rows in the same order as one chunk, for both -/// encodings, and count every record and data point as staged. The sizing pass -/// counts the same records and data points, and the rows up to one `target_info` -/// row per resource. +/// encodings, and count every record and data point as staged: as many as the +/// request has, which is what a partial success counts its rejected records from +/// (`OtelResources::total`, and for protobuf the outline and the wire count of +/// data points). fn chunking_keeps_rows( mut request: Req, rows: usize, @@ -1524,7 +1565,7 @@ fn chunking_keeps_rows( ) .unwrap(); let mut chunks: Vec> = Vec::new(); - let mut chunker = Chunker::new(limits, |rows| { + let mut chunker = Chunker::new(limits, |rows, _| { chunks.push(rows); Ok::<_, JsonFlattenError>(()) }); @@ -1552,17 +1593,26 @@ fn chunking_keeps_rows( "chunked rows differ (protobuf: {})", protobuf ); - let size = resources.size(flatten_exemplars); prop_assert_eq!(staged.rows as usize, whole.len()); - prop_assert_eq!(staged.records, size.records); - prop_assert_eq!(staged.points, size.points); - prop_assert!( - size.rows as usize >= whole.len() - && size.rows as usize <= whole.len() + decoded.resource_count(), - "sizing pass counted {} rows for {}", - size.rows, - whole.len() - ); + prop_assert_eq!(staged.records, decoded.record_count()); + prop_assert_eq!(staged.points, decoded.point_count()); + let units = match decoded { + Req::Metrics(_) => staged.points, + Req::Logs(_) | Req::Traces(_) => staged.records, + }; + prop_assert_eq!(resources.total(), units); + if protobuf { + let body = web::Bytes::from(request.encode_pb()); + let signal = streamed::signal(&decoded); + let outline = crate::otel::protobuf_stream::outline(&body, signal).unwrap(); + prop_assert_eq!(outline.records, staged.records); + if signal == crate::otel::protobuf_stream::Signal::Metrics { + prop_assert_eq!( + crate::otel::protobuf_stream::count_points(&body), + staged.points + ); + } + } } Ok(()) } @@ -1654,24 +1704,37 @@ fn decode_is_total( } } Err(error) => { - // Returns before the dataset field check, the first use of `PARSEABLE` - let refused = flatten_and_push_otel_protobuf( - web::Bytes::copy_from_slice(body), - &OtelTarget { - stream_name: "otel_pb_props", - log_source: source, - p_custom_fields: &HashMap::new(), - telemetry_type, - tenant_id: &None, - }, - || PROTOBUF_OPTIONS, - ) - .expect_err("a body that does not decode is refused"); + let target = OtelTarget { + stream_name: "otel_pb_props", + log_source: source, + p_custom_fields: &HashMap::new(), + telemetry_type, + tenant_id: &None, + }; + let expected = + format!("Invalid Request: Ingestion failed for stream otel_pb_props: {error}"); + let body = web::Bytes::copy_from_slice(body); + let signal = match source { + LogSource::OtelLogs => crate::otel::protobuf_stream::Signal::Logs, + LogSource::OtelMetrics => crate::otel::protobuf_stream::Signal::Metrics, + _ => crate::otel::protobuf_stream::Signal::Traces, + }; + if crate::otel::protobuf_stream::outline(&body, signal).is_err() { + // Broken above its records: refused before the dataset field check, + // the first use of `PARSEABLE` + let refused = + flatten_and_push_otel_protobuf(body.clone(), &target, || PROTOBUF_OPTIONS) + .expect_err("a body that does not decode is refused"); + prop_assert!(matches!(refused, PostError::Invalid(_)), "{refused:?}"); + prop_assert_eq!(refused.to_string(), expected.clone()); + } + // A broken record is met while staging, before the first chunk is full + let (refused, staged) = + stage_otel_protobuf(body, &target, PROTOBUF_OPTIONS, test_limits(), |_| Ok(())); + let refused = refused.expect_err("a body that does not decode is refused"); prop_assert!(matches!(refused, PostError::Invalid(_)), "{refused:?}"); - prop_assert_eq!( - refused.to_string(), - format!("Invalid Request: Ingestion failed for stream otel_pb_props: {error}") - ); + prop_assert_eq!(refused.to_string(), expected); + prop_assert_eq!(staged.chunks, 0); } } Ok(()) @@ -2532,7 +2595,7 @@ fn run_scenario(seed: u64) -> Result)> { return fail(format!("undamaged body refused: {error}"), &mut trace); } if encoding == Encoding::Protobuf { - let refused = flatten_and_push_otel_protobuf( + let (refused, _) = stage_otel_protobuf( web::Bytes::copy_from_slice(&body), &OtelTarget { stream_name: "dst", @@ -2541,7 +2604,9 @@ fn run_scenario(seed: u64) -> Result)> { telemetry_type: request.telemetry_type(), tenant_id: &None, }, - || PROTOBUF_OPTIONS, + PROTOBUF_OPTIONS, + test_limits(), + |_| Ok(()), ); if !matches!(&refused, Err(PostError::Invalid(e)) if e.to_string().ends_with(error.as_str())) { @@ -2708,15 +2773,49 @@ fn dst_otlp_mixed_encoding_seeds_differ() { mod streamed { use super::*; - use crate::otel::expansion::{logs_size, metrics_size, traces_size}; - use crate::otel::protobuf_stream::{Signal, StreamError, flatten_request, size_request}; + use crate::otel::decoded_size::{ + Leaf, bytes_per_wire_byte, leaf_decoded_size, leaf_struct_size, + metric_points as wire_points, + }; + use crate::otel::protobuf_stream::{ + Signal, StreamError, count_points, flatten_request, outline, refusal, + }; use prost::Message as ProstMessage; use prost::encoding::{WireType, encode_key, encode_varint}; - /// Wire edits applied while re-encoding a request field by field - struct Edits<'a>(&'a mut SplitMix64); + /// Damage to one leaf record of a body: byte `at` set to `byte`, or the record + /// cut at `at`, inside the record (its framing is rewritten to fit) + #[derive(Debug, Clone, Copy)] + struct RecordDamage { + index: u64, + at: u64, + byte: u8, + cut: bool, + } + + /// Wire edits applied while re-encoding a request field by field, and the + /// record damage to apply, with the count of records seen so far + struct Edits<'a>(&'a mut SplitMix64, Option, u64); impl Edits<'_> { + /// The encoding of the next leaf record, damaged if it is the one to damage + fn record(&mut self, mut encoded: Vec) -> Vec { + let index = self.2; + self.2 += 1; + if let Some(damage) = self.1 + && damage.index == index + && !encoded.is_empty() + { + let at = (damage.at % encoded.len() as u64) as usize; + if damage.cut { + encoded.truncate(at); + } else { + encoded[at] = damage.byte; + } + } + encoded + } + /// An unknown field (numbers 4-40 or a large one) of a random wire type fn unknown(&mut self, out: &mut Vec) { let tag = if self.0.percent(80) { @@ -2862,9 +2961,10 @@ mod streamed { ) } - /// The protobuf body of `request`, re-encoded field by field with `edits` - fn edited_body(request: &Req, rng: &mut SplitMix64) -> Vec { - let mut edits = Edits(rng); + /// The protobuf body of `request`, re-encoded field by field with edits drawn + /// from `rng`, with `damage` applied to one of its leaf records + fn edited_body(request: &Req, rng: &mut SplitMix64, damage: Option) -> Vec { + let mut edits = Edits(rng, damage, 0); let resources: Vec> = match request { Req::Logs(data) => data .resource_logs @@ -2877,7 +2977,7 @@ mod streamed { let records = s .log_records .iter() - .map(ProstMessage::encode_to_vec) + .map(|record| edits.record(record.encode_to_vec())) .collect(); edits.parent(s.scope.as_ref(), split_scope, records, &s.schema_url) }) @@ -2893,7 +2993,11 @@ mod streamed { .scope_spans .iter() .map(|s| { - let spans = s.spans.iter().map(ProstMessage::encode_to_vec).collect(); + let spans = s + .spans + .iter() + .map(|span| edits.record(span.encode_to_vec())) + .collect(); edits.parent(s.scope.as_ref(), split_scope, spans, &s.schema_url) }) .collect(); @@ -2908,8 +3012,11 @@ mod streamed { .scope_metrics .iter() .map(|s| { - let metrics = - s.metrics.iter().map(ProstMessage::encode_to_vec).collect(); + let metrics = s + .metrics + .iter() + .map(|metric| edits.record(metric.encode_to_vec())) + .collect(); edits.parent(s.scope.as_ref(), split_scope, metrics, &s.schema_url) }) .collect(); @@ -2921,7 +3028,7 @@ mod streamed { edits.level(fields) } - fn signal(request: &Req) -> Signal { + pub(super) fn signal(request: &Req) -> Signal { match request { Req::Logs(_) => Signal::Logs, Req::Metrics(_) => Signal::Metrics, @@ -2929,91 +3036,477 @@ mod streamed { } } - /// Rows and size of `body` decoded whole, or prost's error text - fn whole( - request: &Req, - body: &[u8], - flatten_exemplars: bool, - ) -> Result<(Vec, RequestSize), String> { - let decoded = - OtelProtobufRequest::decode(body, &request.source()).map_err(|e| e.to_string())?; - let decoded = Req::from_decoded(decoded); - let resources = decoded.resources(); + fn leaf(request: &Req) -> Leaf { + match request { + Req::Logs(_) => Leaf::LogRecord, + Req::Metrics(_) => Leaf::Metric, + Req::Traces(_) => Leaf::Span, + } + } + + /// The rows the flatteners build for `request`, or the flatten error text + fn rows_of(request: &Req, flatten_exemplars: bool) -> Result, String> { let mut rows = Vec::new(); - resources + request + .resources() .flatten_into( &mut FlattenBudget::new(FlattenLimits::DEFAULT), flatten_exemplars, &mut rows, ) .map_err(|e| format!("flatten: {e}"))?; - let size = match &decoded { - Req::Logs(data) => logs_size(&data.resource_logs), - Req::Metrics(data) => metrics_size(&data.resource_metrics, flatten_exemplars), - Req::Traces(data) => traces_size(&data.resource_spans), - }; - Ok((serde_json::to_vec(&rows).unwrap(), size)) + Ok(rows) + } + + /// The rows of `request`, and whether some of them take the wall clock for an + /// unset timestamp (then only their number can be compared) + fn clocked_rows(request: &Req, flatten_exemplars: bool) -> Result<(Vec, bool), String> { + let clock = fill_unset_timestamps(&mut request.clone()); + Ok((rows_of(request, flatten_exemplars)?, clock)) } - /// Rows and size of `body` read one record at a time, or the error text - fn streamed( + /// Rows of `body` decoded whole, or prost's error text + fn whole( request: &Req, body: &[u8], flatten_exemplars: bool, - ) -> Result<(Vec, RequestSize), String> { - let text = |e: StreamError<_>| match e { + ) -> Result<(Vec, bool), String> { + let decoded = + OtelProtobufRequest::decode(body, &request.source()).map_err(|e| e.to_string())?; + clocked_rows(&Req::from_decoded(decoded), flatten_exemplars) + } + + /// Whether streamed rows are the expected ones: the same, or as many where the + /// wall clock filled a timestamp + fn same_rows(streamed: &[Value], expected: &[Value], clock: bool) -> bool { + if clock { + streamed.len() == expected.len() + } else { + serde_json::to_vec(streamed).unwrap() == serde_json::to_vec(expected).unwrap() + } + } + + /// What reading `body` one record at a time staged, in chunks of one row + #[derive(Debug)] + struct Streamed { + rows: Vec, + staged: Staged, + /// The error text, if it stopped + error: Option, + /// What a partial success counts its rejected records from: the records of + /// the outline, or the data points read from the wire + total: u64, + } + + fn text(e: StreamError) -> String { + match e { StreamError::Decode(e) => OtelProtobufError::Decode(e).to_string(), StreamError::RecordTooLarge { .. } => "record too large".to_string(), StreamError::Consumer(e) => format!("flatten: {e}"), + } + } + + fn streamed(request: &Req, body: &[u8], flatten_exemplars: bool) -> Streamed { + let body = web::Bytes::copy_from_slice(body); + let signal = signal(request); + let outlined = match outline(&body, signal) { + Ok(outlined) => outlined, + Err(error) => { + return Streamed { + rows: Vec::new(), + staged: Staged::default(), + error: Some(text(refusal(&body, signal, error, || usize::MAX).widen())), + total: 0, + }; + } }; - let size = size_request( - web::Bytes::copy_from_slice(body), - signal(request), - usize::MAX, - flatten_exemplars, - ) - .map_err(|e| { - text(match e { - StreamError::Decode(e) => StreamError::Decode(e), - StreamError::RecordTooLarge { leaf, limit } => { - StreamError::RecordTooLarge { leaf, limit } - } - StreamError::Consumer(never) => match never {}, - }) - })?; let mut rows: Vec = Vec::new(); - flatten_request( - web::Bytes::copy_from_slice(body), - signal(request), + let mut chunker = Chunker::new( + ChunkLimits { + rows: 1, + bytes: usize::MAX, + }, + |chunk, _| { + rows.extend(chunk); + Ok::<_, JsonFlattenError>(()) + }, + ); + let result = flatten_request( + &body, + signal, usize::MAX, &mut FlattenBudget::new(FlattenLimits::DEFAULT), flatten_exemplars, - &mut rows, + &mut chunker, ) - .map_err(text)?; - Ok((serde_json::to_vec(&rows).unwrap(), size)) + .and_then(|()| chunker.finish().map_err(StreamError::Consumer)); + let staged = chunker.staged(); + drop(chunker); + Streamed { + rows, + staged, + error: result.err().map(text), + total: match signal { + Signal::Metrics => count_points(&body), + Signal::Logs | Signal::Traces => outlined.records, + }, + } + } + + /// The levels of a request above its leaf records, with the records kept as + /// bytes: prost decodes a body as this exactly when its framing above the + /// records holds, and merges `resource`, `scope` and `schema_url` as it does + /// for the real messages + #[derive(Clone, PartialEq, prost::Message)] + struct ShallowRequest { + #[prost(message, repeated, tag = "1")] + resources: Vec, + } + + #[derive(Clone, PartialEq, prost::Message)] + struct ShallowResource { + #[prost(message, optional, tag = "1")] + resource: Option, + #[prost(message, repeated, tag = "2")] + scopes: Vec, + #[prost(string, tag = "3")] + schema_url: String, + } + + #[derive(Clone, PartialEq, prost::Message)] + struct ShallowScope { + #[prost(message, optional, tag = "1")] + scope: Option, + #[prost(bytes = "vec", repeated, tag = "2")] + records: Vec>, + #[prost(string, tag = "3")] + schema_url: String, + } + + type Scopes = Vec<(Option, String, Vec)>; + + /// A request rebuilt from its shallow decoding, with the records that prost + /// decodes on their own up to the first that it does not + struct Prefix { + resources: Vec<(Option, String, Scopes)>, + /// Position of the first record that does not decode, in body order + failed: Option, + records: u64, + /// Every record, decoded where it decodes + all: Vec>>, } - fn streamed_matches_whole( - mut request: Req, - seed: u64, + fn prefix(shallow: &ShallowRequest) -> Prefix { + let mut prefix = Prefix { + resources: vec![], + failed: None, + records: 0, + all: vec![], + }; + for resource in &shallow.resources { + if prefix.failed.is_none() { + prefix.resources.push(( + resource.resource.clone(), + resource.schema_url.clone(), + vec![], + )); + } + for scope in &resource.scopes { + if prefix.failed.is_none() { + let scopes = &mut prefix.resources.last_mut().unwrap().2; + scopes.push((scope.scope.clone(), scope.schema_url.clone(), vec![])); + } + for encoded in &scope.records { + let decoded = L::decode(encoded.as_slice()).map_err(|_| encoded.clone()); + if prefix.failed.is_none() { + match &decoded { + Ok(record) => { + let scopes = &mut prefix.resources.last_mut().unwrap().2; + scopes.last_mut().unwrap().2.push(record.clone()); + } + Err(_) => prefix.failed = Some(prefix.records), + } + } + prefix.all.push(decoded); + prefix.records += 1; + } + } + } + prefix + } + + /// What streaming must stage for a body + enum Expected { + /// The framing above the records is broken: nothing is staged + Outer, + Records { + /// The rows of the records before the first that does not decode (all + /// of them if each does), or the flatten error text + rows: Result<(Vec, bool), String>, + failed: Option, + records: u64, + /// Data points of the records before the first that does not decode + staged_points: u64, + /// Data points of every record, those that do not decode read from the wire + total_points: u64, + }, + } + + fn is_target_info(row: &Value) -> bool { + row.get("metric_name") == Some(&json!("target_info")) + && row.get("metric_description") == Some(&json!("Target metadata")) + } + + fn expected(request: &Req, body: &[u8], flatten_exemplars: bool) -> Expected { + let Ok(shallow) = ShallowRequest::decode(body) else { + return Expected::Outer; + }; + let (rows, failed, records, staged_points, total_points) = match request { + Req::Logs(_) => { + let p = prefix::(&shallow); + let request = Req::Logs(LogsData { + resource_logs: p + .resources + .into_iter() + .map(|(resource, schema_url, scopes)| ResourceLogs { + resource, + scope_logs: scopes + .into_iter() + .map(|(scope, schema_url, log_records)| ScopeLogs { + scope, + log_records, + schema_url, + }) + .collect(), + schema_url, + }) + .collect(), + }); + ( + clocked_rows(&request, flatten_exemplars), + p.failed, + p.records, + 0, + 0, + ) + } + Req::Traces(_) => { + let p = prefix::(&shallow); + let request = Req::Traces(TracesData { + resource_spans: p + .resources + .into_iter() + .map(|(resource, schema_url, scopes)| ResourceSpans { + resource, + scope_spans: scopes + .into_iter() + .map(|(scope, schema_url, spans)| ScopeSpans { + scope, + spans, + schema_url, + }) + .collect(), + schema_url, + }) + .collect(), + }); + ( + clocked_rows(&request, flatten_exemplars), + p.failed, + p.records, + 0, + 0, + ) + } + Req::Metrics(_) => { + let p = prefix::(&shallow); + let points = |record: &Result>| match record { + Ok(metric) => metric_points(metric) as u64, + Err(encoded) => wire_points(encoded), + }; + let failed_at = p.failed.unwrap_or(p.records) as usize; + let staged_points = p.all[..failed_at].iter().map(points).sum(); + let total_points = p.all.iter().map(points).sum(); + let resources: Vec = p + .resources + .into_iter() + .map(|(resource, schema_url, scopes)| ResourceMetrics { + resource, + scope_metrics: scopes + .into_iter() + .map(|(scope, schema_url, metrics)| ScopeMetrics { + scope, + metrics, + schema_url, + }) + .collect(), + schema_url, + }) + .collect(); + let clock = fill_unset_timestamps(&mut Req::Metrics(MetricsData { + resource_metrics: resources.clone(), + })); + let rows = if p.failed.is_some() { + // Streaming stops inside the last resource, before its `target_info` row + let (last, complete) = resources.split_last().unwrap(); + let complete = rows_of( + &Req::Metrics(MetricsData { + resource_metrics: complete.to_vec(), + }), + flatten_exemplars, + ); + let last = rows_of( + &Req::Metrics(MetricsData { + resource_metrics: vec![last.clone()], + }), + flatten_exemplars, + ); + complete.and_then(|mut rows| { + let mut last = last?; + if last.last().is_some_and(is_target_info) { + last.pop(); + } + rows.extend(last); + Ok(rows) + }) + } else { + rows_of( + &Req::Metrics(MetricsData { + resource_metrics: resources, + }), + flatten_exemplars, + ) + }; + ( + rows.map(|rows| (rows, clock)), + p.failed, + p.records, + staged_points, + total_points, + ) + } + }; + Expected::Records { + rows, + failed, + records, + staged_points, + total_points, + } + } + + /// Which of the semantics a body met + #[derive(Debug, Clone, Copy, PartialEq, Eq)] + enum Case { + /// Decodes whole: the same rows, every record staged + Decoded, + /// Broken above its records: refused with prost's error, nothing staged + Outer, + /// The first record does not decode: prost's error, nothing staged + FirstRecord, + /// A later record does not decode: prost's error, the rows of the records + /// before it staged, the rest counted as rejected + Partial, + /// Flattening refused a record first + Flatten, + } + + /// The differential property of streamed decoding, for one body: either + /// whole-request decoding and streaming both succeed with identical rows; or + /// streaming stages exactly the rows of the records before the first record + /// prost can not decode and counts the rest rejected; or the framing above the + /// records is broken and nothing is staged. Every failure has prost's text. + /// Also checks the bound on the decoded size of every record of the body. + fn check_body( + request: &Req, + body: &[u8], flatten_exemplars: bool, - cut: Option, - ) -> TestCaseResult { - fill_unset_timestamps(&mut request); - let mut rng = SplitMix64(seed); - let mut body = edited_body(&request, &mut rng); - if let Some(cut) = cut { - body.truncate((cut % (body.len() as u64 + 1)) as usize); + ) -> Result { + let whole = whole(request, body, flatten_exemplars); + let streamed = streamed(request, body, flatten_exemplars); + let leaf = leaf(request); + if let Ok(shallow) = ShallowRequest::decode(body) { + for encoded in shallow + .resources + .iter() + .flat_map(|r| &r.scopes) + .flat_map(|s| &s.records) + { + prop_assert!( + leaf_decoded_size(encoded, leaf) + <= leaf_struct_size(leaf) + bytes_per_wire_byte(leaf) * encoded.len(), + "a {leaf:?} of {} bytes is over the bound", + encoded.len() + ); + } + } + let units = |staged: &Staged| match request { + Req::Metrics(_) => staged.points, + Req::Logs(_) | Req::Traces(_) => staged.records, + }; + match (&whole, expected(request, body, flatten_exemplars)) { + (Ok((rows, clock)), _) => { + prop_assert_eq!(&streamed.error, &None); + prop_assert!( + same_rows(&streamed.rows, rows, *clock), + "whole and streamed rows differ ({} and {})", + rows.len(), + streamed.rows.len() + ); + prop_assert_eq!(streamed.total, units(&streamed.staged)); + Ok(Case::Decoded) + } + (Err(text), Expected::Outer) => { + prop_assert_eq!(streamed.error.as_ref(), Some(text)); + prop_assert!(streamed.rows.is_empty()); + prop_assert_eq!(streamed.staged, Staged::default()); + Ok(Case::Outer) + } + ( + Err(text), + Expected::Records { + rows, + failed, + records, + staged_points, + total_points, + }, + ) => { + let (rows, clock) = match rows { + Ok(rows) => rows, + Err(flatten) => { + prop_assert_eq!(streamed.error, Some(flatten)); + return Ok(Case::Flatten); + } + }; + prop_assert_eq!(streamed.error.as_ref(), Some(text)); + let Some(failed) = failed else { + return Err(TestCaseError::fail(format!( + "whole decoding failed ({text}) but every record decodes on its own" + ))); + }; + prop_assert!( + same_rows(&streamed.rows, &rows, clock), + "streamed did not stage the rows of the records before the broken one ({} of {})", + streamed.rows.len(), + rows.len() + ); + prop_assert_eq!(streamed.staged.records, failed); + let rejected = streamed.total - units(&streamed.staged); + match request { + Req::Metrics(_) => { + prop_assert_eq!(streamed.staged.points, staged_points); + prop_assert_eq!(rejected, total_points - staged_points); + } + Req::Logs(_) | Req::Traces(_) => prop_assert_eq!(rejected, records - failed), + } + Ok(if failed == 0 { + Case::FirstRecord + } else { + Case::Partial + }) + } } - let whole = whole(&request, &body, flatten_exemplars); - let streamed = streamed(&request, &body, flatten_exemplars); - prop_assert_eq!( - &whole, - &streamed, - "whole (left) and streamed (right) differ" - ); - Ok(()) } fn requests() -> BoxedStrategy { @@ -3025,71 +3518,139 @@ mod streamed { .boxed() } + /// Counts the cases a property met, by kind + #[derive(Default)] + struct Cases([AtomicUsize; 5]); + + impl Cases { + fn add(&self, case: Case) { + self.0[case as usize].fetch_add(1, Ordering::Relaxed); + } + + fn get(&self, case: Case) -> usize { + self.0[case as usize].load(Ordering::Relaxed) + } + + fn print(&self, name: &str) { + println!( + "{name}: decoded {} outer {} first_record {} partial {} flatten {}", + self.get(Case::Decoded), + self.get(Case::Outer), + self.get(Case::FirstRecord), + self.get(Case::Partial), + self.get(Case::Flatten) + ); + } + } + #[test] fn otel_pb_streamed_rows_match_whole_decoding() { check( "otel_pb_streamed_rows_match_whole_decoding", 192, (requests(), any::(), any::()), - |(request, seed, flatten_exemplars)| { - streamed_matches_whole(request, seed, flatten_exemplars, None) + |(mut request, seed, flatten_exemplars)| { + fill_unset_timestamps(&mut request); + let body = edited_body(&request, &mut SplitMix64(seed), None); + let case = check_body(&request, &body, flatten_exemplars)?; + prop_assert_eq!(case, Case::Decoded); + Ok(()) }, ); } #[test] - fn otel_pb_streamed_errors_match_whole_decoding() { + fn otel_pb_streamed_cut_bodies_match_whole_decoding() { + let cases = Cases::default(); check( - "otel_pb_streamed_errors_match_whole_decoding", + "otel_pb_streamed_cut_bodies_match_whole_decoding", 192, (requests(), any::(), any::()), - |(request, seed, cut)| streamed_matches_whole(request, seed, false, Some(cut)), + |(mut request, seed, cut)| { + fill_unset_timestamps(&mut request); + let mut body = edited_body(&request, &mut SplitMix64(seed), None); + body.truncate((cut % (body.len() as u64 + 1)) as usize); + cases.add(check_body(&request, &body, false)?); + Ok(()) + }, ); + cases.print("otel_pb_streamed_cut_bodies"); } - /// Single-byte damage: streamed and whole decoding accept and refuse the same - /// bodies, with the same rows, and give the same error (the sizing pass reports - /// the break prost meets first, see `first_error`) + /// Single-byte damage anywhere in the body #[test] fn otel_pb_streamed_damaged_bodies_match_whole_decoding() { - let (refused, other_error) = (AtomicUsize::new(0), AtomicUsize::new(0)); + let cases = Cases::default(); check( "otel_pb_streamed_damaged_bodies_match_whole_decoding", 192, (requests(), any::(), any::(), any::()), |(mut request, seed, at, byte)| { fill_unset_timestamps(&mut request); - let mut body = edited_body(&request, &mut SplitMix64(seed)); + let mut body = edited_body(&request, &mut SplitMix64(seed), None); if !body.is_empty() { let at = (at % body.len() as u64) as usize; body[at] = byte; } - match ( - whole(&request, &body, false), - streamed(&request, &body, false), - ) { - (Ok(whole), Ok(streamed)) => prop_assert_eq!(whole, streamed), - (Err(whole), Err(streamed)) => { - refused.fetch_add(1, Ordering::Relaxed); - if whole != streamed { - other_error.fetch_add(1, Ordering::Relaxed); - } - prop_assert_eq!(whole, streamed, "error texts differ"); - } - (whole, streamed) => prop_assert!( - false, - "whole {:?} and streamed {:?} disagree", - whole.map(|_| ()), - streamed.map(|_| ()) - ), - } + cases.add(check_body(&request, &body, false)?); Ok(()) }, ); - println!( - "otel_pb_streamed_damaged_bodies: refused {} bodies, {} with another error text", - refused.into_inner(), - other_error.into_inner() + cases.print("otel_pb_streamed_damaged_bodies"); + } + + /// Damage inside one record, whose framing is rewritten to fit: the framing + /// above the records holds, so the rows of every record before a record that + /// no longer decodes are staged + #[test] + fn otel_pb_streamed_damaged_records_keep_the_rows_before_them() { + let cases = Cases::default(); + check( + "otel_pb_streamed_damaged_records_keep_the_rows_before_them", + 192, + ( + requests(), + any::(), + any::<(u64, u64, u8, bool)>(), + any::(), + ), + |(mut request, seed, (index, at, byte, cut), flatten_exemplars)| { + fill_unset_timestamps(&mut request); + let records = request.record_count(); + prop_assume!(records > 0); + let damage = RecordDamage { + index: index % records, + at, + byte, + cut, + }; + let body = edited_body(&request, &mut SplitMix64(seed), Some(damage)); + let case = check_body(&request, &body, flatten_exemplars)?; + prop_assert!(case != Case::Outer, "record damage broke the levels above"); + cases.add(case); + Ok(()) + }, + ); + cases.print("otel_pb_streamed_damaged_records"); + assert!(cases.get(Case::Partial) > 0, "no partial case was met"); + } + + /// Arbitrary bytes as a record of every kind stay under the bound on decoded + /// bytes per wire byte + #[test] + fn otel_pb_decoded_size_bound_holds_for_arbitrary_records() { + check( + "otel_pb_decoded_size_bound_holds_for_arbitrary_records", + 512, + (vec(any::(), 0..512), 0..3usize), + |(bytes, leaf)| { + let leaf = [Leaf::LogRecord, Leaf::Span, Leaf::Metric][leaf]; + prop_assert!( + leaf_decoded_size(&bytes, leaf) + <= leaf_struct_size(leaf) + bytes_per_wire_byte(leaf) * bytes.len() + ); + Ok(()) + }, ); } @@ -3111,20 +3672,35 @@ mod streamed { }], }); let body = web::Bytes::from(request.encode_pb()); - let estimate = crate::otel::decoded_size::leaf_decoded_size( + let estimate = leaf_decoded_size( &request_span_bytes(&request), crate::otel::decoded_size::Leaf::Span, ); - let (_, allocated) = crate::test_alloc::measure(|| { - size_request(body.clone(), Signal::Traces, estimate - 1, false) - }); - assert!(matches!( - size_request(body.clone(), Signal::Traces, estimate - 1, false), - Err(StreamError::RecordTooLarge { .. }) - )); + let read = |max_record: usize| { + let mut rows = 0usize; + let mut chunker = Chunker::new(CHUNK_LIMITS, |chunk: Vec, _| { + rows += chunk.len(); + Ok::<_, JsonFlattenError>(()) + }); + let result = flatten_request( + &body, + Signal::Traces, + max_record, + &mut FlattenBudget::new(FlattenLimits::DEFAULT), + false, + &mut chunker, + ) + .and_then(|()| chunker.finish().map_err(StreamError::Consumer)); + drop(chunker); + (result, rows) + }; + let (refused, allocated) = crate::test_alloc::measure(|| read(estimate - 1)); + assert!(matches!(refused.0, Err(StreamError::RecordTooLarge { .. }))); + assert_eq!(refused.1, 0); assert!(allocated.peak < 64 * 1024, "peak {} B", allocated.peak); - let size = size_request(body, Signal::Traces, estimate, false).unwrap(); - assert_eq!(size.rows, 1 << 16); + let (read, rows) = read(estimate); + assert!(read.is_ok()); + assert_eq!(rows, 1 << 16); } fn request_span_bytes(request: &Req) -> Vec { @@ -3133,4 +3709,382 @@ mod streamed { _ => unreachable!(), } } + + // ----------------------------------------------------------------------- + // Partial success after chunks were staged, without the server + // ----------------------------------------------------------------------- + + const T0: u64 = 1_700_000_000_000_000_000; + + fn string_value(value: String) -> Option { + Some(AnyValue { + value: Some(any_value::Value::StringValue(value)), + }) + } + + /// One resource of `attributes` attributes over `records` log records + fn logs_request(records: usize, attributes: usize) -> Req { + Req::Logs(LogsData { + resource_logs: vec![ResourceLogs { + resource: Some(Resource { + attributes: (0..attributes) + .map(|i| KeyValue { + key: format!("resource.attribute.{i:02}"), + value: string_value(format!("value-of-attribute-{i:02}")), + ..Default::default() + }) + .collect(), + ..Default::default() + }), + scope_logs: vec![ScopeLogs { + log_records: (0..records) + .map(|i| LogRecord { + time_unix_nano: T0 + i as u64, + observed_time_unix_nano: T0 + i as u64, + severity_number: 9, + severity_text: format!("S{i:07}"), + body: string_value(format!("record {i}")), + ..Default::default() + }) + .collect(), + ..Default::default() + }], + ..Default::default() + }], + }) + } + + /// `metrics` sum metrics of `points` points each, under a resource without a + /// target identity (so no `target_info` row) + fn metrics_request(metrics: usize, points: usize) -> Req { + Req::Metrics(MetricsData { + resource_metrics: vec![ResourceMetrics { + scope_metrics: vec![ScopeMetrics { + metrics: (0..metrics) + .map(|m| Metric { + name: format!("metric{m:05}"), + data: Some(metric::Data::Sum(Sum { + data_points: (0..points) + .map(|p| NumberDataPoint { + time_unix_nano: T0 + p as u64, + start_time_unix_nano: T0, + value: Some(number_data_point::Value::AsInt(p as i64)), + ..Default::default() + }) + .collect(), + aggregation_temporality: 2, + is_monotonic: true, + })), + ..Default::default() + }) + .collect(), + ..Default::default() + }], + ..Default::default() + }], + }) + } + + /// Replaces the first byte of the only occurrence of `marker` in `body` with + /// 0xff, so the string it is in is not UTF-8 + fn damage_marker(body: &mut [u8], marker: &[u8]) { + let at: Vec = body + .windows(marker.len()) + .enumerate() + .filter(|(_, window)| *window == marker) + .map(|(at, _)| at) + .collect(); + assert_eq!(at.len(), 1); + body[at[0]] = 0xff; + } + + /// Where staging hands its chunks in these tests + #[derive(Default)] + struct Staged2 { + rows: Vec, + bytes: usize, + chunks: usize, + } + + fn collect(staged: &mut Staged2) -> impl FnMut(Vec) -> Result<(), PostError> + '_ { + |rows| { + staged.bytes += rows + .iter() + .map(|row| crate::otel::sink::row_bytes(row.as_object().unwrap())) + .sum::(); + staged.chunks += 1; + staged.rows.extend(rows); + Ok(()) + } + } + + fn target(source: &LogSource) -> OtelTarget<'_> { + static NO_FIELDS: std::sync::LazyLock> = + std::sync::LazyLock::new(HashMap::new); + OtelTarget { + stream_name: "test_stream", + log_source: source, + p_custom_fields: &NO_FIELDS, + telemetry_type: match source { + LogSource::OtelLogs => TelemetryType::Logs, + LogSource::OtelMetrics => TelemetryType::Metrics, + _ => TelemetryType::Traces, + }, + tenant_id: &None, + } + } + + fn limits(rows: usize, max_expanded: u64) -> StageLimits { + StageLimits { + chunk: ChunkLimits { + rows, + bytes: usize::MAX, + }, + max_expanded, + flatten: FlattenLimits::DEFAULT, + } + } + + /// Stages `request` in both encodings with `stage`, the JSON one decoded as + /// ingestion decodes it + fn stage_both( + request: &Req, + limits: StageLimits, + mut stage: impl FnMut(bool, Vec) -> Result<(), PostError>, + ) -> [(Result, Staged); 2] { + let source = request.source(); + let target = target(&source); + let protobuf = stage_otel_protobuf( + web::Bytes::from(request.encode_pb()), + &target, + PROTOBUF_OPTIONS, + limits, + |rows| stage(true, rows), + ); + let decoded = decode_as(request, false); + let json = stage_otel_resources(decoded.resources(), false, limits, |rows| { + stage(false, rows) + }); + [protobuf, json] + } + + /// The expansion cap is a running total: a request passing it after chunks + /// were staged is a partial success, the same in both encodings; one passing + /// it in its first chunk is refused, as before anything is staged + #[test] + fn otel_over_the_expansion_cap_stops_alike_in_both_encodings() { + let request = logs_request(2000, 40); + let mut all = Staged2::default(); + let (whole, _) = stage_otel_protobuf( + web::Bytes::from(request.encode_pb()), + &target(&request.source()), + PROTOBUF_OPTIONS, + limits(100, u64::MAX), + collect(&mut all), + ); + assert_eq!(whole.unwrap(), OtelIngested::Full); + assert_eq!(all.rows.len(), 2000); + + // About two fifths of the rows fit under the cap + let cap = all.bytes as u64 * 2 / 5; + let mut staged = [Staged2::default(), Staged2::default()]; + let [protobuf, json] = stage_both(&request, limits(100, cap), |protobuf, rows| { + collect(&mut staged[usize::from(protobuf)])(rows) + }); + for (outcome, counted) in [&protobuf, &json] { + assert!(counted.chunks > 0 && counted.records < 2000, "{counted:?}"); + let message = format!( + "Invalid Request: The rows of the request take more than the {cap} bytes allowed (1024 times P_MAX_EVENT_PAYLOAD_SIZE). Split the batch into smaller requests, or send fewer resource, scope and span attributes per record" + ); + assert_eq!( + outcome.as_ref().unwrap(), + &OtelIngested::Partial { + rejected: 2000 - counted.records as i64, + message + } + ); + assert!(counted.rows as f64 * 1.0 <= 2000.0 * 0.4 + 100.0); + } + assert_eq!(protobuf.1, json.1); + assert_eq!( + serde_json::to_vec(&staged[0].rows).unwrap(), + serde_json::to_vec(&staged[1].rows).unwrap() + ); + println!( + "over the cap: {} of 2000 records staged in {} chunks, {} rejected", + protobuf.1.records, + protobuf.1.chunks, + 2000 - protobuf.1.records + ); + + // Passed in the first chunk: refused as before staging + let [protobuf, json] = stage_both(&request, limits(100, 1000), |_, _| Ok(())); + for (outcome, counted) in [protobuf, json] { + assert_eq!(counted.chunks, 0); + let error = outcome.unwrap_err(); + assert!(matches!(error, PostError::Invalid(_)), "{error:?}"); + assert!( + error + .to_string() + .contains("more than the 1000 bytes allowed") + ); + } + } + + /// A record that does not decode, met after chunks were staged, is a partial + /// success with prost's error; as the first record, a refusal with it + #[test] + fn otel_pb_record_damaged_late_is_a_partial_success() { + for (damaged, staged_records) in [(999, 900), (0, 0)] { + let mut request = logs_request(1000, 5); + if let Req::Logs(data) = &mut request { + data.resource_logs[0].scope_logs[0].log_records[damaged].severity_text = + "DAMAGEME".into(); + } + let mut body = request.encode_pb(); + damage_marker(&mut body, b"DAMAGEME"); + let prost_error = OtelProtobufRequest::decode(&body, &request.source()) + .unwrap_err() + .to_string(); + let mut staged_rows = Staged2::default(); + let (outcome, staged) = stage_otel_protobuf( + web::Bytes::from(body), + &target(&request.source()), + PROTOBUF_OPTIONS, + limits(100, u64::MAX), + collect(&mut staged_rows), + ); + let message = + format!("Invalid Request: Ingestion failed for stream test_stream: {prost_error}"); + assert_eq!(staged.records, staged_records); + if staged_records > 0 { + assert_eq!(staged.chunks, 9); + assert_eq!( + outcome.unwrap(), + OtelIngested::Partial { + rejected: 1000 - staged_records as i64, + message + } + ); + } else { + assert_eq!(outcome.unwrap_err().to_string(), message); + } + println!("damaged record {damaged}: {prost_error}"); + } + } + + /// A record over the decoded size cap, met after chunks were staged, is a + /// partial success; it is measured because it is long enough to reach the cap + #[test] + fn otel_pb_record_over_the_cap_late_is_a_partial_success() { + let mut request = logs_request(1000, 5); + if let Req::Logs(data) = &mut request { + data.resource_logs[0].scope_logs[0].log_records[999].body = + string_value("x".repeat(100_000)); + } + let options = ProtobufOptions { + max_payload: 4096, + flatten_exemplars: false, + }; + let max_record = crate::otel::protobuf_stream::max_record_bytes(options.max_payload); + assert!(crate::otel::decoded_size::needs_measuring( + 100_010, + Leaf::LogRecord, + max_record + )); + assert!(!crate::otel::decoded_size::needs_measuring( + 100, + Leaf::LogRecord, + max_record + )); + let (outcome, staged) = stage_otel_protobuf( + web::Bytes::from(request.encode_pb()), + &target(&request.source()), + options, + limits(100, u64::MAX), + |_| Ok(()), + ); + assert_eq!(staged.records, 900); + match outcome.unwrap() { + OtelIngested::Partial { rejected, message } => { + assert_eq!(rejected, 100); + assert!( + message + .contains("one LogRecord of the request would take more than 65536 bytes"), + "{message}" + ); + } + other => panic!("{other:?}"), + } + } + + /// A metrics request stopped after some chunks rejects exactly the data points + /// not staged: when staging refuses a chunk (both encodings), when a later + /// metric does not decode (its points read from the wire), and a server error + /// keeps its status + #[test] + fn otel_metrics_stopped_after_some_chunks_reject_the_points_not_staged() { + let request = metrics_request(10, 37); + let refusal = || PostError::Invalid(anyhow::anyhow!("schema conflict")); + let mut calls = [0, 0]; + let [protobuf, json] = stage_both(&request, limits(50, u64::MAX), |protobuf, _| { + let calls = &mut calls[usize::from(protobuf)]; + *calls += 1; + if *calls == 4 { Err(refusal()) } else { Ok(()) } + }); + for (outcome, staged) in [protobuf, json] { + assert_eq!(staged.points, 150); + assert_eq!(staged.records, 4); + assert_eq!( + outcome.unwrap(), + OtelIngested::Partial { + rejected: 370 - 150, + message: "Invalid Request: schema conflict".into() + } + ); + } + + // Metric 8 does not decode: metrics 0-7 (296 points) were flattened, 250 of + // them in full chunks; its 37 points are read from the wire + let mut damaged = request.clone(); + if let Req::Metrics(data) = &mut damaged { + data.resource_metrics[0].scope_metrics[0].metrics[8].name = "DAMAGEME".into(); + } + let mut body = damaged.encode_pb(); + damage_marker(&mut body, b"DAMAGEME"); + let body = web::Bytes::from(body); + assert_eq!(count_points(&body), 370); + let (outcome, staged) = stage_otel_protobuf( + body, + &target(&request.source()), + PROTOBUF_OPTIONS, + limits(50, u64::MAX), + |_| Ok(()), + ); + assert_eq!((staged.chunks, staged.points), (5, 250)); + match outcome.unwrap() { + OtelIngested::Partial { rejected, message } => { + assert_eq!(rejected, 370 - 250); + assert!(message.contains("invalid string value"), "{message}"); + } + other => panic!("{other:?}"), + } + + // A server error after chunks were staged keeps its status + let mut calls = 0; + let [protobuf, _] = stage_both(&request, limits(50, u64::MAX), |protobuf, _| { + calls += usize::from(protobuf); + if protobuf && calls == 2 { + Err(PostError::JsonFlattenError(JsonFlattenError::CannotFlatten)) + } else { + Ok(()) + } + }); + let error = protobuf.0.unwrap_err(); + assert!( + actix_web::ResponseError::status_code(&error).is_server_error(), + "{error:?}" + ); + assert_eq!(protobuf.1.chunks, 1); + } } diff --git a/src/otel.rs b/src/otel.rs index 9d4128c15..98e47836c 100644 --- a/src/otel.rs +++ b/src/otel.rs @@ -17,7 +17,6 @@ */ pub mod decoded_size; -pub mod expansion; pub mod logs; pub mod metrics; pub mod otel_utils; @@ -119,18 +118,19 @@ pub(crate) mod bench { pub fn chunked( flatten: impl FnOnce( &mut super::sink::Chunker< - &mut dyn FnMut(Vec) -> Result<(), JsonFlattenError>, + &mut dyn FnMut(Vec, usize) -> Result<(), JsonFlattenError>, >, ) -> Result<(), JsonFlattenError>, ) -> Vec { let mut rows = Vec::new(); - let mut stage = |chunk: Vec| { + let mut stage = |chunk: Vec, _bytes: usize| { rows.extend(chunk); Ok(()) }; let mut chunker = super::sink::Chunker::new( super::sink::CHUNK_LIMITS, - &mut stage as &mut dyn FnMut(Vec) -> Result<(), JsonFlattenError>, + &mut stage + as &mut dyn FnMut(Vec, usize) -> Result<(), JsonFlattenError>, ); flatten(&mut chunker).expect("benchmark rows flatten"); chunker.finish().expect("benchmark rows stage"); diff --git a/src/otel/decoded_size.rs b/src/otel/decoded_size.rs index cc1304e30..4f04ccf3c 100644 --- a/src/otel/decoded_size.rs +++ b/src/otel/decoded_size.rs @@ -35,6 +35,7 @@ //! the text of a hex or base64 field, more than the bytes it decodes to. use std::mem::size_of; +use std::sync::LazyLock; use opentelemetry_proto::tonic::common::v1::{AnyValue, EntityRef, KeyValue}; use opentelemetry_proto::tonic::logs::v1::{LogRecord, ResourceLogs, ScopeLogs}; @@ -62,17 +63,137 @@ pub enum Leaf { /// occurrences into one `Vec` that grows past the sum of their capacities). A record /// whose framing breaks is counted up to the break, where decoding it fails too. pub fn leaf_decoded_size(body: &[u8], leaf: Leaf) -> usize { - let (msg, own) = match leaf { - Leaf::LogRecord => (Msg::LogRecord, size_of::()), - Leaf::Span => (Msg::Span, size_of::()), - Leaf::Metric => (Msg::Metric, size_of::()), + let msg = match leaf { + Leaf::LogRecord => Msg::LogRecord, + Leaf::Span => Msg::Span, + Leaf::Metric => Msg::Metric, }; - let mut size = own; + let mut size = leaf_struct_size(leaf); // A leaf is three messages deep in its request let _ = scan(body, msg, 3, &mut size); size } +/// Most estimated bytes ([`leaf_decoded_size`]) one wire byte of a `leaf` record adds +/// beyond the record's own struct: `leaf_decoded_size(body, leaf) <= size_of the leaf +/// + bytes_per_wire_byte(leaf) * body.len()` for every `body`, valid or not. +/// +/// The bound is `B = max(8, 2 * S)`, where `S` is the largest element of a repeated +/// field reachable from the leaf. By induction over the messages of a body, each +/// message adds at most `B` times its own encoded length: +/// - a nested message adds what its fields add (its own struct is counted by the +/// `Vec` that holds it, or is part of its parent's struct); +/// - a string or bytes field of `L > 0` bytes adds `max(8, L) <= 8 * L`, and is +/// `L` bytes of content plus at least 2 of key and length; +/// - a repeated field of `n` elements adds a `Vec` of at most `max(4, n.next_power_of_two()) +/// <= 2 * n + 2` elements of `S` bytes, while each element takes at least 2 wire +/// bytes besides its content (a key and a length, or a key and a 1-byte varint; +/// a packed run of `n` numbers takes `n + 2`): `(2n + 2) * S <= 2 * S * 2n`. +/// +/// So a record can come close to `S` bytes per wire byte (many empty elements of the +/// largest kind, 2 bytes each) and reach `2 * S` (one empty element alone in its +/// `Vec`, which holds 4); `bound_holds_for_crafted_and_random_records` checks it. +pub fn bytes_per_wire_byte(leaf: Leaf) -> usize { + static BOUNDS: LazyLock<[usize; 3]> = LazyLock::new(|| { + [ + reachable_bound(Msg::LogRecord), + reachable_bound(Msg::Span), + reachable_bound(Msg::Metric), + ] + }); + BOUNDS[leaf as usize] +} + +/// Bytes of the struct of a `leaf` record +pub fn leaf_struct_size(leaf: Leaf) -> usize { + match leaf { + Leaf::LogRecord => size_of::(), + Leaf::Span => size_of::(), + Leaf::Metric => size_of::(), + } +} + +/// Whether a `leaf` record of `len` wire bytes can take more than `limit` bytes once +/// decoded ([`leaf_decoded_size`]); one that can not needs no measuring +#[inline] +pub fn needs_measuring(len: usize, leaf: Leaf, limit: usize) -> bool { + leaf_struct_size(leaf).saturating_add(bytes_per_wire_byte(leaf).saturating_mul(len)) > limit +} + +/// Field numbers of the OTLP schema are all below this +const MAX_FIELD_NUMBER: u64 = 32; + +/// `max(8, 2 * S)` over the repeated fields of the messages reachable from `root`, +/// see [`bytes_per_wire_byte`] +fn reachable_bound(root: Msg) -> usize { + let mut bound = 8; + let mut seen = vec![root]; + let mut stack = vec![root]; + while let Some(msg) = stack.pop() { + for number in 1..MAX_FIELD_NUMBER { + let Some(Field { kind, slot }) = msg.field(number) else { + continue; + }; + if slot.is_some() { + bound = bound.max(2 * kind.element_size()); + } + if let Kind::Message(child) = kind + && !seen.contains(&child) + { + seen.push(child); + stack.push(child); + } + } + } + bound +} + +/// Data points the metric `body` (its encoding, without a length prefix) decodes to: +/// the elements of the `data_points` field of its `data`, which prost merges when the +/// same kind of data occurs again and replaces when another kind follows. Read from +/// the wire, without decoding the metric. A metric whose framing breaks is counted up +/// to the break. +pub fn metric_points(mut body: &[u8]) -> u64 { + let (mut kind, mut points) = (0, 0); + while !body.is_empty() { + let Ok((number, wire)) = key(&mut body) else { + break; + }; + // `gauge`, `sum`, `histogram`, `exponential_histogram`, `summary` + if matches!(number, 5 | 7 | 9 | 10 | 11) && wire == LEN { + let Ok(data) = varint(&mut body).and_then(|len| take(&mut body, len)) else { + break; + }; + let found = data_points(data); + if number == kind { + points += found; + } else { + (kind, points) = (number, found); + } + } else if skip(&mut body, wire, number, 0).is_err() { + break; + } + } + points +} + +/// Elements of field 1 (`data_points`) of the `data` of a metric, up to a break +fn data_points(mut body: &[u8]) -> u64 { + let mut points = 0; + while !body.is_empty() { + let Ok((number, wire)) = key(&mut body) else { + break; + }; + if skip(&mut body, wire, number, 0).is_err() { + break; + } + if number == 1 && wire == LEN { + points += 1; + } + } + points +} + /// Messages of the OTLP schema whose fields allocate when decoded. Leaf records are /// sized on their own (`leaf_decoded_size`); the levels above them are walked by /// prost in `protobuf_stream`, so their variants are only reached from each other. @@ -480,3 +601,195 @@ fn scan_fields( } Ok(()) } + +#[cfg(test)] +mod tests { + use super::*; + use opentelemetry_proto::tonic::metrics::v1::{Gauge, Sum, metric}; + use prost::Message as _; + + fn put_varint(out: &mut Vec, mut value: u64) { + while value >= 0x80 { + out.push(value as u8 | 0x80); + value >>= 7; + } + out.push(value as u8); + } + + fn put_key(out: &mut Vec, number: u64, wire: u64) { + put_varint(out, (number << 3) | wire); + } + + fn len_field(number: u64, body: &[u8]) -> Vec { + let mut out = Vec::new(); + put_key(&mut out, number, LEN); + put_varint(&mut out, body.len() as u64); + out.extend_from_slice(body); + out + } + + /// The shortest path of field numbers from `root` to every message reachable from it + fn paths(root: Msg) -> Vec<(Msg, Vec)> { + let mut found = vec![(root, vec![])]; + let mut next = 0; + while next < found.len() { + let (msg, path) = found[next].clone(); + next += 1; + for number in 1..MAX_FIELD_NUMBER { + if let Some(Field { + kind: Kind::Message(child), + .. + }) = msg.field(number) + && !found.iter().any(|(seen, _)| *seen == child) + { + let mut path = path.clone(); + path.push(number); + found.push((child, path)); + } + } + } + found + } + + /// Records of `root` built to come close to the bound: for every repeated field + /// of every message reachable from it, `n` elements of the fewest wire bytes, + /// packed and unpacked, inside the shortest path to that message + fn crafted(root: Msg) -> Vec> { + let mut records = Vec::new(); + for (msg, path) in paths(root) { + for number in 1..MAX_FIELD_NUMBER { + let Some(Field { + kind, + slot: Some(_), + }) = msg.field(number) + else { + continue; + }; + for n in [1, 2, 3, 5, 9, 17, 33, 1025, 4097] { + let mut bodies = vec![Vec::new()]; + match kind { + Kind::Message(_) | Kind::Bytes => { + for _ in 0..n { + put_key(&mut bodies[0], number, LEN); + bodies[0].push(0); + } + } + Kind::Numbers(encoding) => { + let (wire, width) = match encoding { + Encoding::Varint => (VARINT, 1), + Encoding::Fixed64 => (FIXED64, 8), + }; + for _ in 0..n { + put_key(&mut bodies[0], number, wire); + bodies[0].extend(std::iter::repeat_n(0, width)); + } + bodies.push(len_field(number, &vec![0; n * width])); + } + } + for mut body in bodies { + for &field in path.iter().rev() { + body = len_field(field, &body); + } + records.push(body); + } + } + } + } + records + } + + #[test] + fn bound_holds_for_crafted_and_random_records() { + println!( + "STRUCTS KeyValue {} AnyValue {} Event {} Link {} NumberDataPoint {} HistogramDataPoint {} ExponentialHistogramDataPoint {} SummaryDataPoint {} ValueAtQuantile {} Exemplar {}", + size_of::(), + size_of::(), + size_of::(), + size_of::(), + size_of::(), + size_of::(), + size_of::(), + size_of::(), + size_of::(), + size_of::(), + ); + let cap = crate::otel::protobuf_stream::max_record_bytes(10 * 1024 * 1024); + for (leaf, root) in [ + (Leaf::LogRecord, Msg::LogRecord), + (Leaf::Span, Msg::Span), + (Leaf::Metric, Msg::Metric), + ] { + let bound = bytes_per_wire_byte(leaf); + let own = leaf_struct_size(leaf); + let mut worst: f64 = 0.0; + let records = crafted(root); + for record in &records { + let size = leaf_decoded_size(record, leaf); + assert!( + size <= own + bound * record.len(), + "{leaf:?}: {size} B from {} wire bytes", + record.len() + ); + worst = worst.max((size - own) as f64 / record.len() as f64); + } + let threshold = (0..).find(|&len| needs_measuring(len, leaf, cap)).unwrap(); + println!( + "BOUND {leaf:?}: {bound} decoded bytes per wire byte, struct {own} B, {} crafted records reach {worst:.1}; at the default cap ({cap} B) records from {threshold} wire bytes are measured", + records.len() + ); + // Close to tight: a record reaches at least half of it + assert!(worst >= bound as f64 / 2.0, "{leaf:?}: {worst} of {bound}"); + assert_eq!(threshold, (cap - own) / bound + 1); + } + } + + fn metric_with(data: metric::Data) -> Vec { + Metric { + name: "m".into(), + data: Some(data), + ..Default::default() + } + .encode_to_vec() + } + + fn gauge(points: usize) -> Vec { + metric_with(metric::Data::Gauge(Gauge { + data_points: vec![NumberDataPoint::default(); points], + })) + } + + fn sum(points: usize) -> Vec { + metric_with(metric::Data::Sum(Sum { + data_points: vec![NumberDataPoint::default(); points], + ..Default::default() + })) + } + + /// Concatenated encodings decode as one merged metric: the same kind of data + /// merges, another kind replaces it + #[test] + fn data_points_read_from_the_wire_match_decoding() { + let cases: Vec> = vec![ + gauge(3), + [gauge(3), gauge(4)].concat(), + [gauge(3), sum(2)].concat(), + [gauge(3), sum(2), gauge(4)].concat(), + [sum(5), sum(0), sum(1)].concat(), + [gauge(2), Metric::default().encode_to_vec()].concat(), + Metric::default().encode_to_vec(), + ]; + for body in cases { + let decoded = Metric::decode(body.as_slice()).unwrap(); + let points = match decoded.data { + Some(metric::Data::Gauge(g)) => g.data_points.len(), + Some(metric::Data::Sum(s)) => s.data_points.len(), + None => 0, + _ => unreachable!(), + }; + assert_eq!(metric_points(&body), points as u64); + } + // Cut short: counted up to the break + let body = gauge(5); + assert!(metric_points(&body[..body.len() - 1]) < 5); + } +} diff --git a/src/otel/expansion.rs b/src/otel/expansion.rs deleted file mode 100644 index a3fd8749b..000000000 --- a/src/otel/expansion.rs +++ /dev/null @@ -1,611 +0,0 @@ -/* - * Parseable Server (C) 2022 - 2025 Parseable, Inc. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - * - */ - -//! What an OTLP request expands to, computed from the decoded message without -//! building a row. -//! -//! Every row carries its own copy of the resource, scope, span and metric fields, -//! so a small request can expand to a very large number of row bytes: 15 KB of -//! resource attributes copied into each of 5 million two-byte log records is tens -//! of GiB. Chunking bounds the memory this takes at once, not what is written to -//! staging, so the request is refused before anything is staged when its rows -//! would hold more than [`max_expanded_bytes`]. The sizes are in the units of -//! [`super::sink::row_bytes`], and follow the flatteners field by field; they are -//! estimates (JSON log bodies are counted as their text, not as the fields parsed -//! from them, which the flatten budget charges). - -use std::collections::HashSet; - -use opentelemetry_proto::tonic::common::v1::{ - AnyValue, InstrumentationScope, KeyValue, any_value::Value as OtelValue, -}; -use opentelemetry_proto::tonic::logs::v1::{LogRecord, ResourceLogs}; -use opentelemetry_proto::tonic::metrics::v1::{ - Exemplar, Metric, ResourceMetrics, exponential_histogram_data_point::Buckets, metric, -}; -use opentelemetry_proto::tonic::resource::v1::Resource; -use opentelemetry_proto::tonic::trace::v1::{ - ResourceSpans, Span, - span::{Event, Link}, -}; - -use super::sink::{ENTRY_BYTES, VALUE_BYTES, heap_bytes}; - -/// Rows, estimated row bytes and leaf records of one request -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub struct RequestSize { - /// Rows the request expands to - pub rows: u64, - /// Estimated memory of all of its rows, see `row_bytes` - pub bytes: u64, - /// Log records, spans or metrics - pub records: u64, - /// Metric data points - pub points: u64, -} - -impl RequestSize { - /// Adds `rows` rows of `row` bytes each - fn add_rows(&mut self, rows: u64, row: usize) { - self.rows += rows; - self.bytes = self.bytes.saturating_add(rows.saturating_mul(row as u64)); - } - - /// Adds bytes that only one row holds - fn add_bytes(&mut self, bytes: usize) { - self.bytes = self.bytes.saturating_add(bytes as u64); - } -} - -/// Estimated bytes of rows one request may expand to, for a payload limit of -/// `max_payload` bytes: `EXPANSION_FACTOR` row bytes per payload byte -pub fn max_expanded_bytes(max_payload: usize) -> u64 { - (max_payload as u64).saturating_mul(EXPANSION_FACTOR) -} - -/// Row bytes per payload byte a request may expand to. The most measured for a -/// request shaped like collector traffic is 459: short log records (a time, a -/// severity and a two-byte body) or bare gauge points under 30 Kubernetes resource -/// attributes; k8s logs, spans and metrics with ordinary records expand 40-110x -/// (`realistic_tests`). 1024 leaves 2.2x headroom over the worst of them, and -/// refuses the requests that copy kilobytes of shared fields into millions of -/// records of a few bytes (47,000 row bytes per body byte for 500 attributes over -/// empty records, `copied_fields_over_tiny_records_are_over_the_expansion_cap`), at 10 GiB of -/// rows for the default 10 MiB payload limit. -pub const EXPANSION_FACTOR: u64 = 1024; - -/// Timestamps are formatted as `%Y-%m-%dT%H:%M:%S%.9fZ` -const TIMESTAMP_LEN: usize = 30; -/// Longest decimal `i64` -const INT_LEN: usize = 20; - -#[inline] -fn field(key_len: usize, value_heap: usize) -> usize { - ENTRY_BYTES + heap_bytes(key_len) + value_heap -} - -#[inline] -fn str_field(key: &str, value_len: usize) -> usize { - field(key.len(), heap_bytes(value_len)) -} - -#[inline] -fn num_field(key: &str) -> usize { - field(key.len(), 0) -} - -#[inline] -fn timestamp_field(key: &str) -> usize { - str_field(key, TIMESTAMP_LEN) -} - -#[inline] -fn hex_field(key: &str, bytes: usize) -> usize { - str_field(key, 2 * bytes) -} - -/// Fields `insert_attributes` adds for `attributes`, with `prefix` before each key -fn attributes_bytes(attributes: &[KeyValue], prefix: usize) -> usize { - attributes - .iter() - .filter_map(|attribute| { - let value = attribute.value.as_ref()?.value.as_ref()?; - Some(value_fields(attribute.key.len() + prefix, value, prefix)) - }) - .sum() -} - -/// Fields one OTLP value adds under a key of `key_len` bytes -fn value_fields(key_len: usize, value: &OtelValue, prefix: usize) -> usize { - match value { - OtelValue::StringValue(s) => field(key_len, heap_bytes(s.len())), - OtelValue::BoolValue(_) | OtelValue::DoubleValue(_) => field(key_len, 0), - OtelValue::IntValue(_) => field(key_len, heap_bytes(INT_LEN)), - OtelValue::BytesValue(b) => field(key_len, heap_bytes(b.len())), - // Serialised to a JSON string - OtelValue::ArrayValue(array) => field(key_len, heap_bytes(array_json_len(&array.values))), - // Every entry becomes a field of its own, under its own key - OtelValue::KvlistValue(list) => list - .values - .iter() - .filter_map(|entry| { - let value = entry.value.as_ref()?.value.as_ref()?; - Some(value_fields(entry.key.len() + prefix, value, prefix)) - }) - .sum(), - OtelValue::StringValueStrindex(_) => 0, - } -} - -/// Approximate length of the JSON text of an array value -fn array_json_len(values: &[AnyValue]) -> usize { - 2 + values - .iter() - .map(|value| { - 1 + match &value.value { - Some(OtelValue::StringValue(s)) => s.len() + 2, - Some(OtelValue::BytesValue(b)) => b.len() + 2, - Some(OtelValue::ArrayValue(array)) => array_json_len(&array.values), - Some(OtelValue::KvlistValue(list)) => list - .values - .iter() - .map(|entry| { - entry.key.len() - + 4 - + entry - .value - .as_ref() - .map_or(4, |value| array_json_len(std::slice::from_ref(value))) - }) - .sum::(), - _ => INT_LEN, - } - }) - .sum::() -} - -fn scope_bytes(scope: Option<&InstrumentationScope>) -> usize { - scope.map_or(0, |scope| { - str_field("scope_name", scope.name.len()) - + str_field("scope_version", scope.version.len()) - + attributes_bytes(&scope.attributes, 0) - + num_field("scope_dropped_attributes_count") - }) -} - -fn resource_bytes(resource: Option<&Resource>) -> usize { - resource.map_or(0, |resource| { - attributes_bytes(&resource.attributes, 0) + num_field("resource_dropped_attributes_count") - }) -} - -// --------------------------------------------------------------------------- -// Logs -// --------------------------------------------------------------------------- - -fn log_record_bytes(record: &LogRecord) -> usize { - timestamp_field("time_unix_nano") - + timestamp_field("observed_time_unix_nano") - + num_field("severity_number") - + str_field("severity_text", record.severity_text.len().max(11)) - + record - .body - .as_ref() - .and_then(|body| body.value.as_ref()) - .map_or(0, |body| value_fields("body".len(), body, 0)) - + attributes_bytes(&record.attributes, 0) - + str_field("p_log_category", 11) - + num_field("log_record_dropped_attributes_count") - + num_field("flags") - + hex_field("span_id", record.span_id.len()) - + hex_field("trace_id", record.trace_id.len()) -} - -/// Sizes a logs request one part at a time, in the order of the request -#[derive(Debug, Default)] -pub struct LogsSizer { - size: RequestSize, - resource: usize, - shared: usize, -} - -impl LogsSizer { - pub fn resource(&mut self, resource: Option<&Resource>, schema_url: &str) { - self.resource = resource_bytes(resource) + str_field("schema_url", schema_url.len()); - } - - pub fn scope(&mut self, scope: Option<&InstrumentationScope>, schema_url: &str) { - self.shared = VALUE_BYTES - + self.resource - + scope_bytes(scope) - + str_field("scope_log_schema_url", schema_url.len()); - } - - pub fn record(&mut self, record: &LogRecord) { - self.size.records += 1; - self.size.add_rows(1, self.shared); - self.size.add_bytes(log_record_bytes(record)); - } - - pub fn finish(self) -> RequestSize { - self.size - } -} - -/// Rows and row bytes of a logs request -pub fn logs_size(resource_logs: &[ResourceLogs]) -> RequestSize { - let mut sizer = LogsSizer::default(); - for resource_log in resource_logs { - sizer.resource(resource_log.resource.as_ref(), &resource_log.schema_url); - for scope_log in &resource_log.scope_logs { - sizer.scope(scope_log.scope.as_ref(), &scope_log.schema_url); - for record in &scope_log.log_records { - sizer.record(record); - } - } - } - sizer.finish() -} - -// --------------------------------------------------------------------------- -// Traces -// --------------------------------------------------------------------------- - -fn span_bytes(span: &Span) -> usize { - hex_field("span_trace_id", span.trace_id.len()) - + hex_field("span_span_id", span.span_id.len()) - + str_field("span_trace_state", span.trace_state.len()) - + hex_field("span_parent_span_id", span.parent_span_id.len()) - + num_field("span_flags") - + str_field("span_flags_description", 26) - + str_field("span_name", span.name.len()) - + num_field("span_kind") - + str_field("span_kind_description", 11) - + timestamp_field("span_start_time_unix_nano") - + num_field("span_start_time_unix_nano_epoch") - + timestamp_field("span_end_time_unix_nano") - + num_field("span_end_time_unix_nano_epoch") - + num_field("span_duration_ns") - + attributes_bytes(&span.attributes, 0) - + num_field("span_dropped_attributes_count") - + num_field("span_dropped_events_count") - + num_field("span_dropped_links_count") - + span.status.as_ref().map_or(0, |status| { - str_field("span_status_message", status.message.len()) - + num_field("span_status_code") - + str_field("span_status_description", 5) - }) -} - -fn event_bytes(event: &Event) -> usize { - timestamp_field("event_time_unix_nano") - + num_field("event_time_unix_nano_epoch") - + str_field("event_name", event.name.len()) - + num_field("event_duration_ns") - + attributes_bytes(&event.attributes, "event_".len()) - + num_field("event_dropped_attributes_count") -} - -fn link_bytes(link: &Link) -> usize { - hex_field("link_span_id", link.span_id.len()) - + hex_field("link_trace_id", link.trace_id.len()) - + attributes_bytes(&link.attributes, "link_".len()) - + num_field("link_dropped_attributes_count") -} - -/// Sizes a traces request one part at a time, in the order of the request -#[derive(Debug, Default)] -pub struct TracesSizer { - size: RequestSize, - resource: usize, - shared: usize, -} - -impl TracesSizer { - pub fn resource(&mut self, resource: Option<&Resource>, schema_url: &str) { - self.resource = - resource_bytes(resource) + str_field("resource_schema_url", schema_url.len()); - } - - pub fn scope(&mut self, scope: Option<&InstrumentationScope>, schema_url: &str) { - self.shared = VALUE_BYTES - + self.resource - + scope_bytes(scope) - + str_field("scope_schema_url", schema_url.len()); - } - - pub fn span(&mut self, span: &Span) { - self.size.records += 1; - let rows = (span.events.len() + span.links.len()).max(1) as u64; - self.size.add_rows(rows, self.shared + span_bytes(span)); - for event in &span.events { - self.size.add_bytes(event_bytes(event)); - } - for link in &span.links { - self.size.add_bytes(link_bytes(link)); - } - } - - pub fn finish(self) -> RequestSize { - self.size - } -} - -/// Rows and row bytes of a traces request -pub fn traces_size(resource_spans: &[ResourceSpans]) -> RequestSize { - let mut sizer = TracesSizer::default(); - for resource_span in resource_spans { - sizer.resource(resource_span.resource.as_ref(), &resource_span.schema_url); - for scope_span in &resource_span.scope_spans { - sizer.scope(scope_span.scope.as_ref(), &scope_span.schema_url); - for span in &scope_span.spans { - sizer.span(span); - } - } - } - sizer.finish() -} - -// --------------------------------------------------------------------------- -// Metrics -// --------------------------------------------------------------------------- - -fn exemplar_fields(exemplar: &Exemplar) -> usize { - attributes_bytes(&exemplar.filtered_attributes, 0) - + timestamp_field("exemplar_time_unix_nano") - + hex_field("exemplar_span_id", exemplar.span_id.len()) - + hex_field("exemplar_trace_id", exemplar.trace_id.len()) - + exemplar - .value - .as_ref() - .map_or(0, |_| num_field("exemplar_value")) -} - -/// Bytes of the exemplars of one data point, including the column table that -/// structural flattening builds from them when they are kept nested -fn exemplars_bytes(exemplars: &[Exemplar], flatten_exemplars: bool) -> usize { - if exemplars.is_empty() { - return 0; - } - let fields: usize = exemplars.iter().map(exemplar_fields).sum(); - if flatten_exemplars { - return fields; - } - let mut keys: HashSet<&str> = HashSet::from([ - "exemplar_time_unix_nano", - "exemplar_span_id", - "exemplar_trace_id", - "exemplar_value", - ]); - for exemplar in exemplars { - keys.extend(exemplar.filtered_attributes.iter().map(|a| a.key.as_str())); - } - let n = exemplars.len(); - field("exemplars".len(), heap_bytes(n * VALUE_BYTES)) - + fields - + keys.len() * (ENTRY_BYTES + n * VALUE_BYTES) -} - -fn array_field(key: &str, len: usize) -> usize { - field(key.len(), heap_bytes(len * VALUE_BYTES)) -} - -fn buckets_bytes(prefix: &str, buckets: Option<&Buckets>) -> usize { - buckets.map_or(0, |buckets| { - field(prefix.len() + "_offset".len(), 0) - + field( - prefix.len() + "_bucket_count".len(), - heap_bytes(buckets.bucket_counts.len() * VALUE_BYTES), - ) - }) -} - -fn temporality_bytes() -> usize { - num_field("aggregation_temporality") + str_field("aggregation_temporality_description", 11) -} - -/// Own fields every data point row has, whatever its type -fn point_common(attributes: &[KeyValue]) -> usize { - attributes_bytes(attributes, 0) - + timestamp_field("start_time_unix_nano") - + timestamp_field("time_unix_nano") -} - -/// Rows and bytes of the data points of one metric, and the count of points -fn metric_points(metric: &Metric, flatten_exemplars: bool, row: usize, size: &mut RequestSize) { - let flags = num_field("data_point_flags") + str_field("data_point_flags_description", 22); - let mut points = |own: usize| { - size.add_rows(1, row); - size.add_bytes(own); - size.points += 1; - }; - let count = match &metric.data { - None => return, - Some(metric::Data::Gauge(gauge)) => { - for dp in &gauge.data_points { - points( - point_common(&dp.attributes) - + exemplars_bytes(&dp.exemplars, flatten_exemplars) - + flags - + num_field("data_point_value"), - ); - } - gauge.data_points.len() - } - Some(metric::Data::Sum(sum)) => { - for dp in &sum.data_points { - points( - point_common(&dp.attributes) - + exemplars_bytes(&dp.exemplars, flatten_exemplars) - + flags - + num_field("data_point_value") - + temporality_bytes() - + num_field("is_monotonic"), - ); - } - sum.data_points.len() - } - Some(metric::Data::Histogram(histogram)) => { - for dp in &histogram.data_points { - points( - point_common(&dp.attributes) - + num_field("data_point_count") - + num_field("data_point_sum") - + array_field("data_point_bucket_counts", dp.bucket_counts.len()) - + array_field("data_point_explicit_bounds", dp.explicit_bounds.len()) - + exemplars_bytes(&dp.exemplars, flatten_exemplars) - + flags - + num_field("data_point_min") - + num_field("data_point_max") - + temporality_bytes(), - ); - } - histogram.data_points.len() - } - Some(metric::Data::ExponentialHistogram(histogram)) => { - for dp in &histogram.data_points { - points( - point_common(&dp.attributes) - + num_field("data_point_count") - + num_field("data_point_sum") - + num_field("data_point_scale") - + num_field("data_point_zero_count") - + buckets_bytes("positive", dp.positive.as_ref()) - + buckets_bytes("negative", dp.negative.as_ref()) - + exemplars_bytes(&dp.exemplars, flatten_exemplars) - + temporality_bytes(), - ); - } - histogram.data_points.len() - } - Some(metric::Data::Summary(summary)) => { - for dp in &summary.data_points { - let n = dp.quantile_values.len(); - points( - point_common(&dp.attributes) - + num_field("data_point_count") - + num_field("data_point_sum") - + array_field("data_point_quantile_values", n) - // Two fields per quantile, then a column table of two keys - + n * 2 * field("quantile".len(), 0) - + if n > 0 { - 2 * (ENTRY_BYTES + n * VALUE_BYTES) - } else { - 0 - }, - ); - } - summary.data_points.len() - } - }; - if count == 0 { - // The one row of a metric that has data but no data points - size.add_rows(1, row); - size.add_bytes(temporality_bytes() + num_field("is_monotonic")); - } -} - -/// Sizes a metrics request one part at a time, in the order of the request -#[derive(Debug, Default)] -pub struct MetricsSizer { - size: RequestSize, - flatten_exemplars: bool, - identity: bool, - resource: usize, - envelope: usize, - any_rows: bool, -} - -impl MetricsSizer { - pub fn new(flatten_exemplars: bool) -> Self { - Self { - flatten_exemplars, - ..Self::default() - } - } - - pub fn resource(&mut self, resource: Option<&Resource>, schema_url: &str) { - // Built once per resource, as the flattener does, since the identity is - // read from the flattened resource fields - self.identity = - super::metrics::ResourceMetricFields::new(resource, schema_url).has_target_identity(); - self.resource = resource_bytes(resource) - + str_field("resource_schema_url", schema_url.len()) - + if self.identity { - str_field("job", 32) + str_field("instance", 32) - } else { - 0 - }; - self.any_rows = false; - } - - pub fn scope(&mut self, scope: Option<&InstrumentationScope>, schema_url: &str) { - self.envelope = - self.resource + scope_bytes(scope) + str_field("scope_schema_url", schema_url.len()); - } - - pub fn metric(&mut self, metric: &Metric) { - self.size.records += 1; - let row = VALUE_BYTES - + self.envelope - + str_field("metric_name", metric.name.len()) - + str_field("metric_description", metric.description.len()) - + str_field("metric_unit", metric.unit.len()) - + str_field("metric_type", 21) - + attributes_bytes(&metric.metadata, 0) - + num_field(super::metrics::SERIES_HASH_COLUMN); - self.any_rows |= metric.data.is_some(); - metric_points(metric, self.flatten_exemplars, row, &mut self.size); - } - - pub fn resource_end(&mut self) { - if self.identity && self.any_rows { - // target_info - self.size.add_rows( - 1, - VALUE_BYTES - + self.resource - + 6 * str_field("metric_description", 16) - + num_field(super::metrics::SERIES_HASH_COLUMN), - ); - } - } - - pub fn finish(self) -> RequestSize { - self.size - } -} - -/// Rows and row bytes of a metrics request -pub fn metrics_size(resource_metrics: &[ResourceMetrics], flatten_exemplars: bool) -> RequestSize { - let mut sizer = MetricsSizer::new(flatten_exemplars); - for resource_metric in resource_metrics { - sizer.resource( - resource_metric.resource.as_ref(), - &resource_metric.schema_url, - ); - for scope_metric in &resource_metric.scope_metrics { - sizer.scope(scope_metric.scope.as_ref(), &scope_metric.schema_url); - for metric in &scope_metric.metrics { - sizer.metric(metric); - } - } - sizer.resource_end(); - } - sizer.finish() -} diff --git a/src/otel/logs.rs b/src/otel/logs.rs index 5002aaa85..3337929d9 100644 --- a/src/otel/logs.rs +++ b/src/otel/logs.rs @@ -1269,10 +1269,9 @@ mod tests { ExportLogsServiceRequest { resource_logs } } - /// What ingestion does with a decoded request before staging: the sizing - /// pass, then the rows handed over in chunks (collected here) + /// What ingestion does with a decoded request: its rows handed over in + /// chunks (collected here) fn flatten(request: &ExportLogsServiceRequest) -> Vec { - std::hint::black_box(crate::otel::expansion::logs_size(&request.resource_logs)); let mut budget = FlattenBudget::new(FlattenLimits::DEFAULT); bench::chunked(|chunker| { super::super::flatten_logs_into(&request.resource_logs, &mut budget, chunker) diff --git a/src/otel/memory_tests.rs b/src/otel/memory_tests.rs index 59c530f34..92e8e723b 100644 --- a/src/otel/memory_tests.rs +++ b/src/otel/memory_tests.rs @@ -59,7 +59,7 @@ fn kv(key: impl Into, value: any_value::Value) -> KeyValue { } /// Takes a chunk of rows, as staging does -type Stage<'a> = dyn FnMut(Vec) -> Result<(), JsonFlattenError> + 'a; +type Stage<'a> = dyn FnMut(Vec, usize) -> Result<(), JsonFlattenError> + 'a; /// Rows handed over, and the most rows a chunk held #[derive(Debug, Default)] @@ -76,7 +76,7 @@ fn hand_over( ) -> (Result, Allocated) { let (result, allocated) = measure(|| { let mut handed = Handed::default(); - let mut stage = |rows: Vec| { + let mut stage = |rows: Vec, _bytes: usize| { handed.rows += rows.len(); handed.largest_chunk = handed.largest_chunk.max(rows.len()); Ok(()) @@ -528,23 +528,15 @@ fn row_estimate_tracks_allocated_memory() { .iter() .map(|row| row_bytes(row.as_object().unwrap())) .sum(); - let sizing = crate::otel::expansion::logs_size(&request.resource_logs); let ratio = allocated.retained as f64 / estimate as f64; println!( - "MEMORY row estimate, {name}: {} rows, allocated {} B, estimated {} B, allocated/estimated {:.2}, sizing pass {} B ({:.2} of estimated)", + "MEMORY row estimate, {name}: {} rows, allocated {} B, estimated {} B, allocated/estimated {:.2}", rows.len(), allocated.retained, estimate, ratio, - sizing.bytes, - sizing.bytes as f64 / estimate as f64 ); assert!((0.5..=2.0).contains(&ratio), "{name}: {ratio:.2}"); - let sizing_ratio = sizing.bytes as f64 / estimate as f64; - assert!( - (0.5..=2.0).contains(&sizing_ratio), - "{name}: {sizing_ratio:.2}" - ); } } @@ -577,7 +569,7 @@ fn resident_memory_of_requests() { std::fs::write("/proc/self/clear_refs", "5").unwrap(); let (before, _) = resident(); let mut rows = 0usize; - let mut stage = |chunk: Vec| { + let mut stage = |chunk: Vec, _bytes: usize| { rows += chunk.len(); Ok::<_, JsonFlattenError>(()) }; diff --git a/src/otel/metrics.rs b/src/otel/metrics.rs index cf9bcc69e..fae8e88c7 100644 --- a/src/otel/metrics.rs +++ b/src/otel/metrics.rs @@ -1706,13 +1706,9 @@ mod tests { ExportMetricsServiceRequest { resource_metrics } } - /// What ingestion does with a decoded request before staging: the sizing - /// pass, then the rows handed over in chunks (collected here) + /// What ingestion does with a decoded request: its rows handed over in + /// chunks (collected here) fn flatten(request: &ExportMetricsServiceRequest) -> Vec { - std::hint::black_box(crate::otel::expansion::metrics_size( - &request.resource_metrics, - false, - )); bench::chunked(|chunker| { super::super::flatten_metrics_into(&request.resource_metrics, false, chunker) }) diff --git a/src/otel/protobuf_stream.rs b/src/otel/protobuf_stream.rs index fe62d7ec7..ee249651f 100644 --- a/src/otel/protobuf_stream.rs +++ b/src/otel/protobuf_stream.rs @@ -19,18 +19,29 @@ //! Decodes an OTLP/HTTP protobuf export request one leaf record (`LogRecord`, //! `Span`, `Metric`) at a time, instead of decoding the whole request first. //! -//! The request, resource and scope levels are messages of their own here, which -//! prost drives exactly as it drives the generated ones: the same keys, wire type -//! checks, recursion limit, unknown-field skipping and error messages (each error -//! gets the `Message.field` path the generated code would push). Their fields are -//! merged as prost merges them, so a singular field that occurs more than once -//! (`resource`, `scope`, `schema_url`) ends up as whole-request decoding leaves it, -//! whatever the field order. The repeated children of a level are not decoded -//! where they occur: their bytes are kept (`Bytes`, so not copied) with the decode -//! context prost would use for them, and decoded once the level is read whole, one -//! at a time. A leaf record is decoded by `prost::encoding::message::merge`, as -//! whole-request decoding decodes it, once its decoded size is known to be under -//! a cap ([`max_record_bytes`]). +//! The request, resource and scope levels are walked as prost walks them: the same +//! keys, wire type checks, recursion limit, unknown-field skipping and error +//! messages (each error gets the `Message.field` path the generated code would +//! push). A resource or scope level is read twice over its own bytes: first its +//! singular fields (`resource`, `scope`, `schema_url`) are merged as prost merges +//! them, so a field that occurs more than once ends up as whole-request decoding +//! leaves it whatever the field order, while its children are only stepped over; +//! then its children are visited in order. A child is decoded from the rest of the +//! body with the decode context prost would use for it where it occurs, so it fails +//! exactly as it fails in place. +//! +//! A request is read in two walks. [`outline`] walks only the levels above the +//! records and counts the records without decoding one, so a body whose framing +//! is broken there is refused before anything is staged. [`flatten_request`] then +//! walks it again and decodes every leaf record once, with +//! `prost::encoding::message::merge` as whole-request decoding decodes it, hands +//! its rows to the sink and drops it. A record whose decoded size could be over +//! [`max_record_bytes`] is measured first, and refused without being decoded when +//! it is over. + +use std::convert::Infallible; +use std::ops::Range; +use std::sync::atomic::{AtomicBool, Ordering}; use bytes::{Buf, Bytes}; use opentelemetry_proto::tonic::common::v1::InstrumentationScope; @@ -39,18 +50,13 @@ use opentelemetry_proto::tonic::metrics::v1::Metric; use opentelemetry_proto::tonic::resource::v1::Resource; use opentelemetry_proto::tonic::trace::v1::Span; use prost::encoding::{ - DecodeContext, WireType, check_wire_type, decode_varint, message, skip_field, string, + DecodeContext, WireType, check_wire_type, decode_key, decode_varint, message, skip_field, + string, }; use prost::{DecodeError, Message}; - -use std::convert::Infallible; -use std::marker::PhantomData; -use std::sync::atomic::{AtomicBool, Ordering}; - use serde_json::Map; -use super::decoded_size::{Leaf, leaf_decoded_size}; -use super::expansion::{LogsSizer, MetricsSizer, RequestSize, TracesSizer}; +use super::decoded_size::{Leaf, leaf_decoded_size, metric_points, needs_measuring}; use super::logs::{log_record_row, resource_log_fields, scope_log_fields}; use super::metrics::{ResourceMetricFields, metric_rows_into}; use super::sink::RowSink; @@ -87,16 +93,11 @@ impl StreamError { } } -/// What a request is made of, in the order its records are read -pub enum Item { - /// A resource level starts: its `resource` and `schema_url` - Resource(Option, String), - /// A scope level of the current resource starts - Scope(Option, String), - /// A leaf record of the current scope - Record(L), - /// The current resource level ends - ResourceEnd, +impl StreamError { + /// The same error, as one of a consumer of any type + pub fn widen(self) -> StreamError { + self.map_consumer(|never| match never {}) + } } /// The names prost's error messages use for the levels of one signal @@ -136,6 +137,24 @@ pub const METRICS: Names = Names { records: "metrics", }; +/// The signal of a protobuf body +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Signal { + Logs, + Metrics, + Traces, +} + +impl Signal { + fn names(self) -> &'static Names { + match self { + Self::Logs => &LOGS, + Self::Metrics => &METRICS, + Self::Traces => &TRACES, + } + } +} + /// A leaf record type and how it is measured pub trait LeafRecord: Message + Default { const LEAF: Leaf; @@ -153,10 +172,11 @@ impl LeafRecord for Metric { const LEAF: Leaf = Leaf::Metric; } -/// A length-delimited child kept for later: where it starts in the body (at its -/// length prefix) and the context prost would decode it with there. It is decoded -/// from the rest of the body, as prost decodes it: a broken length inside it can -/// run past its end before decoding fails, and fails the way it fails in place. +/// A length-delimited child: where it starts in the body (at its length prefix) +/// and the context prost would decode it with there. It is decoded from the rest +/// of the body, as prost decodes it: a broken length inside it can run past its end +/// before decoding fails, and fails the way it fails in place. +#[derive(Clone)] struct Child { start: usize, prefix: usize, @@ -165,16 +185,16 @@ struct Child { } impl Child { - /// Steps over the child at the front of `buf` (the end of a body of `body_len` - /// bytes), failing like prost's `message::merge_repeated` on its framing + /// Steps over the child at the front of `buf`, which ends at `end` in the body, + /// failing like prost's `message::merge_repeated` on its framing fn take( wire_type: WireType, buf: &mut impl Buf, - body_len: usize, + end: usize, ctx: DecodeContext, ) -> Result { check_wire_type(WireType::LengthDelimited, wire_type)?; - let start = body_len - buf.remaining(); + let start = end - buf.remaining(); let mut peek = buf.chunk(); let contiguous = peek.len(); let len = decode_varint(&mut peek)?; @@ -192,18 +212,23 @@ impl Child { } /// Decodes the child into `msg`, as prost decodes it where it occurs - fn merge(self, body: &Bytes, msg: &mut M) -> Result<(), DecodeError> { + fn merge(&self, body: &Bytes, msg: &mut M) -> Result<(), DecodeError> { message::merge( WireType::LengthDelimited, msg, &mut body.slice(self.start..), - self.ctx, + self.ctx.clone(), ) } + /// Where the encoding of the child, without its length prefix, is in the body + fn content(&self) -> Range { + self.start + self.prefix..self.start + self.prefix + self.len + } + /// The encoding of the child, without its length prefix fn body<'b>(&self, body: &'b [u8]) -> &'b [u8] { - &body[self.start + self.prefix..self.start + self.prefix + self.len] + &body[self.content()] } } @@ -212,75 +237,36 @@ fn push(mut error: DecodeError, message: &'static str, field: &'static str) -> D error } -/// The request level: the resource levels, kept -struct RequestLevel { - names: &'static Names, - body_len: usize, - children: Vec, -} - -impl Message for RequestLevel { - fn encode_raw(&self, _buf: &mut impl bytes::BufMut) { - unreachable!("only decoded") - } - - fn merge_field( - &mut self, - tag: u32, - wire_type: WireType, - buf: &mut impl Buf, - ctx: DecodeContext, - ) -> Result<(), DecodeError> { - if tag == 1 { - let child = Child::take(wire_type, buf, self.body_len, ctx) - .map_err(|e| push(e, self.names.request, self.names.resources))?; - self.children.push(child); - Ok(()) - } else { - skip_field(wire_type, tag, buf, ctx) - } - } - - fn encoded_len(&self) -> usize { - 0 - } - - fn clear(&mut self) { - self.children.clear(); - } -} - -/// A resource or scope level: its singular fields, merged, and its children, kept -struct Level

{ - body_len: usize, +/// The singular fields of a resource or scope level, merged as prost merges them. +/// Its children (field 2) are only stepped over, which checks their framing. +struct Fields

{ message: &'static str, parent_field: &'static str, children_field: &'static str, parent: Option

, schema_url: String, - children: Vec, + /// The context prost decodes the fields of the level with, once it has one + ctx: Option, } -impl

Level

{ +impl

Fields

{ fn new( - body_len: usize, message: &'static str, parent_field: &'static str, children_field: &'static str, ) -> Self { Self { - body_len, message, parent_field, children_field, parent: None, schema_url: String::new(), - children: Vec::new(), + ctx: None, } } } -impl Message for Level

{ +impl Message for Fields

{ fn encode_raw(&self, _buf: &mut impl bytes::BufMut) { unreachable!("only decoded") } @@ -292,6 +278,9 @@ impl Message for Level

{ buf: &mut impl Buf, ctx: DecodeContext, ) -> Result<(), DecodeError> { + if self.ctx.is_none() { + self.ctx = Some(ctx.clone()); + } match tag { 1 => message::merge( wire_type, @@ -301,10 +290,11 @@ impl Message for Level

{ ) .map_err(|e| push(e, self.message, self.parent_field)), 2 => { - let child = Child::take(wire_type, buf, self.body_len, ctx) - .map_err(|e| push(e, self.message, self.children_field))?; - self.children.push(child); - Ok(()) + // Only the framing; `Child::take` needs no position for that + let end = buf.remaining(); + Child::take(wire_type, buf, end, ctx) + .map(drop) + .map_err(|e| push(e, self.message, self.children_field)) } 3 => string::merge(wire_type, &mut self.schema_url, buf, ctx) .map_err(|e| push(e, self.message, "schema_url")), @@ -319,192 +309,200 @@ impl Message for Level

{ fn clear(&mut self) { self.parent = None; self.schema_url.clear(); - self.children.clear(); } } -/// Reads the request `body` of the signal `names` belongs to and hands its items to -/// `consume` in order, one leaf record at a time. Records whose decoded size is over -/// `max_record` are refused before they are decoded. -pub fn read_request( - body: Bytes, - names: &'static Names, - max_record: usize, - mut consume: impl FnMut(Item) -> Result<(), E>, +/// Hands every child (fields numbered `tag`) of the level whose fields are +/// `body[range]` to `visit`, in order, stepping over its other fields as prost +/// does. `ctx` is the context prost decodes the fields of the level with; `path` +/// adds the field of the children to a framing error. +fn children( + body: &Bytes, + range: Range, + ctx: &DecodeContext, + tag: u32, + path: impl Fn(DecodeError) -> DecodeError, + visit: &mut dyn FnMut(Child) -> Result<(), StreamError>, ) -> Result<(), StreamError> { - let body_len = body.len(); - let mut request = RequestLevel { - names, - body_len, - children: Vec::new(), - }; - request.merge(body.clone()).map_err(StreamError::Decode)?; - for resource_child in request.children { - let mut resource = - Level::::new(body_len, names.resource_level, "resource", names.scopes); - resource_child - .merge(&body, &mut resource) - .map_err(|e| StreamError::Decode(push(e, names.request, names.resources)))?; - consume(Item::Resource(resource.parent, resource.schema_url)) - .map_err(StreamError::Consumer)?; - for scope_child in resource.children { - let in_resource = |e| { - let e = push(e, names.resource_level, names.scopes); - StreamError::Decode(push(e, names.request, names.resources)) - }; - let mut scope = Level::::new( - body_len, - names.scope_level, - "scope", - names.records, - ); - scope_child.merge(&body, &mut scope).map_err(in_resource)?; - consume(Item::Scope(scope.parent, scope.schema_url)).map_err(StreamError::Consumer)?; - for record_child in scope.children { - if leaf_decoded_size(record_child.body(&body), L::LEAF) > max_record { - return Err(StreamError::RecordTooLarge { - leaf: L::LEAF, - limit: max_record, - }); - } - let mut record = L::default(); - record_child - .merge(&body, &mut record) - .map_err(|e| in_resource(push(e, names.scope_level, names.records)))?; - consume(Item::Record(record)).map_err(StreamError::Consumer)?; - } + let end = range.end; + let mut buf = &body[range]; + while buf.has_remaining() { + let (field, wire_type) = decode_key(&mut buf).map_err(StreamError::Decode)?; + if field == tag { + let child = Child::take(wire_type, &mut buf, end, ctx.clone()) + .map_err(|e| StreamError::Decode(path(e)))?; + visit(child)?; + } else { + skip_field(wire_type, field, &mut buf, ctx.clone()).map_err(StreamError::Decode)?; } - consume(Item::ResourceEnd).map_err(StreamError::Consumer)?; } Ok(()) } -/// Reads only the request level of `body`: the framing of its resource levels and -/// its unknown fields. Needs no limit, so a body that is not a request of the signal -/// at all can be refused before anything else is looked at. On an error, reports -/// the one whole-request decoding gives (`first_error`, here without a cap on the -/// records it decodes on the way, one at a time). -pub fn check_request_level(body: Bytes, signal: Signal) -> Result<(), StreamError> { - let names = signal.names(); - let mut request = RequestLevel { - names, - body_len: body.len(), - children: Vec::new(), - }; - match request.merge(body.clone()) { - Ok(()) => Ok(()), - Err(error) => Err(match signal { - Signal::Logs => first_error::(body, names, usize::MAX), - Signal::Traces => first_error::(body, names, usize::MAX), - Signal::Metrics => first_error::(body, names, usize::MAX), - } - .unwrap_or(StreamError::Decode(error))), - } +/// What a request is made of, in the order of the body +enum Item { + /// A resource level starts: its `resource` and `schema_url` + Resource(Option, String), + /// A scope level of the current resource starts + Scope(Option, String), + /// A leaf record of the current scope, not decoded + Record(Child), + /// The current resource level ends + ResourceEnd, } -/// The signal of a protobuf body -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Signal { - Logs, - Metrics, - Traces, +/// Walks the levels of the request `body` above its leaf records and hands their +/// items to `consume`, in order. Fails with prost's error where one of those levels +/// is broken (a record is only stepped over, so its framing is checked but not its +/// content), or with the first refusal of `consume`. +fn walk( + body: &Bytes, + names: &'static Names, + consume: &mut dyn FnMut(Item) -> Result<(), StreamError>, +) -> Result<(), StreamError> { + let in_request = |e| push(e, names.request, names.resources); + let in_resource = |e| in_request(push(e, names.resource_level, names.scopes)); + let in_scope = |e| in_resource(push(e, names.scope_level, names.records)); + // `Message::merge` decodes the fields of a request with the default context + let top = DecodeContext::default(); + children(body, 0..body.len(), &top, 1, in_request, &mut |resource| { + let mut level = Fields::::new(names.resource_level, "resource", names.scopes); + resource + .merge(body, &mut level) + .map_err(|e| StreamError::Decode(in_request(e)))?; + consume(Item::Resource( + level.parent.take(), + std::mem::take(&mut level.schema_url), + ))?; + if let Some(ctx) = &level.ctx { + children( + body, + resource.content(), + ctx, + 2, + in_resource, + &mut |scope| { + let mut level = Fields::::new( + names.scope_level, + "scope", + names.records, + ); + scope + .merge(body, &mut level) + .map_err(|e| StreamError::Decode(in_resource(e)))?; + consume(Item::Scope( + level.parent.take(), + std::mem::take(&mut level.schema_url), + ))?; + match &level.ctx { + Some(ctx) => { + children(body, scope.content(), ctx, 2, in_scope, &mut |record| { + consume(Item::Record(record)) + }) + } + None => Ok(()), + } + }, + )?; + } + consume(Item::ResourceEnd) + }) } -impl Signal { - fn names(self) -> &'static Names { - match self { - Self::Logs => &LOGS, - Self::Metrics => &METRICS, - Self::Traces => &TRACES, - } - } +/// What [`outline`] found in a request +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct Outline { + /// Leaf records (log records, spans or metrics) of the request + pub records: u64, } -/// Rows, row bytes, records and data points of the request `body`, read one record -/// at a time (the sizing pass of the expansion cap, see `expansion`) -pub fn size_request( - body: Bytes, - signal: Signal, - max_record: usize, - flatten_exemplars: bool, -) -> Result> { - size_in_levels(body.clone(), signal, max_record, flatten_exemplars).map_err(|error| { - match error { - // Report the break whole-request decoding meets first - StreamError::Decode(_) => match signal { - Signal::Logs => first_error::(body, &LOGS, max_record), - Signal::Traces => first_error::(body, &TRACES, max_record), - Signal::Metrics => first_error::(body, &METRICS, max_record), - } - .unwrap_or(error), - error => error, +/// Reads the levels of the request `body` above its leaf records, without decoding +/// a record, and counts the records. Needs no limit, so a body that is not a +/// request of the signal at all is refused before anything else is looked at. +/// The error is the first break met in those levels; [`refusal`] turns it into +/// the error whole-request decoding gives. +pub fn outline(body: &Bytes, signal: Signal) -> Result { + let mut outline = Outline::default(); + walk::(body, signal.names(), &mut |item| { + if let Item::Record(_) = item { + outline.records += 1; } + Ok(()) }) + .map_err(|error| match error { + StreamError::Decode(error) => error, + StreamError::RecordTooLarge { .. } => unreachable!("no record is measured"), + StreamError::Consumer(never) => match never {}, + })?; + Ok(outline) } -fn size_in_levels( - body: Bytes, +/// The error to refuse a body with that [`outline`] found broken (`error`): the one +/// whole-request decoding gives, found by decoding the body in wire order one record +/// at a time (`first_error`), or a record over the cap met before the break. +/// `max_record` is asked for only once a record is met, so a body that is not a +/// request is refused without it. +pub fn refusal( + body: &Bytes, signal: Signal, + error: DecodeError, + max_record: impl FnOnce() -> usize, +) -> StreamError { + let found = match first_error(body, signal, None) { + FirstError::NeedsCap => first_error(body, signal, Some(max_record())), + found => found, + }; + match found { + FirstError::Found(found) => found, + // Not reached: a body broken above its records does not decode + FirstError::None | FirstError::NeedsCap => StreamError::Decode(error), + } +} + +/// Decodes the leaf record `child` of `body`, refusing it before it is decoded if +/// it would take more than `max_record` bytes +fn decode_leaf( + body: &Bytes, + child: &Child, + names: &'static Names, max_record: usize, - flatten_exemplars: bool, -) -> Result> { - match signal { - Signal::Logs => { - let mut sizer = LogsSizer::default(); - read_request::(body, &LOGS, max_record, |item| { - match item { - Item::Resource(resource, url) => sizer.resource(resource.as_ref(), &url), - Item::Scope(scope, url) => sizer.scope(scope.as_ref(), &url), - Item::Record(record) => sizer.record(&record), - Item::ResourceEnd => {} - } - Ok(()) - })?; - Ok(sizer.finish()) - } - Signal::Traces => { - let mut sizer = TracesSizer::default(); - read_request::(body, &TRACES, max_record, |item| { - match item { - Item::Resource(resource, url) => sizer.resource(resource.as_ref(), &url), - Item::Scope(scope, url) => sizer.scope(scope.as_ref(), &url), - Item::Record(span) => sizer.span(&span), - Item::ResourceEnd => {} - } - Ok(()) - })?; - Ok(sizer.finish()) - } - Signal::Metrics => { - let mut sizer = MetricsSizer::new(flatten_exemplars); - read_request::(body, &METRICS, max_record, |item| { - match item { - Item::Resource(resource, url) => sizer.resource(resource.as_ref(), &url), - Item::Scope(scope, url) => sizer.scope(scope.as_ref(), &url), - Item::Record(metric) => sizer.metric(&metric), - Item::ResourceEnd => sizer.resource_end(), - } - Ok(()) - })?; - Ok(sizer.finish()) - } +) -> Result> { + let encoded = child.body(body); + if needs_measuring(encoded.len(), L::LEAF, max_record) + && leaf_decoded_size(encoded, L::LEAF) > max_record + { + return Err(StreamError::RecordTooLarge { + leaf: L::LEAF, + limit: max_record, + }); } + let mut record = L::default(); + child.merge(body, &mut record).map_err(|e| { + let e = push(e, names.scope_level, names.records); + let e = push(e, names.resource_level, names.scopes); + StreamError::Decode(push(e, names.request, names.resources)) + })?; + Ok(record) } /// Hands the rows of the request `body` to `sink`, decoding one record at a time: -/// the same rows, in the same order, as decoding the whole request and flattening it +/// the same rows, in the same order, as decoding the whole request and flattening +/// it. `body` must have passed [`outline`]; then the only errors are those of a +/// record (it does not decode, or is over `max_record`) and refusals of `sink`, +/// and the rows of every record before it were handed over. pub fn flatten_request( - body: Bytes, + body: &Bytes, signal: Signal, max_record: usize, budget: &mut FlattenBudget, flatten_exemplars: bool, sink: &mut S, ) -> Result<(), StreamError> { + let names = signal.names(); match signal { Signal::Logs => { let (mut resource_fields, mut scope_fields) = (Map::new(), Map::new()); - read_request::(body, &LOGS, max_record, |item| { + walk(body, names, &mut |item| { match item { Item::Resource(resource, url) => { resource_fields = resource_log_fields(resource.as_ref(), &url) @@ -512,13 +510,11 @@ pub fn flatten_request( Item::Scope(scope, url) => { scope_fields = scope_log_fields(scope.as_ref(), &url) } - Item::Record(record) => { - sink.row(log_record_row( - &record, - &scope_fields, - &resource_fields, - budget, - )?)?; + Item::Record(child) => { + let record: LogRecord = decode_leaf(body, &child, names, max_record)?; + let row = log_record_row(&record, &scope_fields, &resource_fields, budget) + .map_err(|e| StreamError::Consumer(e.into()))?; + sink.row(row).map_err(StreamError::Consumer)?; sink.record_end(); } Item::ResourceEnd => {} @@ -529,7 +525,7 @@ pub fn flatten_request( Signal::Traces => { let (mut resource_fields, mut scope_fields) = (Map::new(), Map::new()); let mut scope_url = String::new(); - read_request::(body, &TRACES, max_record, |item| { + walk(body, names, &mut |item| { match item { Item::Resource(resource, url) => { resource_fields = resource_span_fields(resource.as_ref(), &url) @@ -538,15 +534,19 @@ pub fn flatten_request( scope_fields = scope_span_fields(scope.as_ref()); scope_url = url; } - Item::Record(span) => span_rows( - &span, - &SpanParents { - scope_fields: &scope_fields, - scope_schema_url: &scope_url, - resource_fields: &resource_fields, - }, - sink, - )?, + Item::Record(child) => { + let span: Span = decode_leaf(body, &child, names, max_record)?; + span_rows( + &span, + &SpanParents { + scope_fields: &scope_fields, + scope_schema_url: &scope_url, + resource_fields: &resource_fields, + }, + sink, + ) + .map_err(StreamError::Consumer)? + } Item::ResourceEnd => {} } Ok(()) @@ -556,7 +556,7 @@ pub fn flatten_request( let mut resource: Option = None; let mut envelope = Map::new(); let mut latest: Option = None; - read_request::(body, &METRICS, max_record, |item| { + walk(body, names, &mut |item| { match item { Item::Resource(r, url) => { resource = Some(ResourceMetricFields::new(r.as_ref(), &url)); @@ -568,15 +568,17 @@ pub fn flatten_request( .expect("a scope is inside a resource") .scope_envelope(scope.as_ref(), &url); } - Item::Record(metric) => { - metric_rows_into(&metric, &envelope, flatten_exemplars, &mut latest, sink)? + Item::Record(child) => { + let metric: Metric = decode_leaf(body, &child, names, max_record)?; + metric_rows_into(&metric, &envelope, flatten_exemplars, &mut latest, sink) + .map_err(StreamError::Consumer)? } Item::ResourceEnd => { if let Some(target) = resource .take() .and_then(|resource| resource.target_info(latest.take())) { - sink.row(target)?; + sink.row(target).map_err(StreamError::Consumer)?; } } } @@ -586,29 +588,57 @@ pub fn flatten_request( } } +/// Data points of the metrics request `body`, counted from the wire without +/// decoding a metric (see `metric_points`). For the rejected count of a partial +/// success, so only read after a failure. `body` must have passed [`outline`]. +pub fn count_points(body: &Bytes) -> u64 { + let mut points = 0u64; + let _ = walk::(body, &METRICS, &mut |item| { + if let Item::Record(child) = item { + points += metric_points(child.body(body)); + } + Ok(()) + }); + points +} + /// One level of `first_error`'s walk: decodes everything in wire order, as prost /// does, keeping nothing but one record at a time -struct WireOrder<'a, L> { +struct WireOrder<'a> { names: &'static Names, + leaf: Leaf, depth: u8, - max_record: usize, - oversized: &'a AtomicBool, - leaf: PhantomData L>, + /// `None` until the cap on one record is known: the walk stops at the first record + max_record: Option, + stopped: &'a AtomicBool, } -impl WireOrder<'_, L> { - fn child(&self) -> WireOrder<'_, L> { +impl WireOrder<'_> { + fn child(&self) -> WireOrder<'_> { WireOrder { names: self.names, + leaf: self.leaf, depth: self.depth + 1, max_record: self.max_record, - oversized: self.oversized, - leaf: PhantomData, + stopped: self.stopped, + } + } + + fn merge_leaf( + &self, + wire_type: WireType, + buf: &mut impl Buf, + ctx: DecodeContext, + ) -> Result<(), DecodeError> { + match self.leaf { + Leaf::LogRecord => message::merge(wire_type, &mut LogRecord::default(), buf, ctx), + Leaf::Span => message::merge(wire_type, &mut Span::default(), buf, ctx), + Leaf::Metric => message::merge(wire_type, &mut Metric::default(), buf, ctx), } } } -impl Message for WireOrder<'_, L> { +impl Message for WireOrder<'_> { fn encode_raw(&self, _buf: &mut impl bytes::BufMut) { unreachable!("only decoded") } @@ -631,17 +661,22 @@ impl Message for WireOrder<'_, L> { (2, 1) => message::merge(wire_type, &mut InstrumentationScope::default(), buf, ctx) .map_err(|e| push(e, names.scope_level, "scope")), (2, 2) => { + let Some(max_record) = self.max_record else { + self.stopped.store(true, Ordering::Relaxed); + return Err(DecodeError::new("stopped at the first record")); + }; // Measured where the framing allows, then decoded in place let mut peek = buf.chunk(); if wire_type == WireType::LengthDelimited && let Ok(len) = decode_varint(&mut peek) && len <= peek.len() as u64 - && leaf_decoded_size(&peek[..len as usize], L::LEAF) > self.max_record + && needs_measuring(len as usize, self.leaf, max_record) + && leaf_decoded_size(&peek[..len as usize], self.leaf) > max_record { - self.oversized.store(true, Ordering::Relaxed); + self.stopped.store(true, Ordering::Relaxed); return Err(DecodeError::new("record over the decoded size cap")); } - message::merge(wire_type, &mut L::default(), buf, ctx) + self.merge_leaf(wire_type, buf, ctx) .map_err(|e| push(e, names.scope_level, names.records)) } (1 | 2, 3) => { @@ -664,31 +699,39 @@ impl Message for WireOrder<'_, L> { fn clear(&mut self) {} } +/// What `first_error` found +enum FirstError { + /// The error whole-request decoding gives, or a record over the cap before it + Found(StreamError), + /// The walk met a record and needs the cap on one record to go on + NeedsCap, + /// The body decodes + None, +} + /// The error whole-request decoding gives for `body`, found by decoding it in wire -/// order one record at a time (`read_request` reads each level whole before its -/// children, so where a body is broken in more than one place it can meet another -/// break first). `None` when the body decodes. -pub fn first_error( - body: Bytes, - names: &'static Names, - max_record: usize, -) -> Option> { - let oversized = AtomicBool::new(false); - let mut walk = WireOrder:: { - names, +/// order one record at a time (`walk` reads each level whole before its children, +/// so where a body is broken in more than one place it can meet another break first) +fn first_error(body: &Bytes, signal: Signal, max_record: Option) -> FirstError { + let stopped = AtomicBool::new(false); + let leaf = match signal { + Signal::Logs => Leaf::LogRecord, + Signal::Traces => Leaf::Span, + Signal::Metrics => Leaf::Metric, + }; + let mut walk = WireOrder { + names: signal.names(), + leaf, depth: 0, max_record, - oversized: &oversized, - leaf: PhantomData, + stopped: &stopped, }; - walk.merge(body).err().map(|error| { - if oversized.load(Ordering::Relaxed) { - StreamError::RecordTooLarge { - leaf: L::LEAF, - limit: max_record, - } - } else { - StreamError::Decode(error) - } - }) + match walk.merge(body.clone()) { + Ok(()) => FirstError::None, + Err(_) if stopped.load(Ordering::Relaxed) => match max_record { + None => FirstError::NeedsCap, + Some(limit) => FirstError::Found(StreamError::RecordTooLarge { leaf, limit }), + }, + Err(error) => FirstError::Found(StreamError::Decode(error)), + } } diff --git a/src/otel/realistic_tests.rs b/src/otel/realistic_tests.rs index c0522621d..bea44775a 100644 --- a/src/otel/realistic_tests.rs +++ b/src/otel/realistic_tests.rs @@ -17,7 +17,8 @@ */ //! Requests shaped like real collector traffic, at the default payload limit: -//! what they expand to per body byte (the numbers behind `EXPANSION_FACTOR`), +//! what their rows hold per body byte (`row_bytes`, the unit of the running total +//! the expansion cap counts while staging; the numbers behind `EXPANSION_FACTOR`), //! and that the expansion cap accepts every one of them. Nothing here touches //! `PARSEABLE`. `OTLP_DUMP_DIR=

` makes the ignored `dump_realistic_bodies` //! write the bodies for end-to-end checks against a server. @@ -36,7 +37,11 @@ use opentelemetry_proto::tonic::resource::v1::Resource; use opentelemetry_proto::tonic::trace::v1::{ResourceSpans, ScopeSpans, Span, Status, span}; use prost::Message; -use super::expansion::{RequestSize, logs_size, max_expanded_bytes, metrics_size, traces_size}; +use serde_json::{Map, Value}; + +use super::protobuf_stream::{Signal, flatten_request, max_record_bytes, outline}; +use super::sink::{RowSink, max_expanded_bytes, row_bytes}; +use crate::utils::json::flatten::{FlattenBudget, FlattenLimits, JsonFlattenError}; /// `P_MAX_EVENT_PAYLOAD_SIZE` default const PAYLOAD: usize = 10 * 1024 * 1024; @@ -365,7 +370,58 @@ pub(crate) struct Shape { pub name: &'static str, pub signal: &'static str, pub body: Vec, - pub size: RequestSize, +} + +/// What the rows of a request add up to, as staging counts them +#[derive(Debug, Default, Clone, Copy)] +pub(crate) struct Totals { + pub rows: u64, + /// `row_bytes` of every row: what the expansion cap counts + pub bytes: u64, + pub records: u64, + pub points: u64, +} + +impl RowSink for Totals { + type Error = JsonFlattenError; + + fn row(&mut self, row: Map) -> Result<(), Self::Error> { + self.rows += 1; + self.bytes += row_bytes(&row) as u64; + Ok(()) + } + + fn point(&mut self, row: Map) -> Result<(), Self::Error> { + self.points += 1; + self.row(row) + } + + fn record_end(&mut self) { + self.records += 1; + } +} + +/// The totals of the protobuf `body` of `signal`, read as ingestion reads it +pub(crate) fn totals(signal: &str, body: &[u8]) -> Totals { + let signal = match signal { + "logs" => Signal::Logs, + "traces" => Signal::Traces, + "metrics" => Signal::Metrics, + other => panic!("{other}"), + }; + let body = bytes::Bytes::copy_from_slice(body); + outline(&body, signal).unwrap(); + let mut totals = Totals::default(); + flatten_request( + &body, + signal, + max_record_bytes(PAYLOAD), + &mut FlattenBudget::new(FlattenLimits::DEFAULT), + false, + &mut totals, + ) + .unwrap(); + totals } /// Records of `one` bytes each that fit in `PAYLOAD`, with room for framing @@ -377,7 +433,6 @@ fn shape( name: &'static str, signal: &'static str, build: impl Fn(usize) -> M, - size: impl Fn(&M) -> RequestSize, ) -> Shape { let probe = build(1000).encoded_len(); let mut n = fitting(probe.div_ceil(1000)); @@ -388,132 +443,102 @@ fn shape( request = build(n); } let body = request.encode_to_vec(); - let size = size(&request); - Shape { - name, - signal, - body, - size, - } + Shape { name, signal, body } } pub(crate) fn shapes() -> Vec { - let logs_size = |r: &ExportLogsServiceRequest| logs_size(&r.resource_logs); - let traces_size = |r: &ExportTraceServiceRequest| traces_size(&r.resource_spans); - let metrics_size = |r: &ExportMetricsServiceRequest| metrics_size(&r.resource_metrics, false); vec![ - shape( - "logs, 30 k8s resource attributes", - "logs", - |n| logs(k8s_resource(), (0..n).map(app_log).collect()), - logs_size, - ), - shape( - "logs, service.name only", - "logs", - |n| logs(minimal_resource(), (0..n).map(app_log).collect()), - logs_size, - ), + shape("logs, 30 k8s resource attributes", "logs", |n| { + logs(k8s_resource(), (0..n).map(app_log).collect()) + }), + shape("logs, service.name only", "logs", |n| { + logs(minimal_resource(), (0..n).map(app_log).collect()) + }), shape( "logs, short records (time, severity, body \"ok\")", "logs", |n| logs(None, (0..n).map(short_log).collect()), - logs_size, ), shape( "logs, short records, 30 k8s resource attributes", "logs", |n| logs(k8s_resource(), (0..n).map(short_log).collect()), - logs_size, - ), - shape( - "traces, 30 k8s resource attributes", - "traces", - |n| traces(k8s_resource(), (0..n).map(server_span).collect()), - traces_size, - ), - shape( - "traces, service.name only", - "traces", - |n| traces(minimal_resource(), (0..n).map(server_span).collect()), - traces_size, - ), - shape( - "traces, bare spans (ids, name, times)", - "traces", - |n| traces(minimal_resource(), (0..n).map(bare_span).collect()), - traces_size, ), + shape("traces, 30 k8s resource attributes", "traces", |n| { + traces(k8s_resource(), (0..n).map(server_span).collect()) + }), + shape("traces, service.name only", "traces", |n| { + traces(minimal_resource(), (0..n).map(server_span).collect()) + }), + shape("traces, bare spans (ids, name, times)", "traces", |n| { + traces(minimal_resource(), (0..n).map(bare_span).collect()) + }), shape( "traces, bare spans, 30 k8s resource attributes", "traces", |n| traces(k8s_resource(), (0..n).map(bare_span).collect()), - traces_size, - ), - shape( - "traces, an event and a link per span, k8s", - "traces", - |n| traces(k8s_resource(), (0..n).map(span_with_event).collect()), - traces_size, ), + shape("traces, an event and a link per span, k8s", "traces", |n| { + traces(k8s_resource(), (0..n).map(span_with_event).collect()) + }), shape( "metrics, sum points, 30 k8s resource attributes", "metrics", |n| metrics(k8s_resource(), sum_points(n)), - metrics_size, - ), - shape( - "metrics, sum points, service.name only", - "metrics", - |n| metrics(minimal_resource(), sum_points(n)), - metrics_size, - ), - shape( - "metrics, bare gauge points (time, value)", - "metrics", - |n| metrics(minimal_resource(), bare_gauge_points(n)), - metrics_size, ), + shape("metrics, sum points, service.name only", "metrics", |n| { + metrics(minimal_resource(), sum_points(n)) + }), + shape("metrics, bare gauge points (time, value)", "metrics", |n| { + metrics(minimal_resource(), bare_gauge_points(n)) + }), shape( "metrics, bare gauge points, 30 k8s resource attributes", "metrics", |n| metrics(k8s_resource(), bare_gauge_points(n)), - metrics_size, ), shape( "metrics, histograms with an exemplar, k8s", "metrics", |n| metrics(k8s_resource(), histogram_points(n)), - metrics_size, ), shape( "metrics, exponential histograms, 160 buckets", "metrics", |n| metrics(minimal_resource(), exp_histogram_points(n)), - metrics_size, ), ] } -/// Every realistic shape at the payload limit is under the expansion cap +/// Every realistic shape at the payload limit is under the expansion cap, counted +/// as staging counts it: the `row_bytes` of every row #[test] fn realistic_requests_at_the_payload_limit_are_under_the_expansion_cap() { + use rayon::prelude::*; let cap = max_expanded_bytes(PAYLOAD); let mut worst: f64 = 0.0; - for shape in shapes() { - let ratio = shape.size.bytes as f64 / shape.body.len() as f64; + // Flattened at once: a few seconds each in a debug build + let measured: Vec<(Shape, Totals)> = shapes() + .into_par_iter() + .map(|shape| { + let totals = totals(shape.signal, &shape.body); + (shape, totals) + }) + .collect(); + for (shape, totals) in measured { + let ratio = totals.bytes as f64 / shape.body.len() as f64; worst = worst.max(ratio); println!( "EXPANSION {}: body {:.2} MiB, {} records, {} rows, {:.0} row bytes per row, {:.1} row bytes per body byte ({:.0}% of the cap)", shape.name, shape.body.len() as f64 / (1024.0 * 1024.0), - shape.size.records, - shape.size.rows, - shape.size.bytes as f64 / shape.size.rows as f64, + totals.records, + totals.rows, + totals.bytes as f64 / totals.rows as f64, ratio, - 100.0 * shape.size.bytes as f64 / cap as f64 + 100.0 * totals.bytes as f64 / cap as f64 ); - assert!(shape.size.bytes <= cap, "{} is refused", shape.name); + assert!(totals.bytes <= cap, "{} is refused", shape.name); } println!( "EXPANSION worst {worst:.1} row bytes per body byte, cap {} per body byte", @@ -521,27 +546,39 @@ fn realistic_requests_at_the_payload_limit_are_under_the_expansion_cap() { ); } -/// Copied fields that no collector sends: a 15 KB resource over empty records of -/// two bytes each, which expand to tens of GiB of rows, are refused -#[test] -fn copied_fields_over_tiny_records_are_over_the_expansion_cap() { +/// The request that copies a 15 KB resource into empty records of two bytes each: +/// half a MiB of protobuf +fn copied_resource_over_empty_records() -> ExportLogsServiceRequest { let resource = Some(Resource { attributes: (0..500) .map(|i| s(&format!("attribute.{i:03}"), "value-0123456789")) .collect(), ..Default::default() }); - // Half a MiB of protobuf - let records = 1 << 18; - let request = logs(resource, vec![LogRecord::default(); records]); - let size = logs_size(&request.resource_logs); + logs(resource, vec![LogRecord::default(); 1 << 18]) +} + +/// Copied fields that no collector sends: a 15 KB resource over empty records of +/// two bytes each, which expand to tens of GiB of rows, pass the expansion cap. +/// Counted from the rows of the first records (they all hold the same), not by +/// building all of them. +#[test] +fn copied_fields_over_tiny_records_are_over_the_expansion_cap() { + let request = copied_resource_over_empty_records(); + let records = request.resource_logs[0].scope_logs[0].log_records.len() as u64; + let mut first = request.clone(); + first.resource_logs[0].scope_logs[0] + .log_records + .truncate(1000); + let totals = totals("logs", &first.encode_to_vec()); + let bytes = totals.bytes / 1000 * records; println!( - "EXPANSION copied resource: {} records, {:.1} GiB of rows", - size.records, - size.bytes as f64 / (1u64 << 30) as f64 + "EXPANSION copied resource: {records} records, {:.0} row bytes each, {:.1} GiB of rows", + totals.bytes as f64 / 1000.0, + bytes as f64 / (1u64 << 30) as f64 ); assert!(request.encoded_len() <= PAYLOAD); - assert!(size.bytes > max_expanded_bytes(PAYLOAD)); + assert!(bytes > max_expanded_bytes(PAYLOAD)); } /// Writes the body of every shape to `OTLP_DUMP_DIR`, named after its signal @@ -551,14 +588,39 @@ fn copied_fields_over_tiny_records_are_over_the_expansion_cap() { fn dump_realistic_bodies() { let dir = std::env::var("OTLP_DUMP_DIR").expect("OTLP_DUMP_DIR"); let mut index = String::new(); - for (i, shape) in shapes().into_iter().enumerate() { - let file = format!("{i:02}-{}.pb", shape.signal); - std::fs::write(format!("{dir}/{file}"), &shape.body).unwrap(); + let mut write = |file: String, signal: &str, name: &str, body: &[u8]| { + let totals = totals(signal, body); + std::fs::write(format!("{dir}/{file}"), body).unwrap(); index.push_str(&format!( - "{file}\t{}\t{}\t{}\t{}\n", - shape.signal, shape.size.records, shape.size.points, shape.name + "{file}\t{signal}\t{}\t{}\t{name}\n", + totals.records, totals.points )); + }; + for (i, shape) in shapes().into_iter().enumerate() { + let file = format!("{i:02}-{}.pb", shape.signal); + write(file, shape.signal, shape.name, &shape.body); } + // Crafted: one span of 2 million empty events (4 MiB), 400k empty spans (0.8 MB) + let events = traces( + None, + vec![Span { + events: vec![span::Event::default(); 1 << 21], + ..Default::default() + }], + ); + write( + "20-traces.pb".into(), + "traces", + "one span of 2 million empty events", + &events.encode_to_vec(), + ); + let spans = traces(None, vec![Span::default(); 400_000]); + write( + "21-traces.pb".into(), + "traces", + "400k empty spans", + &spans.encode_to_vec(), + ); // Requests of 100 records, as an SDK or a collector with a small batch sends them let small: [(&str, Vec); 3] = [ ( diff --git a/src/otel/sink.rs b/src/otel/sink.rs index 6dcc30149..6773baaa6 100644 --- a/src/otel/sink.rs +++ b/src/otel/sink.rs @@ -158,8 +158,31 @@ pub struct Staged { pub points: u64, } -/// Collects rows into chunks and passes every full chunk to `stage`, dropping it -/// before the next row is taken. Call [`Chunker::finish`] to pass on the rest. +/// Row bytes per payload byte one request may expand to: the rows of a request +/// may hold at most `EXPANSION_FACTOR` times `P_MAX_EVENT_PAYLOAD_SIZE` of +/// estimated memory ([`row_bytes`]) in all, counted while they are staged. +/// +/// Every row carries its own copy of the resource, scope, span and metric fields, +/// so a small request can expand to a very large number of row bytes: 15 KB of +/// resource attributes copied into each of 5 million two-byte log records is tens +/// of GiB. Chunking bounds the memory this takes at once, not what is written to +/// staging. The most measured for a request shaped like collector traffic is +/// below 500 (short log records or bare gauge points under 30 Kubernetes resource +/// attributes; ordinary k8s logs, spans and metrics expand 40-110x, see +/// `realistic_tests`), so 1024 leaves about 2x headroom, and stops the requests +/// that copy kilobytes of shared fields into millions of records of a few bytes, +/// at 10 GiB of rows for the default 10 MiB payload limit. +pub const EXPANSION_FACTOR: u64 = 1024; + +/// Estimated bytes of rows one request may expand to, for a payload limit of +/// `max_payload` bytes +pub fn max_expanded_bytes(max_payload: usize) -> u64 { + (max_payload as u64).saturating_mul(EXPANSION_FACTOR) +} + +/// Collects rows into chunks and passes every full chunk to `stage`, with the +/// estimated bytes of its rows, dropping it before the next row is taken. Call +/// [`Chunker::finish`] to pass on the rest. pub struct Chunker { limits: ChunkLimits, stage: F, @@ -173,7 +196,7 @@ pub struct Chunker { impl Chunker where - F: FnMut(Vec) -> Result<(), E>, + F: FnMut(Vec, usize) -> Result<(), E>, E: From, { pub fn new(limits: ChunkLimits, stage: F) -> Self { @@ -196,8 +219,8 @@ where fn flush(&mut self) -> Result<(), E> { let rows = std::mem::take(&mut self.rows); let count = rows.len() as u64; - self.bytes = 0; - (self.stage)(rows)?; + let bytes = std::mem::take(&mut self.bytes); + (self.stage)(rows, bytes)?; self.staged.chunks += 1; self.staged.rows += count; self.staged.records += std::mem::take(&mut self.pending_records); @@ -216,7 +239,7 @@ where impl RowSink for Chunker where - F: FnMut(Vec) -> Result<(), E>, + F: FnMut(Vec, usize) -> Result<(), E>, E: From, { type Error = E; @@ -277,7 +300,7 @@ mod tests { rows: 3, bytes: usize::MAX, }, - |rows| { + |rows, _| { chunks.push(rows.len()); Ok::<_, JsonFlattenError>(()) }, @@ -302,7 +325,7 @@ mod tests { rows: usize::MAX, bytes: 2 * one, }, - |rows| { + |rows, _| { chunks.push(rows.len()); Ok::<_, JsonFlattenError>(()) }, @@ -323,7 +346,7 @@ mod tests { rows: 2, bytes: usize::MAX, }, - |_| { + |_, _| { fail_at -= 1; if fail_at == 0 { Err(JsonFlattenError::CannotFlatten) @@ -347,7 +370,7 @@ mod tests { #[test] fn records_without_rows_count_when_finished() { - let mut chunker = Chunker::new(CHUNK_LIMITS, |_| Ok::<_, JsonFlattenError>(())); + let mut chunker = Chunker::new(CHUNK_LIMITS, |_, _| Ok::<_, JsonFlattenError>(())); chunker.record_end(); chunker.finish().unwrap(); let staged = chunker.staged(); diff --git a/src/otel/traces.rs b/src/otel/traces.rs index af16bd45f..34e2d9f49 100644 --- a/src/otel/traces.rs +++ b/src/otel/traces.rs @@ -1336,10 +1336,9 @@ mod tests { ExportTraceServiceRequest { resource_spans } } - /// What ingestion does with a decoded request before staging: the sizing - /// pass, then the rows handed over in chunks (collected here) + /// What ingestion does with a decoded request: its rows handed over in + /// chunks (collected here) fn flatten(request: &ExportTraceServiceRequest) -> Vec { - std::hint::black_box(crate::otel::expansion::traces_size(&request.resource_spans)); bench::chunked(|chunker| { super::super::flatten_traces_into(&request.resource_spans, chunker) }) From 9e2b9bd51d0a9e4347a859c68b0f93b7e4b8f3b6 Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Tue, 24 Nov 2026 01:49:18 -0600 Subject: [PATCH 14/31] perf(otel): make the decoded-size scan of large records cheaper Only records long enough to reach the cap are scanned now, but a 10 MiB metric still is, and the scan cost it +1.0 % instructions over stage 1 end to end. One-byte varints (keys, lengths) take a fast path, a string's capacity is computed directly, and a message without a repeated field adds no `Vec`s: the same estimate, +0.64 % for that request. Co-Authored-By: Claude Opus 5.5 --- src/otel/decoded_size.rs | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/src/otel/decoded_size.rs b/src/otel/decoded_size.rs index 4f04ccf3c..ab3685307 100644 --- a/src/otel/decoded_size.rs +++ b/src/otel/decoded_size.rs @@ -308,7 +308,8 @@ fn vec_capacity_bytes(len: usize, element_size: usize) -> usize { /// Bytes prost allocates for a string or bytes field of `len` bytes fn bytes_capacity(len: usize) -> usize { - vec_capacity_bytes(len.min(1), 1).max(len) + // `vec_capacity_bytes(len.min(1), 1).max(len)`: 8 bytes at least, once there is one + if len == 0 { 0 } else { len.max(8) } } /// Counts the elements of the repeated fields of one message, and adds the `Vec`s that @@ -317,15 +318,21 @@ fn bytes_capacity(len: usize) -> usize { struct Vecs { lens: [usize; SLOTS], element_sizes: [usize; SLOTS], + /// Whether any slot was pushed to; most messages have no repeated field + used: bool, } impl Vecs { fn push(&mut self, slot: usize, kind: Kind, elements: usize) { self.lens[slot] = self.lens[slot].saturating_add(elements); self.element_sizes[slot] = kind.element_size(); + self.used = true; } fn add_to(&self, size: &mut usize) { + if !self.used { + return; + } for (&len, &element_size) in self.lens.iter().zip(&self.element_sizes) { add(size, vec_capacity_bytes(len, element_size)); } @@ -467,6 +474,13 @@ const MAX_DEPTH: u32 = 128; struct Malformed; fn varint(buf: &mut &[u8]) -> Result { + // Keys, lengths and small numbers take one byte + if let Some((&byte, rest)) = buf.split_first() + && byte < 0x80 + { + *buf = rest; + return Ok(u64::from(byte)); + } let mut value = 0u64; for (index, &byte) in buf.iter().enumerate().take(10) { value |= u64::from(byte & 0x7f) << (7 * index); From 05a391c2ff22599c3fdf7667047e620a6472d771 Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Tue, 24 Nov 2026 02:38:01 -0600 Subject: [PATCH 15/31] fix(otel): fit shared row maps whose attributes repeat keys Resource, scope, span and metric maps are sized from the attribute count, which counts repeated keys, and IndexMap::clone keeps the capacity. A scope of 128 attributes with one key made every row cloned from it hold 25,956 B while row_bytes counted 2,828 B, and a 1.25 MiB request peaked at 159 MiB. When attributes make fewer entries than were counted, the map is now rebuilt with room for that many fewer; distinct keys rebuild nothing. Co-Authored-By: Claude Opus 5.5 --- src/otel.rs | 2 + src/otel/logs.rs | 14 +- src/otel/metrics.rs | 15 +- src/otel/otel_utils.rs | 25 +++ src/otel/regression_tests.rs | 290 +++++++++++++++++++++++++++++++++++ src/otel/traces.rs | 20 +-- 6 files changed, 343 insertions(+), 23 deletions(-) create mode 100644 src/otel/regression_tests.rs diff --git a/src/otel.rs b/src/otel.rs index 98e47836c..93b8b3864 100644 --- a/src/otel.rs +++ b/src/otel.rs @@ -28,6 +28,8 @@ pub mod traces; mod memory_tests; #[cfg(test)] mod realistic_tests; +#[cfg(test)] +mod regression_tests; /// Shared driver for the release-profile micro-benchmarks. Each benchmark is an /// `#[ignore]`d test that never touches the `PARSEABLE` global, so it can be run diff --git a/src/otel/logs.rs b/src/otel/logs.rs index 3337929d9..a683cc9c3 100644 --- a/src/otel/logs.rs +++ b/src/otel/logs.rs @@ -19,6 +19,7 @@ use super::otel_utils::attribute_capacity; use super::otel_utils::collect_json_from_values; use super::otel_utils::convert_epoch_nano_to_timestamp; use super::otel_utils::insert_attributes; +use super::otel_utils::insert_attributes_fitted; use super::sink::{CHUNK_LIMITS, ENTRY_BYTES, RowSink, VALUE_BYTES, heap_bytes}; use crate::metrics::increment_logs_collected_by_date; use crate::utils::json::flatten::{ @@ -448,15 +449,15 @@ pub fn scope_log_fields( scope: Option<&InstrumentationScope>, schema_url: &str, ) -> Map { - let mut scope_log_json = - Map::with_capacity(5 + scope.map_or(0, |scope| attribute_capacity(&scope.attributes))); + let capacity = 5 + scope.map_or(0, |scope| attribute_capacity(&scope.attributes)); + let mut scope_log_json = Map::with_capacity(capacity); if let Some(scope) = scope { scope_log_json.insert("scope_name".to_string(), Value::String(scope.name.clone())); scope_log_json.insert( "scope_version".to_string(), Value::String(scope.version.clone()), ); - insert_attributes(&mut scope_log_json, &scope.attributes); + insert_attributes_fitted(&mut scope_log_json, &scope.attributes, capacity); scope_log_json.insert( "scope_dropped_attributes_count".to_string(), Value::Number(scope.dropped_attributes_count.into()), @@ -471,11 +472,10 @@ pub fn scope_log_fields( /// Fields every row of one `ResourceLogs` gets, after the record's own fields pub fn resource_log_fields(resource: Option<&Resource>, schema_url: &str) -> Map { - let mut resource_log_json = Map::with_capacity( - 4 + resource.map_or(0, |resource| attribute_capacity(&resource.attributes)), - ); + let capacity = 4 + resource.map_or(0, |resource| attribute_capacity(&resource.attributes)); + let mut resource_log_json = Map::with_capacity(capacity); if let Some(resource) = resource { - insert_attributes(&mut resource_log_json, &resource.attributes); + insert_attributes_fitted(&mut resource_log_json, &resource.attributes, capacity); resource_log_json.insert( "resource_dropped_attributes_count".to_string(), Value::Number(resource.dropped_attributes_count.into()), diff --git a/src/otel/metrics.rs b/src/otel/metrics.rs index fae8e88c7..5523dbaa2 100644 --- a/src/otel/metrics.rs +++ b/src/otel/metrics.rs @@ -37,7 +37,8 @@ use crate::metrics::increment_metrics_collected_by_date; use crate::parseable::PARSEABLE; use super::otel_utils::{ - attribute_capacity, convert_epoch_nano_to_timestamp, insert_attributes, insert_number_if_some, + attribute_capacity, convert_epoch_nano_to_timestamp, insert_attributes, + insert_attributes_fitted, insert_number_if_some, }; use super::sink::RowSink; @@ -600,8 +601,9 @@ pub fn metric_rows( }; // Build metric-level fields once - let mut metadata = Map::with_capacity(attribute_capacity(&metrics_record.metadata)); - insert_attributes(&mut metadata, &metrics_record.metadata); + let capacity = attribute_capacity(&metrics_record.metadata); + let mut metadata = Map::with_capacity(capacity); + insert_attributes_fitted(&mut metadata, &metrics_record.metadata, capacity); let fields = MetricFields { name: Value::String(metrics_record.name.clone()), description: Value::String(metrics_record.description.clone()), @@ -715,11 +717,10 @@ pub struct ResourceMetricFields { impl ResourceMetricFields { pub fn new(resource: Option<&Resource>, schema_url: &str) -> Self { // Build resource-level fields once per resource - let mut resource_fields = Map::with_capacity( - resource.map_or(0, |resource| attribute_capacity(&resource.attributes)) + 2, - ); + let capacity = resource.map_or(0, |resource| attribute_capacity(&resource.attributes)) + 2; + let mut resource_fields = Map::with_capacity(capacity); if let Some(resource) = resource { - insert_attributes(&mut resource_fields, &resource.attributes); + insert_attributes_fitted(&mut resource_fields, &resource.attributes, capacity); resource_fields.insert( "resource_dropped_attributes_count".to_string(), Value::Number(resource.dropped_attributes_count.into()), diff --git a/src/otel/otel_utils.rs b/src/otel/otel_utils.rs index c5a388896..8c6864556 100644 --- a/src/otel/otel_utils.rs +++ b/src/otel/otel_utils.rs @@ -283,6 +283,31 @@ pub fn attribute_capacity(attributes: &[KeyValue]) -> usize { .count() } +/// Inserts `attributes` into `map` like `insert_attributes`, for a map created +/// with room for `capacity` entries, `attribute_capacity(attributes)` of them for +/// these attributes. When the attributes make fewer entries than that (repeated +/// keys), the map is rebuilt with room for that many fewer. +/// +/// Resource, scope, span and metric maps are cloned into rows, or are rows, and +/// `IndexMap::clone` keeps the capacity, while `row_bytes` counts the entries: a +/// scope of 128 attributes with one key made every row of it hold about 10 times +/// what was counted. Attributes with distinct keys rebuild nothing. +pub fn insert_attributes_fitted( + map: &mut Map, + attributes: &[KeyValue], + capacity: usize, +) { + let counted = attribute_capacity(attributes); + let before = map.len(); + insert_attributes(map, attributes); + let added = map.len().saturating_sub(before); + if added < counted { + let mut fitted = Map::with_capacity(capacity.saturating_sub(counted - added)); + fitted.extend(std::mem::take(map)); + *map = fitted; + } +} + pub fn insert_attributes(map: &mut Map, attributes: &[KeyValue]) { for attribute in attributes { if let Some(value) = &attribute.value diff --git a/src/otel/regression_tests.rs b/src/otel/regression_tests.rs new file mode 100644 index 000000000..eec0a7302 --- /dev/null +++ b/src/otel/regression_tests.rs @@ -0,0 +1,290 @@ +/* + * Parseable Server (C) 2022 - 2025 Parseable, Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + */ + +//! Regression tests for what two reviews of chunked OTLP ingestion found: the +//! memory of rows whose shared maps were sized by repeated attribute keys. +//! Measured with the test allocator (layout bytes, calling thread). Each test +//! prints `REGRESSION : ...`. None touches `PARSEABLE`, so they may be run +//! with the name filter `otel::regression_tests`. + +use opentelemetry_proto::tonic::collector::logs::v1::ExportLogsServiceRequest; +use opentelemetry_proto::tonic::common::v1::{AnyValue, InstrumentationScope, KeyValue, any_value}; +use opentelemetry_proto::tonic::logs::v1::{LogRecord, ResourceLogs, ScopeLogs}; +use opentelemetry_proto::tonic::metrics::v1::{Gauge, Metric, NumberDataPoint, metric}; +use opentelemetry_proto::tonic::resource::v1::Resource; +use opentelemetry_proto::tonic::trace::v1::Span; +use opentelemetry_proto::tonic::trace::v1::span::Event; +use prost::Message as _; +use serde_json::{Map, Value}; + +use super::sink::{CHUNK_LIMITS, Chunker, RowSink, row_bytes}; +use crate::test_alloc::measure; +use crate::utils::json::flatten::{FlattenBudget, FlattenLimits, JsonFlattenError}; + +const MIB: usize = 1024 * 1024; + +/// What a request may make the server hold while its rows are built and staged, +/// as `memory_tests` states it: two chunks of rows and a little more +const PEAK_BOUND: usize = 2 * CHUNK_LIMITS.bytes + 8 * MIB; + +fn mb(bytes: impl TryInto) -> f64 { + bytes.try_into().ok().unwrap() as f64 / MIB as f64 +} + +fn kv(key: &str, value: &str) -> KeyValue { + KeyValue { + key: key.into(), + value: Some(AnyValue { + value: Some(any_value::Value::StringValue(value.into())), + }), + ..Default::default() + } +} + +/// 128 attributes that all have the key `k`: one field, counted as 128 by +/// `attribute_capacity` +fn repeated_keys() -> Vec { + (0..128).map(|_| kv("k", "v")).collect() +} + +fn scope(attributes: Vec) -> Option { + Some(InstrumentationScope { + name: "scope".into(), + version: "1".into(), + attributes, + ..Default::default() + }) +} + +fn resource(attributes: Vec) -> Option { + Some(Resource { + attributes, + ..Default::default() + }) +} + +/// Keeps the last row it is handed, and nothing else +#[derive(Default)] +struct Last(Option>); + +impl RowSink for Last { + type Error = JsonFlattenError; + + fn row(&mut self, row: Map) -> Result<(), Self::Error> { + self.0 = Some(row); + Ok(()) + } +} + +/// Bytes the row built by `build` holds once built, and its `row_bytes` +fn held_and_estimated(build: impl FnOnce(&mut Last)) -> (isize, usize) { + let mut last = Last::default(); + let ((), allocated) = measure(|| build(&mut last)); + let row = last.0.expect("a row"); + (allocated.retained, row_bytes(&row)) +} + +/// Review finding 1: resource, scope, span and metric maps are sized from the +/// attribute count, which counts repeated keys, and `IndexMap::clone` keeps the +/// capacity, so a row cloned from such a map held about 10x what `row_bytes` +/// counts (a scope of 128 attributes with one key: 25,917 B against 2,613 B). +/// Every shared map now holds no more than its entries need before it is cloned. +#[test] +fn rows_copied_from_maps_with_repeated_keys_hold_what_row_bytes_counts() { + let record = LogRecord { + time_unix_nano: 1_700_000_000_000_000_000, + observed_time_unix_nano: 1_700_000_000_000_000_000, + ..Default::default() + }; + let span = Span { + trace_id: vec![1; 16], + span_id: vec![2; 8], + start_time_unix_nano: 1_700_000_000_000_000_000, + end_time_unix_nano: 1_700_000_000_000_000_001, + ..Default::default() + }; + let span_with_event = Span { + events: vec![Event { + time_unix_nano: 1_700_000_000_000_000_000, + name: "e".into(), + ..Default::default() + }], + ..span.clone() + }; + let gauge = |metadata: Vec| Metric { + name: "m".into(), + metadata, + data: Some(metric::Data::Gauge(Gauge { + data_points: vec![NumberDataPoint { + time_unix_nano: 1_700_000_000_000_000_000, + ..Default::default() + }], + })), + ..Default::default() + }; + let with_identity = |mut attributes: Vec| { + attributes.push(kv("service.name", "api")); + attributes + }; + + let mut cases: Vec<(&str, Box)> = Vec::new(); + for (level, resource_attributes, scope_attributes) in [ + ("resource", repeated_keys(), vec![]), + ("scope", vec![], repeated_keys()), + ] { + let (ra, sa) = (resource_attributes.clone(), scope_attributes.clone()); + let record = record.clone(); + cases.push(( + if level == "resource" { + "logs, resource" + } else { + "logs, scope" + }, + Box::new(move |sink: &mut Last| { + let resource_fields = super::logs::resource_log_fields(resource(ra.clone()).as_ref(), ""); + let scope_fields = super::logs::scope_log_fields(scope(sa.clone()).as_ref(), ""); + let row = super::logs::log_record_row( + &record, + &scope_fields, + &resource_fields, + &mut FlattenBudget::new(FlattenLimits::DEFAULT), + ) + .unwrap(); + drop((resource_fields, scope_fields)); + sink.row(row).unwrap(); + }), + )); + } + for (name, resource_attributes, scope_attributes, span) in [ + ("traces, resource", repeated_keys(), vec![], span.clone()), + ("traces, scope", vec![], repeated_keys(), span.clone()), + ( + "traces, span", + vec![], + vec![], + Span { + attributes: repeated_keys(), + ..span.clone() + }, + ), + ( + "traces, span with an event", + vec![], + vec![], + Span { + attributes: repeated_keys(), + ..span_with_event.clone() + }, + ), + ] { + cases.push(( + name, + Box::new(move |sink: &mut Last| { + let resource_fields = super::traces::resource_span_fields( + resource(resource_attributes.clone()).as_ref(), + "", + ); + let scope_fields = super::traces::scope_span_fields(scope(scope_attributes.clone()).as_ref()); + super::traces::span_rows( + &span, + &super::traces::SpanParents { + scope_fields: &scope_fields, + scope_schema_url: "", + resource_fields: &resource_fields, + }, + sink, + ) + .unwrap(); + }), + )); + } + for (name, resource_attributes, scope_attributes, metadata, target_info) in [ + ("metrics, resource", with_identity(repeated_keys()), vec![], vec![], false), + ("metrics, resource, target_info row", with_identity(repeated_keys()), vec![], vec![], true), + ("metrics, scope", with_identity(vec![]), repeated_keys(), vec![], false), + ("metrics, metric metadata", with_identity(vec![]), vec![], repeated_keys(), false), + ] { + let metric = gauge(metadata); + cases.push(( + name, + Box::new(move |sink: &mut Last| { + let fields = super::metrics::ResourceMetricFields::new( + resource(resource_attributes.clone()).as_ref(), + "", + ); + let envelope = fields.scope_envelope(scope(scope_attributes.clone()).as_ref(), ""); + let mut latest = None; + super::metrics::metric_rows_into(&metric, &envelope, false, &mut latest, sink) + .unwrap(); + if target_info { + sink.row(fields.target_info(latest).expect("a target_info row")) + .unwrap(); + } + }), + )); + } + + let mut failed = Vec::new(); + for (name, build) in &cases { + let (held, estimated) = held_and_estimated(build); + let ratio = held as f64 / estimated as f64; + println!( + "REGRESSION repeated keys, {name}: row holds {held} B, row_bytes {estimated} B, held/estimated {ratio:.2}" + ); + if ratio > 2.0 { + failed.push(*name); + } + } + + // The reviewer's request: 65,536 records under that scope, 1.25 MiB of protobuf + let request = ExportLogsServiceRequest { + resource_logs: vec![ResourceLogs { + scope_logs: vec![ScopeLogs { + scope: scope(repeated_keys()), + log_records: vec![record; 1 << 16], + ..Default::default() + }], + ..Default::default() + }], + }; + let (rows, allocated) = measure(|| { + let mut rows = 0usize; + let mut chunker = Chunker::new(CHUNK_LIMITS, |chunk: Vec, _bytes: usize| { + rows += chunk.len(); + Ok::<_, JsonFlattenError>(()) + }); + super::logs::flatten_logs_into( + &request.resource_logs, + &mut FlattenBudget::new(FlattenLimits::DEFAULT), + &mut chunker, + ) + .and_then(|()| chunker.finish()) + .unwrap(); + drop(chunker); + rows + }); + println!( + "REGRESSION repeated keys, request: protobuf {} KiB, {rows} rows, peak {:.1} MiB, bound {:.0} MiB", + request.encoded_len() / 1024, + mb(allocated.peak), + mb(PEAK_BOUND) + ); + assert!(failed.is_empty(), "rows hold over 2x row_bytes: {failed:?}"); + assert_eq!(rows, 1 << 16); + assert!(allocated.peak <= PEAK_BOUND, "peak {:.1} MiB", mb(allocated.peak)); +} diff --git a/src/otel/traces.rs b/src/otel/traces.rs index 34e2d9f49..468cf23f9 100644 --- a/src/otel/traces.rs +++ b/src/otel/traces.rs @@ -32,7 +32,7 @@ use crate::otel::otel_utils::flatten_attributes; use super::otel_utils::attribute_capacity; use super::otel_utils::convert_epoch_nano_to_timestamp; -use super::otel_utils::insert_attributes; +use super::otel_utils::insert_attributes_fitted; use super::sink::RowSink; pub const OTEL_TRACES_KNOWN_FIELD_LIST: [&str; 32] = [ @@ -74,13 +74,14 @@ pub fn scope_span_fields(scope: Option<&InstrumentationScope>) -> Map) -> Map, schema_url: &str) -> Map { - let mut resource_span_json = Map::with_capacity( - 4 + resource.map_or(0, |resource| attribute_capacity(&resource.attributes)), - ); + let capacity = 4 + resource.map_or(0, |resource| attribute_capacity(&resource.attributes)); + let mut resource_span_json = Map::with_capacity(capacity); if let Some(resource) = resource { - insert_attributes(&mut resource_span_json, &resource.attributes); + insert_attributes_fitted(&mut resource_span_json, &resource.attributes, capacity); resource_span_json.insert( "resource_dropped_attributes_count".to_string(), Value::Number(resource.dropped_attributes_count.into()), @@ -352,7 +352,9 @@ fn flatten_kind(kind: i32) -> Map { /// The fields of one span that every row of it gets fn flatten_span_fields(span_record: &Span) -> Map { - let mut span_record_json = Map::with_capacity(40 + attribute_capacity(&span_record.attributes)); + // Room for the scope and resource fields merged into the span's own row + let capacity = 40 + attribute_capacity(&span_record.attributes); + let mut span_record_json = Map::with_capacity(capacity); span_record_json.insert( "span_trace_id".to_string(), Value::String(hex::encode(&span_record.trace_id)), @@ -407,7 +409,7 @@ fn flatten_span_fields(span_record: &Span) -> Map { Value::Number(serde_json::Number::from(duration_nanos)), ); - insert_attributes(&mut span_record_json, &span_record.attributes); + insert_attributes_fitted(&mut span_record_json, &span_record.attributes, capacity); span_record_json.insert( "span_dropped_attributes_count".to_string(), Value::Number(span_record.dropped_attributes_count.into()), From 5a0c18d48122c1e2c86ff85aebf6d7c87fd88f57 Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Tue, 24 Nov 2026 02:38:10 -0600 Subject: [PATCH 16/31] fix(otel): keep a JSON text log body as text when its parse is over one chunk A JSON text body was parsed when its parse was estimated under 64 MiB (a 3 MiB body of 241,980 fields was accepted and peaked at 180 MiB), and a body estimated over it refused its record with LogBodyTooLarge (450,000 fields, which b8c7d979 accepted). Now at most one chunk's worth (16 MiB) of parsed memory is allowed per record; a body over it is not parsed and is kept as its text, as text that is not JSON is. Nothing is refused for this any more, so LogBodyTooLarge is removed. The scan before parsing estimated under 64 MiB for 400,000 fields whose parse held 74.5 MiB. It now counts the table and entries an IndexMap grows to, the capacity a Vec doubles to (at least 4), the old block of the last growth, and the scratch buffer escaped strings are unescaped into; checked against the allocator for 28 shapes (estimate/peak 1.00-1.95). Co-Authored-By: Claude Opus 5.5 --- src/otel/logs.rs | 278 ++++++++++++++++++++++++++++++++------ src/otel/memory_tests.rs | 5 +- src/utils/json/flatten.rs | 5 - 3 files changed, 239 insertions(+), 49 deletions(-) diff --git a/src/otel/logs.rs b/src/otel/logs.rs index a683cc9c3..19066ec64 100644 --- a/src/otel/logs.rs +++ b/src/otel/logs.rs @@ -20,7 +20,7 @@ use super::otel_utils::collect_json_from_values; use super::otel_utils::convert_epoch_nano_to_timestamp; use super::otel_utils::insert_attributes; use super::otel_utils::insert_attributes_fitted; -use super::sink::{CHUNK_LIMITS, ENTRY_BYTES, RowSink, VALUE_BYTES, heap_bytes}; +use super::sink::{CHUNK_LIMITS, RowSink, VALUE_BYTES, heap_bytes}; use crate::metrics::increment_logs_collected_by_date; use crate::utils::json::flatten::{ FlattenBudget, FlattenCost, JsonFlattenError, expand_generic_flattening, flatten_pipeline_cost, @@ -175,23 +175,26 @@ fn category_from_body(body_str: &str) -> &'static str { .map_or("UNSPECIFIED", |(_, label)| *label) } -/// Most memory the JSON text bodies of one log record may be parsed into: four -/// chunks of rows. JSON text of typical logs parses into about 8 bytes per byte, -/// so a body of several MiB of such text is accepted. -pub const MAX_PARSED_BODY_BYTES: usize = 4 * CHUNK_LIMITS.bytes; +/// Most memory the JSON text bodies of one log record may be parsed into: one +/// chunk of rows. JSON text of typical logs parses into about 8 bytes per byte, +/// so a body of a MiB or two of such text is parsed. A body that would take more +/// is kept as its text, like text that is not JSON. +pub const MAX_PARSED_BODY_BYTES: usize = CHUNK_LIMITS.bytes; -/// Most bytes one byte of JSON text parses into: `0,` in an array is a 72 byte -/// `Value`, in a `Vec` that may have grown to twice its length +/// Most bytes one byte of JSON text parses into, at the peak of parsing it: each +/// level of arrays nested in arrays (`[` and `]`, two bytes) is a `Vec` of four +/// 72 byte `Value`s, which is the most any two bytes of text make (see +/// `json_object_text_bytes`) const PARSED_BYTES_PER_TEXT_BYTE: usize = 2 * VALUE_BYTES; /// Parses every body that is the JSON text of an object, as the fields of the /// record are extracted from those only. Bodies are measured before they are /// parsed: a body whose text could parse into more than what is left of /// `MAX_PARSED_BODY_BYTES` is first scanned without allocating, which finds its -/// type and the memory parsing it takes. Text that is not an object is not parsed. -fn parse_json_object_bodies( - body_json: &Map, -) -> Result>, JsonFlattenError> { +/// type and the memory parsing it takes. A body that would take more than is left +/// is not parsed, and neither is text that is not an object: those are kept as +/// their text. +fn parse_json_object_bodies(body_json: &Map) -> Vec> { let mut held = 0usize; let mut parsed = Vec::with_capacity(body_json.len()); for value in body_json.values() { @@ -202,17 +205,14 @@ fn parse_json_object_bodies( let most = text.len().saturating_mul(PARSED_BYTES_PER_TEXT_BYTE); if held.saturating_add(most) > MAX_PARSED_BODY_BYTES { match json_object_text_bytes(text) { - // Not the JSON text of an object: not parsed, as before - None => { + Some(bytes) if held.saturating_add(bytes) <= MAX_PARSED_BODY_BYTES => { + held += bytes; + } + // Not the JSON text of an object, or too large to parse: kept as text + _ => { parsed.push(None); continue; } - Some(bytes) => { - held = held.saturating_add(bytes); - if held > MAX_PARSED_BODY_BYTES { - return Err(JsonFlattenError::LogBodyTooLarge(MAX_PARSED_BODY_BYTES)); - } - } } } else { held += most; @@ -223,29 +223,83 @@ fn parse_json_object_bodies( .filter(Value::is_object), ); } - Ok(parsed) + parsed } -/// Memory `serde_json::from_str::(text)` takes when `text` is the JSON -/// text of an object, found without allocating; `None` for any other text +/// Size of one `serde_json::Map` entry (an `IndexMap` bucket): the hash, the key +/// and the value +const MAP_ENTRY_BYTES: usize = + std::mem::size_of::() + std::mem::size_of::() + VALUE_BYTES; + +/// Most memory `serde_json::from_str::(text)` holds at once while parsing +/// `text`, when it is the JSON text of an object, found without allocating; `None` +/// for any other text. +/// +/// Containers are counted at the capacity they grow to while their elements are +/// pushed one at a time: a `Vec` to at least 4 elements and then by doubling, a +/// map's hash table by doubling its buckets (3, 7, 14, 28... entries fit) and its +/// entries to what the table fits. The old block of the last growth is counted as +/// well, as a reallocation holds both. So is the scratch buffer strings with escapes +/// are unescaped into, at three times the longest string. Repeated keys are counted +/// as distinct ones. The most any two bytes of text make is one more level of +/// arrays nested in arrays: a `Vec` of four `Value`s, `2 * VALUE_BYTES` per byte, +/// which `PARSED_BYTES_PER_TEXT_BYTE` is. fn json_object_text_bytes(text: &str) -> Option { use serde::de::{Deserialize, Deserializer, MapAccess, SeqAccess, Visitor}; - /// Heap bytes of one parsed value, and whether it is an object + /// Heap bytes of one parsed value, whether it is an object, and the longest + /// string in it struct Parsed { bytes: usize, object: bool, + longest: usize, } impl Parsed { - fn scalar(bytes: usize) -> Self { + fn scalar() -> Self { Self { - bytes, + bytes: 0, object: false, + longest: 0, } } } + /// Bytes of a `Vec` of `len` values pushed one at a time, at the peak of its + /// last growth + fn vec_bytes(len: usize) -> usize { + if len == 0 { + return 0; + } + let capacity = len.next_power_of_two().max(4); + let previous = if len > 4 { capacity / 2 } else { 0 }; + heap_bytes(capacity.saturating_mul(VALUE_BYTES)) + .saturating_add(heap_bytes(previous.saturating_mul(VALUE_BYTES))) + } + + /// Bytes of a map of `len` entries inserted one at a time, at the peak of its + /// last growth: the hash table of `usize` indices (8 bytes and a control byte + /// per bucket, and one group of control bytes), and the entries, which grow to + /// what the table fits + fn map_bytes(len: usize) -> usize { + if len == 0 { + return 0; + } + let fits = |buckets: usize| if buckets < 8 { buckets - 1 } else { buckets / 8 * 7 }; + let mut buckets = 4usize; + while fits(buckets) < len { + buckets = buckets.saturating_mul(2); + } + let table = heap_bytes(buckets.saturating_mul(9).saturating_add(16)); + let entries = heap_bytes(fits(buckets).saturating_mul(MAP_ENTRY_BYTES)); + let previous = if buckets > 4 { + heap_bytes(fits(buckets / 2).saturating_mul(MAP_ENTRY_BYTES)) + } else { + 0 + }; + table.saturating_add(entries).saturating_add(previous) + } + impl<'de> Deserialize<'de> for Parsed { fn deserialize>(deserializer: D) -> Result { deserializer.deserialize_any(ParsedVisitor) @@ -261,47 +315,56 @@ fn json_object_text_bytes(text: &str) -> Option { formatter.write_str("any JSON value") } fn visit_bool(self, _: bool) -> Result { - Ok(Parsed::scalar(0)) + Ok(Parsed::scalar()) } fn visit_i64(self, _: i64) -> Result { - Ok(Parsed::scalar(0)) + Ok(Parsed::scalar()) } fn visit_u64(self, _: u64) -> Result { - Ok(Parsed::scalar(0)) + Ok(Parsed::scalar()) } fn visit_f64(self, _: f64) -> Result { - Ok(Parsed::scalar(0)) + Ok(Parsed::scalar()) } fn visit_unit(self) -> Result { - Ok(Parsed::scalar(0)) + Ok(Parsed::scalar()) } fn visit_str(self, s: &str) -> Result { - Ok(Parsed::scalar(heap_bytes(s.len()))) + Ok(Parsed { + bytes: heap_bytes(s.len()), + object: false, + longest: s.len(), + }) } fn visit_seq>(self, mut seq: A) -> Result { let mut len = 0usize; let mut bytes = 0usize; + let mut longest = 0usize; while let Some(element) = seq.next_element::()? { len += 1; bytes = bytes.saturating_add(element.bytes); + longest = longest.max(element.longest); } - // The `Vec` grows by doubling - Ok(Parsed::scalar(bytes.saturating_add(heap_bytes( - len.next_power_of_two().saturating_mul(VALUE_BYTES), - )))) + Ok(Parsed { + bytes: bytes.saturating_add(vec_bytes(len)), + object: false, + longest, + }) } fn visit_map>(self, mut map: A) -> Result { + let mut len = 0usize; let mut bytes = 0usize; + let mut longest = 0usize; while let Some(key) = map.next_key::()? { let value = map.next_value::()?; - bytes = bytes - .saturating_add(ENTRY_BYTES) - .saturating_add(key.bytes) - .saturating_add(value.bytes); + len += 1; + bytes = bytes.saturating_add(key.bytes).saturating_add(value.bytes); + longest = longest.max(key.longest).max(value.longest); } Ok(Parsed { - bytes, + bytes: bytes.saturating_add(map_bytes(len)), object: true, + longest, }) } } @@ -309,7 +372,10 @@ fn json_object_text_bytes(text: &str) -> Option { let mut deserializer = serde_json::Deserializer::from_str(text); let parsed = Parsed::deserialize(&mut deserializer).ok()?; deserializer.end().ok()?; - parsed.object.then_some(parsed.bytes) + let scratch = heap_bytes(parsed.longest.saturating_mul(3)); + parsed + .object + .then_some(parsed.bytes.saturating_add(scratch)) } /// this function flattens the `LogRecord` object @@ -348,7 +414,7 @@ pub fn flatten_log_record( let body = &log_record.body; let body_json = collect_json_from_values(body, "body"); // Values that are strings which can be parsed as JSON objects get their fields extracted - let parsed_bodies = parse_json_object_bodies(&body_json)?; + let parsed_bodies = parse_json_object_bodies(&body_json); // The rows of every parsed body are merged into this record, but they are all built // first, so charge all of them before building any let limits = budget.limits(); @@ -1118,6 +1184,134 @@ mod tests { ); } + const MIB: usize = 1024 * 1024; + + /// A JSON object of `fields` fields `"f0000000":0`, the reviewer's shape + fn many_fields(fields: usize) -> String { + let mut text = String::from("{"); + for i in 0..fields { + if i > 0 { + text.push(','); + } + text.push_str(&format!("\"f{i:07}\":0")); + } + text.push('}'); + text + } + + fn timed_record(body: String) -> LogRecord { + LogRecord { + time_unix_nano: 1_700_000_000_000_000_000, + observed_time_unix_nano: 1_700_000_000_000_000_000, + body: string_body(&body), + ..Default::default() + } + } + + /// Review findings 2 and 6: a JSON text body was parsed when its parse was + /// estimated under 64 MiB (a 3 MiB body of 241,980 fields was accepted and + /// peaked at 180 MiB), and a body estimated over it refused its record with + /// `LogBodyTooLarge` (450,000 fields, 5.6 MiB, which `b8c7d979` accepted). Now + /// at most one chunk's worth (16 MiB) of parsed memory is allowed, and a body + /// over it is kept as its text, as text that is not JSON is: never refused. + #[test] + fn json_text_body_over_one_chunk_of_parsed_memory_is_kept_as_text() { + let mut measured = Vec::new(); + for fields in [241_980usize, 400_000, 450_000] { + let text = many_fields(fields); + let record = timed_record(text.clone()); + let mut budget = FlattenBudget::new(FlattenLimits::DEFAULT); + let (flattened, allocated) = + crate::test_alloc::measure(|| flatten_log_record(&record, &mut budget)); + println!( + "REGRESSION JSON text body of {fields} fields: text {:.2} MiB, {}, peak {:.1} MiB", + text.len() as f64 / MIB as f64, + match &flattened { + Ok(row) => format!("{} fields", row.len()), + Err(e) => format!("refused: {e}"), + }, + allocated.peak as f64 / MIB as f64, + ); + measured.push((fields, text, flattened, allocated.peak)); + } + for (fields, text, flattened, peak) in measured { + let row = flattened.expect("the record is not refused"); + assert_eq!(row["body"], json!(text)); + assert!( + !row.keys().any(|key| key.starts_with("body_")), + "{fields} fields: the body was parsed" + ); + // Copies of the text: the body field, its copy in the row, and the + // text the category is looked for in (severity is unset) + assert!(peak < 5 * text.len() + MIB, "{fields} fields"); + } + // A body whose parse fits in one chunk is still parsed + let text = many_fields(40_000); + let row = flatten_log_record( + &timed_record(text), + &mut FlattenBudget::new(FlattenLimits::DEFAULT), + ) + .unwrap(); + assert_eq!(row["body_f0039999"], json!(0)); + } + + /// Review finding 6: the scan before parsing estimated under 64 MiB for an + /// object of 400,000 fields whose parse held 74.5 MiB. The estimate counts the + /// table and entries an `IndexMap` grows to, a `Vec` the capacity it doubles + /// to, and the old block of the last growth, which a reallocation holds too. + #[test] + fn parsed_body_estimate_covers_what_parsing_holds() { + let mut shapes: Vec<(String, String)> = [1usize, 3, 4, 7, 8, 15, 100, 1000, 100_000, 400_000] + .into_iter() + .map(|n| (format!("object of {n} fields"), many_fields(n))) + .collect(); + for n in [1usize, 4, 5, 1000, 262_145] { + let numbers = vec!["0"; n].join(","); + shapes.push((format!("{n} numbers"), format!(r#"{{"a":[{numbers}]}}"#))); + let singles = vec!["[0]"; n].join(","); + shapes.push((format!("{n} one-number arrays"), format!(r#"{{"a":[{singles}]}}"#))); + let objects = vec![r#"{"k":"v","n":1}"#; n].join(","); + shapes.push((format!("{n} small objects"), format!(r#"{{"a":[{objects}]}}"#))); + } + for n in [1000usize, 1_000_000] { + // Escapes are unescaped into a scratch buffer while parsing + shapes.push(( + format!("escaped string of {n} bytes"), + format!(r#"{{"m":"{}"}}"#, "\\n".repeat(n)), + )); + } + shapes.push(( + "nested objects".into(), + format!("{}{}", r#"{"a":"#.repeat(100), format!("0{}", "}".repeat(100))), + )); + let mut under = Vec::new(); + for (name, text) in shapes { + let estimate = super::json_object_text_bytes(&text).expect("an object"); + let (parsed, allocated) = + crate::test_alloc::measure(|| serde_json::from_str::(&text)); + assert!(parsed.is_ok()); + drop(parsed); + let ratio = estimate as f64 / allocated.peak.max(1) as f64; + println!( + "REGRESSION parsed body estimate, {name}: text {} B, estimate {estimate} B, parse peak {} B, estimate/peak {ratio:.2}", + text.len(), + allocated.peak + ); + if estimate < allocated.peak { + under.push(name.clone()); + } + assert!( + (text.len() * super::PARSED_BYTES_PER_TEXT_BYTE) >= allocated.peak, + "{name}: over the quick bound per text byte" + ); + assert!( + (text.len() * super::PARSED_BYTES_PER_TEXT_BYTE) >= estimate, + "{name}: estimate over the quick bound per text byte" + ); + } + assert!(under.is_empty(), "estimated under the parse: {under:?}"); + } + // Release-profile micro-benchmarks. Run with a filter, for example: // cargo test --release --lib -- --ignored --exact otel::logs::tests::bench_flatten_otel_protobuf_logs --nocapture // They never touch the PARSEABLE global: every timestamp is set, so the rows diff --git a/src/otel/memory_tests.rs b/src/otel/memory_tests.rs index 92e8e723b..de37aa03a 100644 --- a/src/otel/memory_tests.rs +++ b/src/otel/memory_tests.rs @@ -244,7 +244,8 @@ fn tiny_copied_fields_are_handed_over_in_bounded_memory() { } /// Review finding 7: a log body that is JSON text was parsed before anything was -/// charged. A 10 MiB body `{"a":[0,0,...]}` peaked at 586 MiB. +/// charged. A 10 MiB body `{"a":[0,0,...]}` peaked at 586 MiB. It would parse into +/// more than one chunk's worth of memory, so it is kept as its text. #[test] fn json_text_log_body_is_not_parsed_into_unbounded_memory() { let mut text = String::with_capacity(10 * MIB); @@ -272,7 +273,7 @@ fn json_text_log_body_is_not_parsed_into_unbounded_memory() { }; let mut budget = FlattenBudget::new(FlattenLimits::DEFAULT); let (result, allocated) = hand_over("10 MiB JSON text body", logs(&request, &mut budget)); - assert!(result.is_err(), "the body expands far beyond the limits"); + assert_eq!(result.unwrap().rows, 1, "the record is kept, its body as text"); // The row holds copies of the body text, nothing parsed from it assert!( allocated.peak < PEAK_BOUND + 3 * body_len, diff --git a/src/utils/json/flatten.rs b/src/utils/json/flatten.rs index 77cbeb50e..13a25575b 100644 --- a/src/utils/json/flatten.rs +++ b/src/utils/json/flatten.rs @@ -117,10 +117,6 @@ pub enum JsonFlattenError { "Flattening the request would produce more than {0} bytes of JSON (P_MAX_FLATTEN_BYTES_PER_REQUEST). Split the batch into smaller requests, or reduce the number or size of nested arrays in its events" )] BytesPerRequestLimitExceeded(usize), - #[error( - "A log body of JSON text would take more than {0} bytes of memory once parsed. Send it as a key-value list body, or split it over several records" - )] - LogBodyTooLarge(usize), } impl JsonFlattenError { @@ -132,7 +128,6 @@ impl JsonFlattenError { Self::RowsPerEventLimitExceeded(_) | Self::RowsPerRequestLimitExceeded(_) | Self::BytesPerRequestLimitExceeded(_) - | Self::LogBodyTooLarge(_) ) } } From 0b44f8cc0e13a5fd5c029aeace690ccd5974e7a8 Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Tue, 24 Nov 2026 02:39:14 -0600 Subject: [PATCH 17/31] fix(otel): cap expansion by the body, answer empty requests without a stream Three changes to staging one OTLP request: - The expansion cap was 1024 x P_MAX_EVENT_PAYLOAD_SIZE (10 GiB) for any body, so a 45 KB body staged 460 MB of rows. It is now 4096 x the length of the decompressed body, at least one chunk (16 MiB). The 15 realistic shapes at the payload limit stay under it with at least 8x headroom (worst 458 row bytes per body byte), and so do the same shapes with 1, 10 and 100 records. - An empty request (an empty protobuf body, or `{}` for JSON) is answered 200 without the stream. The dataset field check counts a missing stream as having no fields; staging a request that has rows still needs the stream (404). `{}` was refused by serde before, and an empty request to a missing stream got 404 at b8c7d979 too. - For OTLP JSON the dataset field count is checked before the body is decoded into a request, as at b8c7d979. Co-Authored-By: Claude Opus 5.5 --- src/handlers/http/modal/utils/ingest_utils.rs | 125 ++++++++++++--- .../utils/ingest_utils/otel_protobuf_props.rs | 10 +- .../ingest_utils/otel_regression_tests.rs | 131 +++++++++++++++ .../ingest_utils/otel_server_state_tests.rs | 150 ++++++++++++++++++ src/otel/realistic_tests.rs | 43 +++-- src/otel/sink.rs | 39 +++-- 6 files changed, 448 insertions(+), 50 deletions(-) create mode 100644 src/handlers/http/modal/utils/ingest_utils/otel_regression_tests.rs create mode 100644 src/handlers/http/modal/utils/ingest_utils/otel_server_state_tests.rs diff --git a/src/handlers/http/modal/utils/ingest_utils.rs b/src/handlers/http/modal/utils/ingest_utils.rs index 147070a1d..ac18806c3 100644 --- a/src/handlers/http/modal/utils/ingest_utils.rs +++ b/src/handlers/http/modal/utils/ingest_utils.rs @@ -66,8 +66,8 @@ use crate::{ refusal, }, sink::{ - CHUNK_LIMITS, ChunkLimits, Chunker, EXPANSION_FACTOR, RowSink, Staged, - max_expanded_bytes, + CHUNK_LIMITS, ChunkLimits, Chunker, EXPANSION_FACTOR, MIN_EXPANDED_BYTES, RowSink, + Staged, max_expanded_bytes, }, traces::flatten_traces_into, }, @@ -305,7 +305,7 @@ fn handle_otel_ingestion( return Err(PostError::SerdeError(e)); } }; - ingest_otel_json(json, &target).inspect_err(|e| { + ingest_otel_json(json, body.len(), &target).inspect_err(|e| { error!("Ingestion failed for stream {stream_name}: {e}"); }) } @@ -390,6 +390,29 @@ impl OtelResources<'_> { } } + /// Leaf records of the request: log records, metrics or spans. A request + /// without any has no rows. + fn records(&self) -> u64 { + let count = |n: usize| n as u64; + match self { + Self::Logs(resources) => resources + .iter() + .flat_map(|r| &r.scope_logs) + .map(|s| count(s.log_records.len())) + .sum(), + Self::Metrics(resources) => resources + .iter() + .flat_map(|r| &r.scope_metrics) + .map(|s| count(s.metrics.len())) + .sum(), + Self::Traces(resources) => resources + .iter() + .flat_map(|r| &r.scope_spans) + .map(|s| count(s.spans.len())) + .sum(), + } + } + /// Hands the rows of the request to `sink`, one at a time fn flatten_into( &self, @@ -416,7 +439,7 @@ impl OtelResources<'_> { /// The refusal of a request whose rows hold more than `max` estimated bytes in all fn expansion_error(max: u64) -> PostError { PostError::Invalid(anyhow::anyhow!( - "The rows of the request take more than the {max} bytes allowed ({EXPANSION_FACTOR} times P_MAX_EVENT_PAYLOAD_SIZE). Split the batch into smaller requests, or send fewer resource, scope and span attributes per record" + "The rows of the request take more than the {max} bytes allowed ({EXPANSION_FACTOR} times the length of its body, at least {MIN_EXPANDED_BYTES}). Split the batch into smaller requests, or send fewer resource, scope and span attributes per record" )) } @@ -429,6 +452,17 @@ struct StageLimits { flatten: FlattenLimits, } +impl StageLimits { + /// The limits of staging a request whose body (decompressed) is `body_len` bytes + fn for_body(body_len: usize, flatten: FlattenLimits) -> Self { + Self { + chunk: CHUNK_LIMITS, + max_expanded: max_expanded_bytes(body_len), + flatten, + } + } +} + /// Flattens one OTEL request and hands its rows to `stage` in chunks (see /// `Chunker`), so that they are never all held at once. The rows passed on are /// counted against `limits.max_expanded` as they go: the chunk that would pass @@ -500,26 +534,27 @@ fn otel_outcome( } } -/// Stages the rows of one OTEL request in chunks into its stream, see -/// `stage_otel_rows` and `otel_outcome` +/// Stages the rows of one OTEL request of `records` leaf records (log records, +/// metrics or spans), whose body is `body_len` bytes, in chunks into its stream, +/// see `stage_otel_rows` and `otel_outcome`. The caller has checked the dataset +/// field count (`verify_otel_fields_count`). A request without records has no +/// rows, and is answered without the stream. fn ingest_otel_rows( signal: Signal, target: &OtelTarget<'_>, + body_len: usize, + records: u64, flatten: impl FnOnce( &mut FlattenBudget, &mut dyn RowSink, ) -> Result<(), PostError>, total: impl FnOnce() -> u64, ) -> Result { + if records == 0 { + return Ok(OtelIngested::Full); + } let tenant_str = target.tenant_id.as_deref().unwrap_or(DEFAULT_TENANT); - // Verify the dataset fields count - verify_dataset_fields_count(target.stream_name, target.tenant_id)?; - - let limits = StageLimits { - chunk: CHUNK_LIMITS, - max_expanded: max_expanded_bytes(max_event_payload_size()), - flatten: FlattenLimits::from_config(), - }; + let limits = StageLimits::for_body(body_len, FlattenLimits::from_config()); let mut staging = Staging::new(target.stream_name, target.tenant_id)?; let (result, staged) = stage_otel_rows(limits, flatten, |rows| { staging.push( @@ -539,12 +574,15 @@ fn ingest_otel_rows( /// `ingest_otel_rows` for a request decoded whole (OTLP JSON) fn ingest_otel_resources( resources: OtelResources<'_>, + body_len: usize, target: &OtelTarget<'_>, ) -> Result { let flatten_exemplars = PARSEABLE.options.otel_flatten_exemplars; ingest_otel_rows( resources.signal(), target, + body_len, + resources.records(), |budget, sink| resources.flatten_into(budget, flatten_exemplars, sink), || resources.total(), ) @@ -564,21 +602,43 @@ fn count_collected(signal: Signal, records: u64, tenant_id: &str) { } } -/// The OTEL arms of `handle_otel_ingestion` for a JSON body -fn ingest_otel_json(json: Value, target: &OtelTarget<'_>) -> Result { +/// The OTEL arms of `handle_otel_ingestion` for a JSON body of `body_len` bytes. +/// The dataset field count is checked before the body is decoded into a request. +fn ingest_otel_json( + json: Value, + body_len: usize, + target: &OtelTarget<'_>, +) -> Result { let normalise = PARSEABLE.options.normalise_otel_payload; + // `{}` is the JSON encoding of an empty request, which the generated types + // refuse for the collection it leaves out; it has no rows + let empty = |json: &Value| -> Result { + verify_otel_fields_count(target.stream_name, target.tenant_id)?; + Ok(json.as_object().is_some_and(|fields| fields.is_empty())) + }; match target.log_source { + LogSource::OtelLogs | LogSource::OtelMetrics | LogSource::OtelTraces if empty(&json)? => { + Ok(OtelIngested::Full) + } LogSource::OtelLogs => { let logs: LogsData = deserialize_otel_json(json, normalise)?; - ingest_otel_resources(OtelResources::Logs(&logs.resource_logs), target) + ingest_otel_resources(OtelResources::Logs(&logs.resource_logs), body_len, target) } LogSource::OtelMetrics => { let metrics: MetricsData = deserialize_otel_json(json, normalise)?; - ingest_otel_resources(OtelResources::Metrics(&metrics.resource_metrics), target) + ingest_otel_resources( + OtelResources::Metrics(&metrics.resource_metrics), + body_len, + target, + ) } LogSource::OtelTraces => { let traces: TracesData = deserialize_otel_json(json, normalise)?; - ingest_otel_resources(OtelResources::Traces(&traces.resource_spans), target) + ingest_otel_resources( + OtelResources::Traces(&traces.resource_spans), + body_len, + target, + ) } other => Err(PostError::Invalid(anyhow::anyhow!( "OTLP ingestion requires an OTLP log source, got {other}" @@ -666,9 +726,12 @@ fn flatten_and_push_otel_protobuf( options: impl FnOnce() -> ProtobufOptions, ) -> Result { let (signal, outline, options) = outline_otel_protobuf(&body, target, options)?; + verify_otel_fields_count(target.stream_name, target.tenant_id)?; ingest_otel_rows( signal, target, + body.len(), + outline.records, |budget, sink| flatten_otel_protobuf(&body, signal, &options, target, budget, sink), || protobuf_total(&body, signal, &outline), ) @@ -858,7 +921,11 @@ pub fn flatten_and_push_logs( telemetry_type, tenant_id, }; - if let OtelIngested::Partial { message, .. } = ingest_otel_json(json, &target)? { + // The body's length, as the expansion cap counts it, is that of the + // JSON text of the value + let body_len = json_byte_size(&json) as usize; + if let OtelIngested::Partial { message, .. } = ingest_otel_json(json, body_len, &target)? + { return Err(PostError::Invalid(anyhow::Error::msg(message))); } } @@ -1295,6 +1362,20 @@ pub fn get_otel_custom_fields_from_header( custom_fields } +/// `verify_dataset_fields_count` for an OTEL request, which may be answered +/// without its stream: a stream that does not exist has no fields to count. +/// Staging a chunk of a request that has rows needs the stream, and fails there +/// as before (404). +fn verify_otel_fields_count( + stream_name: &str, + tenant_id: &Option, +) -> Result<(), PostError> { + match verify_dataset_fields_count(stream_name, tenant_id) { + Err(PostError::StreamNotFound(_)) => Ok(()), + checked => checked, + } +} + fn verify_dataset_fields_count( stream_name: &str, tenant_id: &Option, @@ -1969,3 +2050,7 @@ mod tests { #[cfg(test)] mod otel_protobuf_props; +#[cfg(test)] +mod otel_regression_tests; +#[cfg(test)] +mod otel_server_state_tests; diff --git a/src/handlers/http/modal/utils/ingest_utils/otel_protobuf_props.rs b/src/handlers/http/modal/utils/ingest_utils/otel_protobuf_props.rs index 0f68bc307..0cc4814d7 100644 --- a/src/handlers/http/modal/utils/ingest_utils/otel_protobuf_props.rs +++ b/src/handlers/http/modal/utils/ingest_utils/otel_protobuf_props.rs @@ -84,13 +84,9 @@ const PROTOBUF_OPTIONS: ProtobufOptions = ProtobufOptions { flatten_exemplars: false, }; -/// The staging limits of the server defaults +/// The staging limits of the server defaults, for a body at the payload limit fn test_limits() -> StageLimits { - StageLimits { - chunk: CHUNK_LIMITS, - max_expanded: max_expanded_bytes(PROTOBUF_OPTIONS.max_payload), - flatten: FlattenLimits::DEFAULT, - } + StageLimits::for_body(PROTOBUF_OPTIONS.max_payload, FlattenLimits::DEFAULT) } // --------------------------------------------------------------------------- @@ -3894,7 +3890,7 @@ mod streamed { for (outcome, counted) in [&protobuf, &json] { assert!(counted.chunks > 0 && counted.records < 2000, "{counted:?}"); let message = format!( - "Invalid Request: The rows of the request take more than the {cap} bytes allowed (1024 times P_MAX_EVENT_PAYLOAD_SIZE). Split the batch into smaller requests, or send fewer resource, scope and span attributes per record" + "Invalid Request: The rows of the request take more than the {cap} bytes allowed (4096 times the length of its body, at least 16777216). Split the batch into smaller requests, or send fewer resource, scope and span attributes per record" ); assert_eq!( outcome.as_ref().unwrap(), diff --git a/src/handlers/http/modal/utils/ingest_utils/otel_regression_tests.rs b/src/handlers/http/modal/utils/ingest_utils/otel_regression_tests.rs new file mode 100644 index 000000000..0421830de --- /dev/null +++ b/src/handlers/http/modal/utils/ingest_utils/otel_regression_tests.rs @@ -0,0 +1,131 @@ +/* + * Parseable Server (C) 2022 - 2025 Parseable, Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + */ + +//! Regression tests for what two reviews of chunked OTLP staging found, at the +//! level of one request. Each prints `REGRESSION : ...`. None touches +//! `PARSEABLE`, so they may be run with the filter `otel_regression_tests`; the +//! ones that need the server are in `otel_server_state_tests`. + +use super::*; +use opentelemetry_proto::tonic::common::v1::{AnyValue, KeyValue, any_value}; +use opentelemetry_proto::tonic::logs::v1::{LogRecord, ScopeLogs}; +use opentelemetry_proto::tonic::resource::v1::Resource; + +const MIB: usize = 1024 * 1024; + +/// `P_MAX_EVENT_PAYLOAD_SIZE` default +const PAYLOAD: usize = 10 * MIB; + +const OPTIONS: ProtobufOptions = ProtobufOptions { + max_payload: PAYLOAD, + flatten_exemplars: false, +}; + +fn kv(key: &str, value: impl Into) -> KeyValue { + KeyValue { + key: key.into(), + value: Some(AnyValue { + value: Some(any_value::Value::StringValue(value.into())), + }), + ..Default::default() + } +} + +fn target<'a>( + log_source: &'a LogSource, + p_custom_fields: &'a HashMap, +) -> OtelTarget<'a> { + OtelTarget { + stream_name: "otel_regression", + log_source, + p_custom_fields, + telemetry_type: TelemetryType::Logs, + tenant_id: &None, + } +} + +/// The staging limits ingestion uses for a body of `body_len` bytes +fn limits_for(body_len: usize) -> StageLimits { + StageLimits::for_body(body_len, FlattenLimits::DEFAULT) +} + +/// Review finding 8: the expansion cap was 1024 x `P_MAX_EVENT_PAYLOAD_SIZE` +/// (10 GiB) whatever the size of the body, so a body of a few KiB could stage +/// gigabytes of rows. It is now 4096 x the length of the body, with a floor. +#[test] +fn expansion_cap_is_4096_times_the_body_with_a_floor() { + use crate::otel::sink::{EXPANSION_FACTOR, MIN_EXPANDED_BYTES}; + assert_eq!(EXPANSION_FACTOR, 4096); + assert_eq!(max_expanded_bytes(0), MIN_EXPANDED_BYTES); + assert_eq!(max_expanded_bytes(1000), MIN_EXPANDED_BYTES); + assert_eq!(max_expanded_bytes(1 << 20), 4u64 << 30); + assert_eq!(max_expanded_bytes(PAYLOAD), 40u64 << 30); +} + +/// Review finding 8, as a request: a body of 47 KiB whose rows expand past 4096x +/// its length is cut off by the cap (it passed whole under the 10 GiB cap) +#[test] +fn a_small_body_expanding_past_4096_times_its_length_is_refused() { + // 100 resource attributes over records of two bytes each: their rows hold + // about 460 MB, past 4096 x the body's length but far under 10 GiB + let request = ExportLogsServiceRequest { + resource_logs: vec![ResourceLogs { + resource: Some(Resource { + attributes: (0..100) + .map(|i| kv(&format!("k8s.pod.label.{i:03}"), format!("{i:032}"))) + .collect(), + ..Default::default() + }), + scope_logs: vec![ScopeLogs { + log_records: vec![LogRecord::default(); 20_000], + ..Default::default() + }], + ..Default::default() + }], + }; + let body = web::Bytes::from(request.encode_to_vec()); + let limits = limits_for(body.len()); + let fields = HashMap::new(); + let mut staged_bytes = 0u64; + let (outcome, staged) = stage_otel_protobuf( + body.clone(), + &target(&LogSource::OtelLogs, &fields), + OPTIONS, + limits, + |rows| { + staged_bytes += rows + .iter() + .map(|row| crate::otel::sink::row_bytes(row.as_object().unwrap()) as u64) + .sum::(); + Ok(()) + }, + ); + println!( + "REGRESSION expansion cap: body {} B, cap {} B, staged {} of 20000 rows ({} B), outcome {:?}", + body.len(), + limits.max_expanded, + staged.rows, + staged_bytes, + outcome.as_ref().map_err(|e| e.to_string()) + ); + assert!( + matches!(&outcome, Ok(OtelIngested::Partial { rejected, .. }) if *rejected > 0), + "{outcome:?}" + ); + assert!(staged_bytes <= limits.max_expanded); +} diff --git a/src/handlers/http/modal/utils/ingest_utils/otel_server_state_tests.rs b/src/handlers/http/modal/utils/ingest_utils/otel_server_state_tests.rs new file mode 100644 index 000000000..044164a81 --- /dev/null +++ b/src/handlers/http/modal/utils/ingest_utils/otel_server_state_tests.rs @@ -0,0 +1,150 @@ +/* + * Parseable Server (C) 2022 - 2025 Parseable, Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + */ + +//! Regression tests of OTLP ingestion that read the server state (`PARSEABLE`). +//! Each first sets up the global server state as the metastore contract tests do +//! (`CONTRACT_PARSEABLE_FACTORY`: default options, local storage in a temporary +//! directory under `target`), so the configuration is never parsed from the test +//! binary's command line and the tests may be run with a name filter. Each prints +//! `REGRESSION : ...`. + +use super::*; +use crate::metadata::{LogStreamMetadata, SchemaVersion}; +use actix_web::test::TestRequest; +use arrow_schema::{DataType, Field}; +use std::sync::Arc; + +/// Sets up `PARSEABLE` for tests, unless a test already did +fn initialize_server() { + fn factory() -> crate::parseable::Parseable { + use crate::storage::object_storage::ObjectStorageProvider; + let root = tempfile::tempdir_in(concat!(env!("CARGO_MANIFEST_DIR"), "/target")) + .unwrap() + .keep(); + let provider = Arc::new(crate::storage::FSConfig { root }); + let storage = provider.construct_client(); + let metastore = Arc::new( + crate::metastore::metastores::object_store_metastore::ObjectStoreMetastore { + storage: storage.clone(), + }, + ); + crate::parseable::Parseable::new( + crate::cli::Options::default(), + #[cfg(feature = "kafka")] + ::parse_from([ + "otel", + ]), + provider, + metastore, + storage, + ) + } + let _ = crate::parseable::CONTRACT_PARSEABLE_FACTORY.set(factory); + once_cell::sync::Lazy::force(&PARSEABLE); +} + +const SIGNALS: [(TelemetryType, LogSource); 3] = [ + (TelemetryType::Logs, LogSource::OtelLogs), + (TelemetryType::Metrics, LogSource::OtelMetrics), + (TelemetryType::Traces, LogSource::OtelTraces), +]; + +/// Review finding 7d: an empty request must be answered 200 without the stream, +/// in both encodings and for every signal. Collector setup scripts detect +/// protobuf support by posting an empty protobuf body to `/v1/metrics`. +#[tokio::test] +async fn empty_requests_are_answered_200_without_a_stream() { + initialize_server(); + for (telemetry_type, log_source) in SIGNALS { + for (content_type, body) in [ + ("application/x-protobuf", &b""[..]), + ("application/json", &b"{}"[..]), + ] { + let req = TestRequest::default() + .insert_header((CONTENT_TYPE, content_type)) + .to_http_request(); + let ingested = process_otel_content( + &req, + web::Bytes::from_static(body), + "otel_regression_no_such_stream", + &log_source, + telemetry_type, + ) + .await; + println!( + "REGRESSION empty request, {log_source}, {content_type}: {:?}", + ingested.as_ref().map_err(|e| e.to_string()) + ); + let ingested = ingested.expect("an empty request is accepted"); + assert_eq!(ingested, OtelIngested::Full); + let response = otel_response(&req, telemetry_type, &ingested); + assert_eq!(response.status(), actix_web::http::StatusCode::OK); + } + } +} + +/// Review finding 7a: for OTLP JSON the dataset field count is checked before +/// the body is decoded into a request, as at `b8c7d979`: a body that is not a +/// request, sent to a dataset over its field limit, is refused for the limit. +#[tokio::test] +async fn otlp_json_checks_the_field_count_before_decoding() { + initialize_server(); + let stream = "otel_regression_fields_limit"; + let limit = PARSEABLE.options.dataset_fields_allowed_limit; + let schema = (0..=limit) + .map(|i| { + let name = format!("f{i}"); + (name.clone(), Arc::new(Field::new(name, DataType::Utf8, true))) + }) + .collect(); + PARSEABLE.streams.get_or_create( + PARSEABLE.options.clone(), + stream.to_string(), + LogStreamMetadata { + schema, + schema_version: SchemaVersion::V1, + ..Default::default() + }, + None, + &None, + ); + for (telemetry_type, log_source, body) in [ + (TelemetryType::Logs, LogSource::OtelLogs, r#"{"resourceLogs":5}"#), + (TelemetryType::Metrics, LogSource::OtelMetrics, r#"{"resourceMetrics":5}"#), + (TelemetryType::Traces, LogSource::OtelTraces, r#"{"resourceSpans":5}"#), + ] { + let req = TestRequest::default() + .insert_header((CONTENT_TYPE, "application/json")) + .to_http_request(); + let refused = process_otel_content( + &req, + web::Bytes::from_static(body.as_bytes()), + stream, + &log_source, + telemetry_type, + ) + .await + .expect_err("refused"); + println!("REGRESSION field count before decoding, {log_source}: {refused}"); + assert!( + matches!(refused, PostError::FieldsCountLimitExceeded(..)), + "{log_source}: {refused:?}" + ); + } + PARSEABLE.streams.delete(stream, &None); +} diff --git a/src/otel/realistic_tests.rs b/src/otel/realistic_tests.rs index bea44775a..512b247c3 100644 --- a/src/otel/realistic_tests.rs +++ b/src/otel/realistic_tests.rs @@ -40,7 +40,7 @@ use prost::Message; use serde_json::{Map, Value}; use super::protobuf_stream::{Signal, flatten_request, max_record_bytes, outline}; -use super::sink::{RowSink, max_expanded_bytes, row_bytes}; +use super::sink::{EXPANSION_FACTOR, MIN_EXPANDED_BYTES, RowSink, max_expanded_bytes, row_bytes}; use crate::utils::json::flatten::{FlattenBudget, FlattenLimits, JsonFlattenError}; /// `P_MAX_EVENT_PAYLOAD_SIZE` default @@ -370,6 +370,8 @@ pub(crate) struct Shape { pub name: &'static str, pub signal: &'static str, pub body: Vec, + /// The same request with 1, 10 and 100 records + pub small: Vec>, } /// What the rows of a request add up to, as staging counts them @@ -443,7 +445,16 @@ fn shape( request = build(n); } let body = request.encode_to_vec(); - Shape { name, signal, body } + let small = [1, 10, 100] + .into_iter() + .map(|n| build(n).encode_to_vec()) + .collect(); + Shape { + name, + signal, + body, + small, + } } pub(crate) fn shapes() -> Vec { @@ -510,12 +521,12 @@ pub(crate) fn shapes() -> Vec { ] } -/// Every realistic shape at the payload limit is under the expansion cap, counted -/// as staging counts it: the `row_bytes` of every row +/// Every realistic shape at the payload limit is under the expansion cap for its +/// body with at least 8x headroom, counted as staging counts it: the `row_bytes` +/// of every row. So is the same shape with 1, 10 and 100 records. #[test] fn realistic_requests_at_the_payload_limit_are_under_the_expansion_cap() { use rayon::prelude::*; - let cap = max_expanded_bytes(PAYLOAD); let mut worst: f64 = 0.0; // Flattened at once: a few seconds each in a debug build let measured: Vec<(Shape, Totals)> = shapes() @@ -526,6 +537,7 @@ fn realistic_requests_at_the_payload_limit_are_under_the_expansion_cap() { }) .collect(); for (shape, totals) in measured { + let cap = max_expanded_bytes(shape.body.len()); let ratio = totals.bytes as f64 / shape.body.len() as f64; worst = worst.max(ratio); println!( @@ -538,11 +550,24 @@ fn realistic_requests_at_the_payload_limit_are_under_the_expansion_cap() { ratio, 100.0 * totals.bytes as f64 / cap as f64 ); - assert!(totals.bytes <= cap, "{} is refused", shape.name); + assert!(totals.bytes.saturating_mul(8) <= cap, "{} is under 8x headroom", shape.name); + for body in &shape.small { + let small = self::totals(shape.signal, body); + let ratio = small.bytes as f64 / body.len() as f64; + println!( + "EXPANSION {}, {} records: body {} B, {} row bytes, {ratio:.1} row bytes per body byte", + shape.name, small.records, body.len(), small.bytes + ); + assert!( + small.bytes.saturating_mul(8) <= max_expanded_bytes(body.len()), + "{} with {} records", + shape.name, + small.records + ); + } } println!( - "EXPANSION worst {worst:.1} row bytes per body byte, cap {} per body byte", - cap / PAYLOAD as u64 + "EXPANSION worst {worst:.1} row bytes per body byte, cap {EXPANSION_FACTOR} per body byte, at least {MIN_EXPANDED_BYTES}" ); } @@ -578,7 +603,7 @@ fn copied_fields_over_tiny_records_are_over_the_expansion_cap() { bytes as f64 / (1u64 << 30) as f64 ); assert!(request.encoded_len() <= PAYLOAD); - assert!(bytes > max_expanded_bytes(PAYLOAD)); + assert!(bytes > max_expanded_bytes(request.encoded_len())); } /// Writes the body of every shape to `OTLP_DUMP_DIR`, named after its signal diff --git a/src/otel/sink.rs b/src/otel/sink.rs index 6773baaa6..2cc03d15c 100644 --- a/src/otel/sink.rs +++ b/src/otel/sink.rs @@ -158,26 +158,37 @@ pub struct Staged { pub points: u64, } -/// Row bytes per payload byte one request may expand to: the rows of a request -/// may hold at most `EXPANSION_FACTOR` times `P_MAX_EVENT_PAYLOAD_SIZE` of -/// estimated memory ([`row_bytes`]) in all, counted while they are staged. +/// Row bytes per body byte one request may expand to: the rows of a request may +/// hold at most `EXPANSION_FACTOR` times the length of its body (decompressed) of +/// estimated memory ([`row_bytes`]) in all, counted while they are staged, and at +/// least [`MIN_EXPANDED_BYTES`]. /// /// Every row carries its own copy of the resource, scope, span and metric fields, /// so a small request can expand to a very large number of row bytes: 15 KB of /// resource attributes copied into each of 5 million two-byte log records is tens /// of GiB. Chunking bounds the memory this takes at once, not what is written to /// staging. The most measured for a request shaped like collector traffic is -/// below 500 (short log records or bare gauge points under 30 Kubernetes resource -/// attributes; ordinary k8s logs, spans and metrics expand 40-110x, see -/// `realistic_tests`), so 1024 leaves about 2x headroom, and stops the requests -/// that copy kilobytes of shared fields into millions of records of a few bytes, -/// at 10 GiB of rows for the default 10 MiB payload limit. -pub const EXPANSION_FACTOR: u64 = 1024; - -/// Estimated bytes of rows one request may expand to, for a payload limit of -/// `max_payload` bytes -pub fn max_expanded_bytes(max_payload: usize) -> u64 { - (max_payload as u64).saturating_mul(EXPANSION_FACTOR) +/// below 500 row bytes per body byte (short log records or bare gauge points under +/// 30 Kubernetes resource attributes; ordinary k8s logs, spans and metrics expand +/// 40-110x, see `realistic_tests`), and a request of such records expands less the +/// fewer records share its resource, so 4096 leaves at least 8x headroom at every +/// body size, and stops the requests that copy kilobytes of shared fields into +/// millions of records of a few bytes. +pub const EXPANSION_FACTOR: u64 = 4096; + +/// Estimated bytes of rows any request may expand to, whatever the length of its +/// body: one chunk. Below it the cap would only cut requests whose rows fit in one +/// chunk, whose memory the chunk limit bounds anyway. The bodies it decides for are +/// under 4 KiB, which realistic records expand to at most 2 MiB of rows (500 bytes +/// per body byte), 8x under it. +pub const MIN_EXPANDED_BYTES: u64 = CHUNK_LIMITS.bytes as u64; + +/// Estimated bytes of rows one request may expand to, for a body of `body_len` +/// bytes +pub fn max_expanded_bytes(body_len: usize) -> u64 { + (body_len as u64) + .saturating_mul(EXPANSION_FACTOR) + .max(MIN_EXPANDED_BYTES) } /// Collects rows into chunks and passes every full chunk to `stage`, with the From d9e52e339b622933bd284258219232b95b9fa858 Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Tue, 24 Nov 2026 02:39:14 -0600 Subject: [PATCH 18/31] test(otel): pin that outer protobuf levels are read in constant memory The security review found the request, resource and scope levels indexed before the first was read: a 10 MiB body of 5.2 million empty two-byte resource_logs entries held 384 MiB. At f0f75899 they are already walked as they are read; this pins it for empty resources and for empty scopes of one resource, for all three signals, in outline, flatten_request and count_points (peak at most 1.8 KB). Co-Authored-By: Claude Opus 5.5 --- src/otel/regression_tests.rs | 87 +++++++++++++++++++++++++++++++++++- 1 file changed, 86 insertions(+), 1 deletion(-) diff --git a/src/otel/regression_tests.rs b/src/otel/regression_tests.rs index eec0a7302..dbaf88a7c 100644 --- a/src/otel/regression_tests.rs +++ b/src/otel/regression_tests.rs @@ -17,11 +17,13 @@ */ //! Regression tests for what two reviews of chunked OTLP ingestion found: the -//! memory of rows whose shared maps were sized by repeated attribute keys. +//! memory of rows whose shared maps were sized by repeated attribute keys, and +//! the memory of walking a body of millions of empty resource or scope levels. //! Measured with the test allocator (layout bytes, calling thread). Each test //! prints `REGRESSION : ...`. None touches `PARSEABLE`, so they may be run //! with the name filter `otel::regression_tests`. +use bytes::Bytes; use opentelemetry_proto::tonic::collector::logs::v1::ExportLogsServiceRequest; use opentelemetry_proto::tonic::common::v1::{AnyValue, InstrumentationScope, KeyValue, any_value}; use opentelemetry_proto::tonic::logs::v1::{LogRecord, ResourceLogs, ScopeLogs}; @@ -32,6 +34,7 @@ use opentelemetry_proto::tonic::trace::v1::span::Event; use prost::Message as _; use serde_json::{Map, Value}; +use super::protobuf_stream::{Signal, count_points, flatten_request, max_record_bytes, outline}; use super::sink::{CHUNK_LIMITS, Chunker, RowSink, row_bytes}; use crate::test_alloc::measure; use crate::utils::json::flatten::{FlattenBudget, FlattenLimits, JsonFlattenError}; @@ -42,6 +45,9 @@ const MIB: usize = 1024 * 1024; /// as `memory_tests` states it: two chunks of rows and a little more const PEAK_BOUND: usize = 2 * CHUNK_LIMITS.bytes + 8 * MIB; +/// `P_MAX_EVENT_PAYLOAD_SIZE` default +const PAYLOAD: usize = 10 * MIB; + fn mb(bytes: impl TryInto) -> f64 { bytes.try_into().ok().unwrap() as f64 / MIB as f64 } @@ -288,3 +294,82 @@ fn rows_copied_from_maps_with_repeated_keys_hold_what_row_bytes_counts() { assert_eq!(rows, 1 << 16); assert!(allocated.peak <= PEAK_BOUND, "peak {:.1} MiB", mb(allocated.peak)); } + +/// A body of `count` two-byte empty entries of field 1 (`resource_logs`, +/// `resource_metrics`, `resource_spans`): every one an empty resource level +fn empty_resources(count: usize) -> Bytes { + Bytes::from([0x0a, 0x00].repeat(count)) +} + +/// One resource level holding `count` two-byte empty scope levels (field 2) +fn empty_scopes_in_one_resource(count: usize) -> Bytes { + let scopes = [0x12, 0x00].repeat(count); + let mut body = vec![0x0a]; + prost::encoding::encode_varint(scopes.len() as u64, &mut body); + body.extend_from_slice(&scopes); + Bytes::from(body) +} + +/// Security review finding 1: the outer levels of a protobuf body were indexed +/// (32 bytes per entry) before the first was read, so a 10 MiB body of 5.2 million +/// empty two-byte `resource_logs` entries held 384 MiB while it was answered 200. +/// The levels are walked as they are read: what reading a body holds for them does +/// not grow with how many there are, for empty resources and for empty scopes of +/// one resource, in every pass over the body. +#[test] +fn outer_levels_are_read_in_memory_independent_of_their_count() { + let max_record = max_record_bytes(PAYLOAD); + for (shape, body) in [ + ("empty resources", empty_resources(PAYLOAD / 2)), + ( + "empty scopes of one resource", + empty_scopes_in_one_resource((PAYLOAD - 8) / 2), + ), + ] { + assert!(body.len() <= PAYLOAD); + for (name, signal) in [ + ("logs", Signal::Logs), + ("metrics", Signal::Metrics), + ("traces", Signal::Traces), + ] { + let (read, outlined) = measure(|| outline(&body, signal).expect("the body decodes")); + let (rows, flattened) = measure(|| { + let mut rows = 0usize; + let mut chunker = Chunker::new(CHUNK_LIMITS, |chunk: Vec, _bytes: usize| { + rows += chunk.len(); + Ok::<_, JsonFlattenError>(()) + }); + flatten_request( + &body, + signal, + max_record, + &mut FlattenBudget::new(FlattenLimits::DEFAULT), + false, + &mut chunker, + ) + .map_err(|_| "flatten failed") + .and_then(|()| chunker.finish().map_err(|_| "staging failed")) + .unwrap(); + drop(chunker); + rows + }); + let (points, counted) = measure(|| count_points(&body)); + println!( + "REGRESSION outer levels, {shape}, {name}: body {:.1} MiB, {} records, {rows} rows, {points} points; peak: outline {} B, flatten_request {} B, count_points {} B", + mb(body.len()), + read.records, + outlined.peak, + flattened.peak, + counted.peak + ); + assert_eq!((read.records, rows, points), (0, 0, 0)); + for (pass, peak) in [ + ("outline", outlined.peak), + ("flatten_request", flattened.peak), + ("count_points", counted.peak), + ] { + assert!(peak < 64 * 1024, "{shape}, {name}: {pass} held {peak} B"); + } + } + } +} From f1411ec7c71f811abd94135da4aeb993bcb0877a Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Tue, 24 Nov 2026 02:39:14 -0600 Subject: [PATCH 19/31] docs(otel): correct what an exporter does after a 5xx once chunks are staged OTLP/HTTP exporters retry only 429, 502, 503 and 504. A 500 is permanent: the staged chunks stay and the client counts the batch as failed. Only a 503 makes the client send the whole request again. Co-Authored-By: Claude Opus 5.5 --- src/handlers/http/modal/utils/ingest_utils.rs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/handlers/http/modal/utils/ingest_utils.rs b/src/handlers/http/modal/utils/ingest_utils.rs index ac18806c3..11274a660 100644 --- a/src/handlers/http/modal/utils/ingest_utils.rs +++ b/src/handlers/http/modal/utils/ingest_utils.rs @@ -501,8 +501,12 @@ fn stage_otel_rows( /// staged in full as rejected, answered with status 200 as OTLP/HTTP requires. /// `total` gives the rejected unit for the whole request (log records, data /// points or spans), and is only asked for here; -/// - a server error keeps its 5xx status. The exporter then retries the whole -/// request, so the rows of the chunks already staged are staged twice. +/// - a server error keeps its 5xx status, and the chunks already staged stay +/// staged. OTLP/HTTP exporters retry only 429, 502, 503 and 504: after a 500 +/// (most staging errors) the client counts the whole batch as failed and does +/// not send it again, so the rows staged are kept but counted as not delivered; +/// after a 503 (some object storage errors) it sends the whole request again, +/// and the rows of the chunks already staged are staged twice. fn otel_outcome( signal: Signal, stream_name: &str, From e694900d21e8cff25e7aa3b82e757095c15f95d9 Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Tue, 24 Nov 2026 02:39:14 -0600 Subject: [PATCH 20/31] docs(otel): document that chunks are typed against the previous chunk's schema Each chunk of a request is staged as its own event and typed against the schema the chunk before it committed, so a value whose type changes between records of a request cut into several chunks can land in a differently named column than one batch would put it in, exactly as two separate requests would. Pinned with the reviewer's two cases. Co-Authored-By: Claude Opus 5.5 --- src/handlers/http/modal/utils/ingest_utils.rs | 9 ++ .../ingest_utils/otel_regression_tests.rs | 93 +++++++++++++++++++ 2 files changed, 102 insertions(+) diff --git a/src/handlers/http/modal/utils/ingest_utils.rs b/src/handlers/http/modal/utils/ingest_utils.rs index 11274a660..b7c6a3f0e 100644 --- a/src/handlers/http/modal/utils/ingest_utils.rs +++ b/src/handlers/http/modal/utils/ingest_utils.rs @@ -468,6 +468,15 @@ impl StageLimits { /// counted against `limits.max_expanded` as they go: the chunk that would pass /// it is refused with `expansion_error`, like any other chunk `stage` refuses. /// Stops at the first error. Needs no server state. +/// +/// Each chunk is staged as an event of its own, so its column types are inferred +/// against the schema the stream has then, which includes what the chunk before +/// it committed. When the type of a value changes between the records of a +/// request cut into several chunks, the value can land in a differently named +/// column than if the request were staged as one batch: `{"x": true}` then +/// `{"x": "on"}` give `x` (Boolean) and `x_utf8` in two chunks, but `x` (Utf8) +/// and `x_bool` in one. That is exactly what two separate requests give. A +/// request that fits in one chunk is staged as one batch. fn stage_otel_rows( limits: StageLimits, flatten: impl FnOnce( diff --git a/src/handlers/http/modal/utils/ingest_utils/otel_regression_tests.rs b/src/handlers/http/modal/utils/ingest_utils/otel_regression_tests.rs index 0421830de..b108671cc 100644 --- a/src/handlers/http/modal/utils/ingest_utils/otel_regression_tests.rs +++ b/src/handlers/http/modal/utils/ingest_utils/otel_regression_tests.rs @@ -22,9 +22,14 @@ //! ones that need the server are in `otel_server_state_tests`. use super::*; +use crate::metadata::SchemaVersion; +use arrow_schema::Field; use opentelemetry_proto::tonic::common::v1::{AnyValue, KeyValue, any_value}; use opentelemetry_proto::tonic::logs::v1::{LogRecord, ScopeLogs}; use opentelemetry_proto::tonic::resource::v1::Resource; +use serde_json::json; +use std::collections::BTreeMap; +use std::sync::Arc; const MIB: usize = 1024 * 1024; @@ -129,3 +134,91 @@ fn a_small_body_expanding_past_4096_times_its_length_is_refused() { ); assert!(staged_bytes <= limits.max_expanded); } + +/// Columns staged for `rows`, as one batch or in chunks of `chunk` rows, each +/// chunk typed against the schema the chunks before it committed, as a stream's +/// schema is +fn staged_columns(rows: &[Value], chunk: usize) -> Vec<(String, String, Vec)> { + use crate::event::format::{EventFormat as _, json as json_format}; + let mut storage: HashMap> = HashMap::new(); + let mut cells: BTreeMap)> = BTreeMap::new(); + for part in rows.chunks(chunk) { + let (rb, _) = json_format::Event { + json: Value::Array(part.to_vec()), + p_timestamp: chrono::Utc::now(), + } + .into_recordbatch( + &storage, + false, + None, + SchemaVersion::V1, + &HashMap::new(), + true, + ) + .unwrap(); + for (i, field) in rb.schema().fields().iter().enumerate() { + if field.name() == "p_timestamp" { + continue; + } + storage.insert(field.name().clone(), field.clone()); + let column = rb.column(i); + let entry = cells + .entry(field.name().clone()) + .or_insert_with(|| (format!("{:?}", field.data_type()), Vec::new())); + for row in 0..rb.num_rows() { + entry.1.push( + arrow::util::display::array_value_to_string(column, row).unwrap_or_default(), + ); + } + } + } + cells + .into_iter() + .map(|(name, (ty, values))| (name, ty, values)) + .collect() +} + +/// Review finding 3, kept as documented behaviour: each chunk of a request is +/// typed against the schema the chunk before it committed, so a value whose type +/// changes between the records of a request that is cut into chunks can land in +/// a differently named column than one batch would put it in, exactly as two +/// separate requests would. Requests that fit in one chunk are not affected. +#[test] +fn a_type_change_between_chunks_lands_where_a_second_request_would_put_it() { + let columns = |columns: &[(String, String, Vec)]| { + columns + .iter() + .map(|(name, ty, values)| format!("{name}:{ty}:{}", values.join("|"))) + .collect::>() + }; + let cases = [ + ( + vec![json!({"x": true, "n": 1}), json!({"x": "on", "n": 2})], + ["n:Float64:1.0|2.0", "x:Utf8:|on", "x_bool:Boolean:true|"], + ["n:Float64:1.0|2.0", "x:Boolean:true", "x_utf8:Utf8:on"], + ), + ( + vec![ + json!({"http_status_code": 200, "n": 1}), + json!({"http_status_code": "OK", "n": 2}), + ], + [ + "http_status_code:Utf8:|OK", + "http_status_code_int64:Float64:200.0|", + "n:Float64:1.0|2.0", + ], + [ + "http_status_code:Float64:200.0", + "http_status_code_utf8:Utf8:OK", + "n:Float64:1.0|2.0", + ], + ), + ]; + for (rows, one_batch, two_chunks) in cases { + let whole = columns(&staged_columns(&rows, rows.len())); + let chunked = columns(&staged_columns(&rows, 1)); + println!("REGRESSION type change: one batch {whole:?}, two chunks {chunked:?}"); + assert_eq!(whole, one_batch); + assert_eq!(chunked, two_chunks); + } +} From 18ef4448da759abe4fb17f5e350ca195e4fa7624 Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Tue, 24 Nov 2026 02:39:14 -0600 Subject: [PATCH 21/31] test(otel): confirm the expansion total counts the Prometheus labels in full The security review found the sizing pass charged job and instance at 32 bytes each while they copy service.name and service.instance.id. There is no sizing pass any more: the running total is the row_bytes of the staged rows, labels included. With a 64 KiB service.name each row counts 133,889 bytes and the request stops at the cap. Co-Authored-By: Claude Opus 5.5 --- .../ingest_utils/otel_regression_tests.rs | 89 ++++++++++++++++++- 1 file changed, 88 insertions(+), 1 deletion(-) diff --git a/src/handlers/http/modal/utils/ingest_utils/otel_regression_tests.rs b/src/handlers/http/modal/utils/ingest_utils/otel_regression_tests.rs index b108671cc..aecba5fc4 100644 --- a/src/handlers/http/modal/utils/ingest_utils/otel_regression_tests.rs +++ b/src/handlers/http/modal/utils/ingest_utils/otel_regression_tests.rs @@ -23,11 +23,16 @@ use super::*; use crate::metadata::SchemaVersion; +use crate::otel::sink::RowSink; +use crate::utils::json::flatten::JsonFlattenError; use arrow_schema::Field; use opentelemetry_proto::tonic::common::v1::{AnyValue, KeyValue, any_value}; use opentelemetry_proto::tonic::logs::v1::{LogRecord, ScopeLogs}; +use opentelemetry_proto::tonic::metrics::v1::{ + Gauge, Metric, NumberDataPoint, ScopeMetrics, metric, number_data_point, +}; use opentelemetry_proto::tonic::resource::v1::Resource; -use serde_json::json; +use serde_json::{Map, json}; use std::collections::BTreeMap; use std::sync::Arc; @@ -222,3 +227,85 @@ fn a_type_change_between_chunks_lands_where_a_second_request_would_put_it() { assert_eq!(chunked, two_chunks); } } + +/// Security review finding 2: the sizing pass charged the Prometheus `job` and +/// `instance` labels at 32 bytes, but they hold copies of `service.name` and +/// `service.instance.id`. There is no sizing pass any more: the running total is +/// the `row_bytes` of every staged row, labels included at their real size, so a +/// request whose labels are long is refused where its rows pass the cap. +#[test] +fn expansion_total_counts_the_prometheus_identity_labels_at_their_size() { + const LABEL: usize = 64 * 1024; + let label = LABEL; + let points = 13_000usize; + let resource_metrics = vec![ResourceMetrics { + resource: Some(Resource { + attributes: vec![kv("service.name", "n".repeat(label))], + ..Default::default() + }), + scope_metrics: vec![ScopeMetrics { + metrics: vec![Metric { + name: "m".into(), + data: Some(metric::Data::Gauge(Gauge { + data_points: (0..points) + .map(|i| NumberDataPoint { + time_unix_nano: 1_700_000_000_000_000_000 + i as u64, + start_time_unix_nano: 1_700_000_000_000_000_000, + value: Some(number_data_point::Value::AsDouble(1.0)), + ..Default::default() + }) + .collect(), + })), + ..Default::default() + }], + ..Default::default() + }], + ..Default::default() + }]; + + /// Keeps the `row_bytes` of the first row + #[derive(Default)] + struct First(Option); + impl RowSink for First { + type Error = JsonFlattenError; + fn row(&mut self, row: Map) -> Result<(), Self::Error> { + assert_eq!(row["job"], json!("n".repeat(LABEL))); + self.0.get_or_insert(crate::otel::sink::row_bytes(&row)); + Err(JsonFlattenError::CannotFlatten) + } + } + let mut first = First::default(); + let _ = flatten_metrics_into(&resource_metrics, false, &mut first); + let per_row = first.0.unwrap() as u64; + + let max_expanded = 1u64 << 30; + let limits = StageLimits { + chunk: CHUNK_LIMITS, + max_expanded, + flatten: FlattenLimits::DEFAULT, + }; + let mut staged_bytes = 0u64; + let (outcome, staged) = stage_otel_resources( + OtelResources::Metrics(&resource_metrics), + false, + limits, + |rows| { + staged_bytes += rows + .iter() + .map(|row| crate::otel::sink::row_bytes(row.as_object().unwrap()) as u64) + .sum::(); + Ok(()) + }, + ); + println!( + "REGRESSION identity labels: {per_row} row bytes per row ({label} B label twice), staged {} of {points} rows, {staged_bytes} B, cap {max_expanded} B, outcome {:?}", + staged.rows, + outcome.as_ref().map_err(|e| e.to_string()) + ); + // `service.name` and its copy in `job`, each at its real size + assert!(per_row > 2 * label as u64); + assert!(matches!(outcome, Ok(OtelIngested::Partial { .. }))); + assert!(staged_bytes <= max_expanded); + // Stopped by the cap, not before it: one more chunk would have passed it + assert!(staged_bytes + CHUNK_LIMITS.bytes as u64 + per_row > max_expanded); +} From 31dacf5391900012315b27754fa87bc9f18c5989 Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Tue, 24 Nov 2026 02:48:17 -0600 Subject: [PATCH 22/31] style(otel): format the regression tests, name their row builder type Co-Authored-By: Claude Opus 5.5 --- src/handlers/http/modal/utils/ingest_utils.rs | 3 +- .../ingest_utils/otel_server_state_tests.rs | 27 +++++++--- src/otel/logs.rs | 29 ++++++++--- src/otel/memory_tests.rs | 6 ++- src/otel/realistic_tests.rs | 11 ++++- src/otel/regression_tests.rs | 49 ++++++++++++++++--- 6 files changed, 98 insertions(+), 27 deletions(-) diff --git a/src/handlers/http/modal/utils/ingest_utils.rs b/src/handlers/http/modal/utils/ingest_utils.rs index b7c6a3f0e..91b48a0e3 100644 --- a/src/handlers/http/modal/utils/ingest_utils.rs +++ b/src/handlers/http/modal/utils/ingest_utils.rs @@ -937,7 +937,8 @@ pub fn flatten_and_push_logs( // The body's length, as the expansion cap counts it, is that of the // JSON text of the value let body_len = json_byte_size(&json) as usize; - if let OtelIngested::Partial { message, .. } = ingest_otel_json(json, body_len, &target)? + if let OtelIngested::Partial { message, .. } = + ingest_otel_json(json, body_len, &target)? { return Err(PostError::Invalid(anyhow::Error::msg(message))); } diff --git a/src/handlers/http/modal/utils/ingest_utils/otel_server_state_tests.rs b/src/handlers/http/modal/utils/ingest_utils/otel_server_state_tests.rs index 044164a81..5baea4be9 100644 --- a/src/handlers/http/modal/utils/ingest_utils/otel_server_state_tests.rs +++ b/src/handlers/http/modal/utils/ingest_utils/otel_server_state_tests.rs @@ -46,9 +46,7 @@ fn initialize_server() { crate::parseable::Parseable::new( crate::cli::Options::default(), #[cfg(feature = "kafka")] - ::parse_from([ - "otel", - ]), + ::parse_from(["otel"]), provider, metastore, storage, @@ -109,7 +107,10 @@ async fn otlp_json_checks_the_field_count_before_decoding() { let schema = (0..=limit) .map(|i| { let name = format!("f{i}"); - (name.clone(), Arc::new(Field::new(name, DataType::Utf8, true))) + ( + name.clone(), + Arc::new(Field::new(name, DataType::Utf8, true)), + ) }) .collect(); PARSEABLE.streams.get_or_create( @@ -124,9 +125,21 @@ async fn otlp_json_checks_the_field_count_before_decoding() { &None, ); for (telemetry_type, log_source, body) in [ - (TelemetryType::Logs, LogSource::OtelLogs, r#"{"resourceLogs":5}"#), - (TelemetryType::Metrics, LogSource::OtelMetrics, r#"{"resourceMetrics":5}"#), - (TelemetryType::Traces, LogSource::OtelTraces, r#"{"resourceSpans":5}"#), + ( + TelemetryType::Logs, + LogSource::OtelLogs, + r#"{"resourceLogs":5}"#, + ), + ( + TelemetryType::Metrics, + LogSource::OtelMetrics, + r#"{"resourceMetrics":5}"#, + ), + ( + TelemetryType::Traces, + LogSource::OtelTraces, + r#"{"resourceSpans":5}"#, + ), ] { let req = TestRequest::default() .insert_header((CONTENT_TYPE, "application/json")) diff --git a/src/otel/logs.rs b/src/otel/logs.rs index 19066ec64..ec4329e9a 100644 --- a/src/otel/logs.rs +++ b/src/otel/logs.rs @@ -285,7 +285,13 @@ fn json_object_text_bytes(text: &str) -> Option { if len == 0 { return 0; } - let fits = |buckets: usize| if buckets < 8 { buckets - 1 } else { buckets / 8 * 7 }; + let fits = |buckets: usize| { + if buckets < 8 { + buckets - 1 + } else { + buckets / 8 * 7 + } + }; let mut buckets = 4usize; while fits(buckets) < len { buckets = buckets.saturating_mul(2); @@ -1261,17 +1267,24 @@ mod tests { /// to, and the old block of the last growth, which a reallocation holds too. #[test] fn parsed_body_estimate_covers_what_parsing_holds() { - let mut shapes: Vec<(String, String)> = [1usize, 3, 4, 7, 8, 15, 100, 1000, 100_000, 400_000] - .into_iter() - .map(|n| (format!("object of {n} fields"), many_fields(n))) - .collect(); + let mut shapes: Vec<(String, String)> = + [1usize, 3, 4, 7, 8, 15, 100, 1000, 100_000, 400_000] + .into_iter() + .map(|n| (format!("object of {n} fields"), many_fields(n))) + .collect(); for n in [1usize, 4, 5, 1000, 262_145] { let numbers = vec!["0"; n].join(","); shapes.push((format!("{n} numbers"), format!(r#"{{"a":[{numbers}]}}"#))); let singles = vec!["[0]"; n].join(","); - shapes.push((format!("{n} one-number arrays"), format!(r#"{{"a":[{singles}]}}"#))); + shapes.push(( + format!("{n} one-number arrays"), + format!(r#"{{"a":[{singles}]}}"#), + )); let objects = vec![r#"{"k":"v","n":1}"#; n].join(","); - shapes.push((format!("{n} small objects"), format!(r#"{{"a":[{objects}]}}"#))); + shapes.push(( + format!("{n} small objects"), + format!(r#"{{"a":[{objects}]}}"#), + )); } for n in [1000usize, 1_000_000] { // Escapes are unescaped into a scratch buffer while parsing @@ -1282,7 +1295,7 @@ mod tests { } shapes.push(( "nested objects".into(), - format!("{}{}", r#"{"a":"#.repeat(100), format!("0{}", "}".repeat(100))), + format!("{}0{}", r#"{"a":"#.repeat(100), "}".repeat(100)), )); let mut under = Vec::new(); for (name, text) in shapes { diff --git a/src/otel/memory_tests.rs b/src/otel/memory_tests.rs index de37aa03a..f5dc92b73 100644 --- a/src/otel/memory_tests.rs +++ b/src/otel/memory_tests.rs @@ -273,7 +273,11 @@ fn json_text_log_body_is_not_parsed_into_unbounded_memory() { }; let mut budget = FlattenBudget::new(FlattenLimits::DEFAULT); let (result, allocated) = hand_over("10 MiB JSON text body", logs(&request, &mut budget)); - assert_eq!(result.unwrap().rows, 1, "the record is kept, its body as text"); + assert_eq!( + result.unwrap().rows, + 1, + "the record is kept, its body as text" + ); // The row holds copies of the body text, nothing parsed from it assert!( allocated.peak < PEAK_BOUND + 3 * body_len, diff --git a/src/otel/realistic_tests.rs b/src/otel/realistic_tests.rs index 512b247c3..a57334ff3 100644 --- a/src/otel/realistic_tests.rs +++ b/src/otel/realistic_tests.rs @@ -550,13 +550,20 @@ fn realistic_requests_at_the_payload_limit_are_under_the_expansion_cap() { ratio, 100.0 * totals.bytes as f64 / cap as f64 ); - assert!(totals.bytes.saturating_mul(8) <= cap, "{} is under 8x headroom", shape.name); + assert!( + totals.bytes.saturating_mul(8) <= cap, + "{} is under 8x headroom", + shape.name + ); for body in &shape.small { let small = self::totals(shape.signal, body); let ratio = small.bytes as f64 / body.len() as f64; println!( "EXPANSION {}, {} records: body {} B, {} row bytes, {ratio:.1} row bytes per body byte", - shape.name, small.records, body.len(), small.bytes + shape.name, + small.records, + body.len(), + small.bytes ); assert!( small.bytes.saturating_mul(8) <= max_expanded_bytes(body.len()), diff --git a/src/otel/regression_tests.rs b/src/otel/regression_tests.rs index dbaf88a7c..7aada16fd 100644 --- a/src/otel/regression_tests.rs +++ b/src/otel/regression_tests.rs @@ -97,6 +97,9 @@ impl RowSink for Last { } } +/// Builds one row into a `Last` +type BuildRow = Box; + /// Bytes the row built by `build` holds once built, and its `row_bytes` fn held_and_estimated(build: impl FnOnce(&mut Last)) -> (isize, usize) { let mut last = Last::default(); @@ -148,7 +151,7 @@ fn rows_copied_from_maps_with_repeated_keys_hold_what_row_bytes_counts() { attributes }; - let mut cases: Vec<(&str, Box)> = Vec::new(); + let mut cases: Vec<(&str, BuildRow)> = Vec::new(); for (level, resource_attributes, scope_attributes) in [ ("resource", repeated_keys(), vec![]), ("scope", vec![], repeated_keys()), @@ -162,7 +165,8 @@ fn rows_copied_from_maps_with_repeated_keys_hold_what_row_bytes_counts() { "logs, scope" }, Box::new(move |sink: &mut Last| { - let resource_fields = super::logs::resource_log_fields(resource(ra.clone()).as_ref(), ""); + let resource_fields = + super::logs::resource_log_fields(resource(ra.clone()).as_ref(), ""); let scope_fields = super::logs::scope_log_fields(scope(sa.clone()).as_ref(), ""); let row = super::logs::log_record_row( &record, @@ -205,7 +209,8 @@ fn rows_copied_from_maps_with_repeated_keys_hold_what_row_bytes_counts() { resource(resource_attributes.clone()).as_ref(), "", ); - let scope_fields = super::traces::scope_span_fields(scope(scope_attributes.clone()).as_ref()); + let scope_fields = + super::traces::scope_span_fields(scope(scope_attributes.clone()).as_ref()); super::traces::span_rows( &span, &super::traces::SpanParents { @@ -220,10 +225,34 @@ fn rows_copied_from_maps_with_repeated_keys_hold_what_row_bytes_counts() { )); } for (name, resource_attributes, scope_attributes, metadata, target_info) in [ - ("metrics, resource", with_identity(repeated_keys()), vec![], vec![], false), - ("metrics, resource, target_info row", with_identity(repeated_keys()), vec![], vec![], true), - ("metrics, scope", with_identity(vec![]), repeated_keys(), vec![], false), - ("metrics, metric metadata", with_identity(vec![]), vec![], repeated_keys(), false), + ( + "metrics, resource", + with_identity(repeated_keys()), + vec![], + vec![], + false, + ), + ( + "metrics, resource, target_info row", + with_identity(repeated_keys()), + vec![], + vec![], + true, + ), + ( + "metrics, scope", + with_identity(vec![]), + repeated_keys(), + vec![], + false, + ), + ( + "metrics, metric metadata", + with_identity(vec![]), + vec![], + repeated_keys(), + false, + ), ] { let metric = gauge(metadata); cases.push(( @@ -292,7 +321,11 @@ fn rows_copied_from_maps_with_repeated_keys_hold_what_row_bytes_counts() { ); assert!(failed.is_empty(), "rows hold over 2x row_bytes: {failed:?}"); assert_eq!(rows, 1 << 16); - assert!(allocated.peak <= PEAK_BOUND, "peak {:.1} MiB", mb(allocated.peak)); + assert!( + allocated.peak <= PEAK_BOUND, + "peak {:.1} MiB", + mb(allocated.peak) + ); } /// A body of `count` two-byte empty entries of field 1 (`resource_logs`, From 2266bc1ce8ff0ec77671dbae821610284a6d15a5 Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Tue, 24 Nov 2026 03:49:11 -0600 Subject: [PATCH 23/31] test(otel): pin the rows of a seeded corpus of generated OTLP requests The bench digests and the JSON-versus-protobuf properties cannot show that a flattener change keeps rows identical: the bench covers one request shape, and both sides of the properties run the same flattener. This corpus generates 3000 requests per signal from a fixed SplitMix64 seed, every timestamp set, and pins one digest per signal over the rows serialised in order (key order included, since it decides column order). The generator covers attribute keys that collide with the fixed row fields of all three signals and with each other across resource, scope, record, event, link and data point; one key repeated many times in a list; attributes without a value; string, bool, int, double (including 1e20, -0.0, NaN, infinity), bytes (invalid UTF-8 too), arrays and key-value lists, nested three deep; missing and empty resources and scopes; log bodies of every kind including JSON text; every metric type, exemplars and metadata, a metric with data but no points; spans with up to 80 events and 40 links. Metrics are flattened with and without exemplar flattening. Digests at this commit: logs 13,819 rows 5247f2af863c6427, metrics 42,718 rows b299fcc3bdad0047, traces 65,400 rows 2f813bb532c511a5. Each of these mutations changed the digests it should, so the corpus reaches them: resource fields not overriding a log record's fields, span fields not overriding an event's, metric metadata not overriding a data point's (all three digests); the first of repeated attribute keys winning (all three); a double label hashed with Rust's float formatting (metrics). DST_SEED and DST_ITERS change the corpus; the digests are checked only for the defaults. The tests do not touch PARSEABLE. Co-Authored-By: Claude Opus 5.5 --- src/otel.rs | 2 + src/otel/corpus_tests.rs | 691 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 693 insertions(+) create mode 100644 src/otel/corpus_tests.rs diff --git a/src/otel.rs b/src/otel.rs index 93b8b3864..4f2855e95 100644 --- a/src/otel.rs +++ b/src/otel.rs @@ -24,6 +24,8 @@ pub mod protobuf_stream; pub mod sink; pub mod traces; +#[cfg(test)] +mod corpus_tests; #[cfg(test)] mod memory_tests; #[cfg(test)] diff --git a/src/otel/corpus_tests.rs b/src/otel/corpus_tests.rs new file mode 100644 index 000000000..19bcbd935 --- /dev/null +++ b/src/otel/corpus_tests.rs @@ -0,0 +1,691 @@ +/* + * Parseable Server (C) 2022 - 2025 Parseable, Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + */ + +//! Seeded corpus of generated OTLP requests, pinning the rows the flatteners +//! make for every signal. A change to the flatteners that is meant to be a pure +//! speedup must leave every digest here unchanged: the rows, their values and +//! the order of the keys inside each row (which decides column order). +//! +//! The generator aims at what the benchmark requests do not reach: attribute +//! keys that collide with fixed row fields and with each other across resource, +//! scope, record, event, link and data point; repeated keys inside one list; +//! attributes without a value; every `AnyValue` kind, nested; empty and missing +//! scopes and resources; log bodies of every kind including JSON text; every +//! metric type with exemplars and metadata; spans with many events and links. +//! Every timestamp is set, so rows do not depend on the clock. +//! +//! Conventions follow the DST harness: SplitMix64, `DST_SEED` and `DST_ITERS` +//! override the seed and the request count (the pinned digests are checked +//! only for the defaults), and the seed is printed. None of these tests touches +//! `PARSEABLE`, so they may be run with the filter `otel::corpus_tests`. + +use opentelemetry_proto::tonic::common::v1::{ + AnyValue, ArrayValue, InstrumentationScope, KeyValue, KeyValueList, any_value, +}; +use opentelemetry_proto::tonic::logs::v1::{LogRecord, ResourceLogs, ScopeLogs}; +use opentelemetry_proto::tonic::metrics::v1::{ + Exemplar, ExponentialHistogram, ExponentialHistogramDataPoint, Gauge, Histogram, + HistogramDataPoint, Metric, NumberDataPoint, ResourceMetrics, ScopeMetrics, Sum, Summary, + SummaryDataPoint, exemplar, exponential_histogram_data_point, metric, number_data_point, + summary_data_point, +}; +use opentelemetry_proto::tonic::resource::v1::Resource; +use opentelemetry_proto::tonic::trace::v1::span::{Event, Link}; +use opentelemetry_proto::tonic::trace::v1::{ResourceSpans, ScopeSpans, Span, Status}; +use serde_json::Value; + +use crate::utils::json::flatten::{FlattenBudget, FlattenLimits}; + +const DEFAULT_SEED: u64 = 0x0071_9c0d_5eed_2026; +const DEFAULT_ITERS: usize = 3000; + +/// SplitMix64, as the DST harness uses +struct Rng(u64); + +impl Rng { + fn next(&mut self) -> u64 { + self.0 = self.0.wrapping_add(0x9e37_79b9_7f4a_7c15); + let mut z = self.0; + z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9); + z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb); + z ^ (z >> 31) + } + + /// A number in `0..n` + fn below(&mut self, n: usize) -> usize { + (self.next() % n as u64) as usize + } + + /// True with probability `percent` in 100 + fn chance(&mut self, percent: usize) -> bool { + self.below(100) < percent + } + + fn pick<'a, T>(&mut self, items: &'a [T]) -> &'a T { + &items[self.below(items.len())] + } + + /// A nonzero timestamp, so the flatteners never read the clock + fn timestamp(&mut self) -> u64 { + match self.below(4) { + 0 => 1, + 1 => 1_700_000_000_000_000_000 + self.below(1_000_000_000) as u64, + 2 => u64::MAX - self.below(1000) as u64, + _ => 1 + self.next() % (i64::MAX as u64), + } + } + + fn id(&mut self) -> Vec { + let len = *self.pick(&[0usize, 8, 16, 3]); + (0..len).map(|_| self.next() as u8).collect() + } +} + +/// Keys every signal can collide with: its own fixed row fields, generic keys +/// shared across levels, and keys a flattened JSON body or key-value list makes +fn key_pool() -> Vec<&'static str> { + let mut keys: Vec<&'static str> = vec![ + "k", + "a", + "a.b", + "service.name", + "host.name", + "body", + "body_a", + "body_k", + "p_timestamp", + "p_log_category", + "", + "ключ", + "le", + "quantile", + ]; + keys.extend(super::logs::OTEL_LOG_KNOWN_FIELD_LIST); + keys.extend(super::traces::OTEL_TRACES_KNOWN_FIELD_LIST); + keys.extend(super::metrics::OTEL_METRICS_KNOWN_FIELD_LIST); + keys +} + +const TEXTS: [&str; 14] = [ + "", + "v", + "INFO", + "warn", + "Error", + "UNSPECIFIED", + "fatal: disk full", + "ünïcödé ✓", + "{\"a\":1,\"b\":{\"c\":[1,2,{\"d\":null}]},\"k\":\"x\"}", + "{\"severity_text\":\"x\",\"body\":true,\"nested\":{\"deep\":{\"deeper\":[[1],[2]]}}}", + "{}", + "[1,2,3]", + "{\"a\":", + "null", +]; + +const DOUBLES: [f64; 12] = [ + 0.0, + -0.0, + 1.5, + -2.25, + 1e20, + 1e21, + 1e-7, + 123456789.125, + f64::MAX, + f64::MIN_POSITIVE, + f64::NAN, + f64::INFINITY, +]; + +struct Gen { + rng: Rng, + keys: Vec<&'static str>, +} + +impl Gen { + fn key(&mut self) -> String { + // A small pool for most keys, so lists repeat keys and levels collide + if self.rng.chance(85) { + let index = self.rng.below(self.keys.len().min(24)); + self.keys[index].to_string() + } else { + self.rng.pick(&self.keys).to_string() + } + } + + fn text(&mut self) -> String { + if self.rng.chance(80) { + self.rng.pick(&TEXTS).to_string() + } else { + format!("s{}", self.rng.next() % 1000) + } + } + + fn any_value(&mut self, depth: usize) -> AnyValue { + AnyValue { + value: self.value(depth), + } + } + + fn value(&mut self, depth: usize) -> Option { + let kinds = if depth == 0 { 6 } else { 8 }; + Some(match self.rng.below(kinds + 1) { + 0 => return None, + 1 => any_value::Value::StringValue(self.text()), + 2 => any_value::Value::BoolValue(self.rng.chance(50)), + 3 => { + let random = self.rng.next() as i64; + any_value::Value::IntValue(*self.rng.pick(&[0, -1, 42, i64::MIN, i64::MAX, random])) + } + 4 => any_value::Value::DoubleValue(*self.rng.pick(&DOUBLES)), + 5 => { + let len = self.rng.below(6); + let mut bytes: Vec = (0..len).map(|_| self.rng.next() as u8).collect(); + if self.rng.chance(30) { + bytes.extend_from_slice(b"ok"); + } + any_value::Value::BytesValue(bytes) + } + 6 => any_value::Value::StringValue(self.rng.pick(&TEXTS[8..]).to_string()), + 7 => any_value::Value::ArrayValue(ArrayValue { + values: (0..self.rng.below(5)) + .map(|_| self.any_value(depth - 1)) + .collect(), + }), + _ => any_value::Value::KvlistValue(KeyValueList { + values: self.attributes_up_to(4, depth - 1), + }), + }) + } + + fn attribute(&mut self, depth: usize) -> KeyValue { + KeyValue { + key: self.key(), + value: if self.rng.chance(10) { + None + } else { + Some(self.any_value(depth)) + }, + ..Default::default() + } + } + + fn attributes_up_to(&mut self, max: usize, depth: usize) -> Vec { + let len = self.rng.below(max + 1); + let mut attributes: Vec = (0..len).map(|_| self.attribute(depth)).collect(); + // Sometimes one key many times over + if self.rng.chance(5) { + let key = self.key(); + for _ in 0..self.rng.below(40) { + let mut attribute = self.attribute(depth); + attribute.key = key.clone(); + attributes.push(attribute); + } + } + attributes + } + + fn attributes(&mut self) -> Vec { + self.attributes_up_to(8, 3) + } + + fn resource(&mut self) -> Option { + match self.rng.below(5) { + 0 => None, + 1 => Some(Resource::default()), + _ => Some(Resource { + attributes: self.attributes(), + dropped_attributes_count: self.rng.below(3) as u32, + ..Default::default() + }), + } + } + + fn scope(&mut self) -> Option { + match self.rng.below(5) { + 0 => None, + 1 => Some(InstrumentationScope::default()), + _ => Some(InstrumentationScope { + name: self.text(), + version: self.text(), + attributes: self.attributes(), + dropped_attributes_count: self.rng.below(3) as u32, + }), + } + } + + fn schema_url(&mut self) -> String { + if self.rng.chance(50) { + String::new() + } else { + "https://opentelemetry.io/schemas/1.21.0".into() + } + } + + fn count(&mut self, max: usize) -> usize { + self.rng.below(max + 1) + } + + fn log_record(&mut self) -> LogRecord { + LogRecord { + time_unix_nano: self.rng.timestamp(), + observed_time_unix_nano: self.rng.timestamp(), + severity_number: self.rng.below(28) as i32 - 1, + severity_text: self.text(), + body: match self.rng.below(6) { + 0 => None, + 1 => Some(AnyValue { + value: Some(any_value::Value::StringValue( + self.rng.pick(&TEXTS[8..]).to_string(), + )), + }), + _ => Some(self.any_value(3)), + }, + attributes: self.attributes(), + dropped_attributes_count: self.rng.below(3) as u32, + flags: *self.rng.pick(&[0u32, 1, 255, 256, 7]), + trace_id: self.rng.id(), + span_id: self.rng.id(), + event_name: self.text(), + } + } + + fn logs(&mut self) -> Vec { + (0..self.count(3)) + .map(|_| ResourceLogs { + resource: self.resource(), + scope_logs: (0..self.count(3)) + .map(|_| ScopeLogs { + scope: self.scope(), + log_records: (0..self.count(4)).map(|_| self.log_record()).collect(), + schema_url: self.schema_url(), + }) + .collect(), + schema_url: self.schema_url(), + }) + .collect() + } + + fn event(&mut self) -> Event { + Event { + time_unix_nano: self.rng.timestamp(), + name: self.text(), + attributes: self.attributes_up_to(4, 2), + dropped_attributes_count: self.rng.below(3) as u32, + } + } + + fn link(&mut self) -> Link { + Link { + trace_id: self.rng.id(), + span_id: self.rng.id(), + trace_state: self.text(), + attributes: self.attributes_up_to(4, 2), + dropped_attributes_count: self.rng.below(3) as u32, + flags: *self.rng.pick(&[0u32, 1, 256, 512, 769]), + } + } + + fn span(&mut self) -> Span { + // Most spans have a few events and links; some have many + let (events, links) = if self.rng.chance(5) { + (20 + self.count(60), 10 + self.count(30)) + } else { + (self.count(3), self.count(2)) + }; + Span { + trace_id: self.rng.id(), + span_id: self.rng.id(), + trace_state: self.text(), + parent_span_id: self.rng.id(), + flags: *self.rng.pick(&[0u32, 255, 256, 512, 1, 769]), + name: self.text(), + kind: self.rng.below(8) as i32 - 1, + start_time_unix_nano: self.rng.timestamp(), + end_time_unix_nano: self.rng.timestamp(), + attributes: self.attributes(), + dropped_attributes_count: self.rng.below(3) as u32, + events: (0..events).map(|_| self.event()).collect(), + dropped_events_count: self.rng.below(3) as u32, + links: (0..links).map(|_| self.link()).collect(), + dropped_links_count: self.rng.below(3) as u32, + status: if self.rng.chance(30) { + None + } else { + Some(Status { + message: self.text(), + code: self.rng.below(5) as i32 - 1, + }) + }, + } + } + + fn traces(&mut self) -> Vec { + (0..self.count(3)) + .map(|_| ResourceSpans { + resource: self.resource(), + scope_spans: (0..self.count(3)) + .map(|_| ScopeSpans { + scope: self.scope(), + spans: (0..self.count(3)).map(|_| self.span()).collect(), + schema_url: self.schema_url(), + }) + .collect(), + schema_url: self.schema_url(), + }) + .collect() + } + + fn double(&mut self) -> f64 { + *self.rng.pick(&DOUBLES) + } + + fn option_double(&mut self) -> Option { + self.rng.chance(70).then(|| self.double()) + } + + fn exemplars(&mut self) -> Vec { + (0..self.count(3)) + .map(|_| Exemplar { + filtered_attributes: self.attributes_up_to(4, 2), + time_unix_nano: self.rng.timestamp(), + span_id: self.rng.id(), + trace_id: self.rng.id(), + value: match self.rng.below(3) { + 0 => None, + 1 => Some(exemplar::Value::AsInt(self.rng.next() as i64)), + _ => Some(exemplar::Value::AsDouble(self.double())), + }, + }) + .collect() + } + + fn number_points(&mut self) -> Vec { + (0..self.count(4)) + .map(|_| NumberDataPoint { + attributes: self.attributes(), + start_time_unix_nano: self.rng.timestamp(), + time_unix_nano: self.rng.timestamp(), + exemplars: self.exemplars(), + flags: self.rng.below(3) as u32, + value: match self.rng.below(3) { + 0 => None, + 1 => Some(number_data_point::Value::AsInt(self.rng.next() as i64)), + _ => Some(number_data_point::Value::AsDouble(self.double())), + }, + }) + .collect() + } + + fn counts(&mut self) -> Vec { + (0..self.count(5)) + .map(|_| self.rng.below(100) as u64) + .collect() + } + + fn metric(&mut self) -> Metric { + let temporality = self.rng.below(4) as i32; + let data = match self.rng.below(7) { + 0 => None, + 1 => Some(metric::Data::Gauge(Gauge { + data_points: self.number_points(), + })), + 2 => Some(metric::Data::Sum(Sum { + data_points: self.number_points(), + aggregation_temporality: temporality, + is_monotonic: self.rng.chance(50), + })), + 3 => Some(metric::Data::Histogram(Histogram { + data_points: (0..self.count(3)) + .map(|_| HistogramDataPoint { + attributes: self.attributes(), + start_time_unix_nano: self.rng.timestamp(), + time_unix_nano: self.rng.timestamp(), + count: self.rng.below(1000) as u64, + sum: self.option_double(), + bucket_counts: self.counts(), + explicit_bounds: (0..self.count(4)).map(|_| self.double()).collect(), + exemplars: self.exemplars(), + flags: self.rng.below(3) as u32, + min: self.option_double(), + max: self.option_double(), + }) + .collect(), + aggregation_temporality: temporality, + })), + 4 => Some(metric::Data::ExponentialHistogram(ExponentialHistogram { + data_points: (0..self.count(3)) + .map(|_| ExponentialHistogramDataPoint { + attributes: self.attributes(), + start_time_unix_nano: self.rng.timestamp(), + time_unix_nano: self.rng.timestamp(), + count: self.rng.below(1000) as u64, + sum: self.option_double(), + scale: self.rng.below(20) as i32 - 10, + zero_count: self.rng.below(10) as u64, + positive: self.rng.chance(70).then(|| { + exponential_histogram_data_point::Buckets { + offset: self.rng.below(10) as i32 - 5, + bucket_counts: self.counts(), + } + }), + negative: self.rng.chance(50).then(|| { + exponential_histogram_data_point::Buckets { + offset: self.rng.below(10) as i32 - 5, + bucket_counts: self.counts(), + } + }), + flags: self.rng.below(3) as u32, + exemplars: self.exemplars(), + min: self.option_double(), + max: self.option_double(), + zero_threshold: self.double(), + }) + .collect(), + aggregation_temporality: temporality, + })), + 5 => Some(metric::Data::Summary(Summary { + data_points: (0..self.count(3)) + .map(|_| SummaryDataPoint { + attributes: self.attributes(), + start_time_unix_nano: self.rng.timestamp(), + time_unix_nano: self.rng.timestamp(), + count: self.rng.below(1000) as u64, + sum: self.double(), + quantile_values: (0..self.count(4)) + .map(|_| summary_data_point::ValueAtQuantile { + quantile: self.double(), + value: self.double(), + }) + .collect(), + flags: self.rng.below(3) as u32, + }) + .collect(), + })), + // Data with no data points + _ => Some(metric::Data::Gauge(Gauge { + data_points: Vec::new(), + })), + }; + Metric { + name: self.text(), + description: self.text(), + unit: self.text(), + metadata: self.attributes_up_to(4, 2), + data, + } + } + + fn metrics(&mut self) -> Vec { + (0..self.count(3)) + .map(|_| ResourceMetrics { + resource: self.resource(), + scope_metrics: (0..self.count(3)) + .map(|_| ScopeMetrics { + scope: self.scope(), + metrics: (0..self.count(4)).map(|_| self.metric()).collect(), + schema_url: self.schema_url(), + }) + .collect(), + schema_url: self.schema_url(), + }) + .collect() + } +} + +/// FNV-1a over everything written, independent of any crate's hasher +struct Digest { + hash: u64, + rows: usize, + bytes: usize, +} + +impl Digest { + fn new() -> Self { + Self { + hash: 0xcbf2_9ce4_8422_2325, + rows: 0, + bytes: 0, + } + } + + fn write(&mut self, bytes: &[u8]) { + for byte in bytes { + self.hash ^= u64::from(*byte); + self.hash = self.hash.wrapping_mul(0x0000_0100_0000_01b3); + } + self.bytes += bytes.len(); + } + + /// The rows of one request in order, each with its keys in order, or the + /// error that stopped it + fn request(&mut self, rows: &[Value], result: Result<(), E>) { + for row in rows { + self.write(&serde_json::to_vec(row).unwrap()); + self.write(b"\n"); + self.rows += 1; + } + if let Err(error) = result { + self.write(format!("error: {error}\n").as_bytes()); + } + self.write(b"--\n"); + } +} + +fn settings() -> (u64, usize, bool) { + let seed = std::env::var("DST_SEED").ok().map(|seed| { + let seed = seed.trim(); + seed.strip_prefix("0x") + .map_or_else(|| seed.parse(), |hex| u64::from_str_radix(hex, 16)) + .expect("DST_SEED is a number") + }); + let iters = std::env::var("DST_ITERS") + .ok() + .map(|iters| iters.parse().expect("DST_ITERS is a number")); + let pinned = seed.is_none_or(|seed| seed == DEFAULT_SEED) + && iters.is_none_or(|iters| iters == DEFAULT_ITERS); + ( + seed.unwrap_or(DEFAULT_SEED), + iters.unwrap_or(DEFAULT_ITERS), + pinned, + ) +} + +/// Runs `signal` over the corpus and checks its digest against `expected` (rows, +/// bytes, digest) when the default seed and count are used +fn check( + signal: &str, + salt: u64, + expected: (usize, usize, u64), + mut run: impl FnMut(&mut Gen, &mut Digest), +) { + let (seed, iters, pinned) = settings(); + let mut generator = Gen { + rng: Rng(seed ^ salt), + keys: key_pool(), + }; + let mut digest = Digest::new(); + for _ in 0..iters { + run(&mut generator, &mut digest); + } + println!( + "CORPUS {signal}: seed {seed:#x}, {iters} requests, {} rows, {} bytes, digest {:016x}", + digest.rows, digest.bytes, digest.hash + ); + if pinned { + assert_eq!( + (digest.rows, digest.bytes, digest.hash), + expected, + "rows of the {signal} corpus changed (seed {seed:#x})" + ); + } +} + +#[test] +fn seeded_corpus_log_rows_are_stable() { + check( + "logs", + 1, + (13_819, 8_786_447, 0x5247_f2af_863c_6427), + |generator, digest| { + let request = generator.logs(); + let mut rows = Vec::new(); + let result = super::logs::flatten_logs_into( + &request, + &mut FlattenBudget::new(FlattenLimits::DEFAULT), + &mut rows, + ); + digest.request(&rows, result); + }, + ); +} + +#[test] +fn seeded_corpus_metric_rows_are_stable() { + check( + "metrics", + 2, + (42_718, 40_623_570, 0xb299_fcc3_bdad_0047), + |generator, digest| { + let request = generator.metrics(); + // Both exemplar modes over the same request + for flatten_exemplars in [false, true] { + let mut rows = Vec::new(); + let result = + super::metrics::flatten_metrics_into(&request, flatten_exemplars, &mut rows); + digest.request(&rows, result); + } + }, + ); +} + +#[test] +fn seeded_corpus_trace_rows_are_stable() { + check( + "traces", + 3, + (65_400, 83_307_143, 0x2f81_3bb5_32c5_11a5), + |generator, digest| { + let request = generator.traces(); + let mut rows = Vec::new(); + let result = super::traces::flatten_traces_into(&request, &mut rows); + digest.request(&rows, result); + }, + ); +} From 6c8c5072219ed03587de8a976eb34aaa2ad87dc1 Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Tue, 24 Nov 2026 03:52:19 -0600 Subject: [PATCH 24/31] test(otel): measure record-level maps with repeated keys against row_bytes The repeated-keys regression test covered the maps that are cloned into rows (resource, scope, span, metric metadata). Add the maps that are rows themselves: a log record's own fields, a span event, a span link and a metric data point, each with 128 attributes of one key. Measured at 98ae3903 (held/estimated): log record 1.19, under the 2x bound like the shared maps. Event 3.09, link 3.25 and data point 5.03 are already over it: those maps are sized from their own attribute count, repeats included, which the fix in e77e6b51 left alone (their slack is bounded by the record's wire bytes). They get bounds just above those values so the slack cannot grow unnoticed; fitting them is a separate change. Co-Authored-By: Claude Opus 5.5 --- src/otel/regression_tests.rs | 93 +++++++++++++++++++++++++++++++++--- 1 file changed, 87 insertions(+), 6 deletions(-) diff --git a/src/otel/regression_tests.rs b/src/otel/regression_tests.rs index 7aada16fd..0934bcc2d 100644 --- a/src/otel/regression_tests.rs +++ b/src/otel/regression_tests.rs @@ -30,7 +30,7 @@ use opentelemetry_proto::tonic::logs::v1::{LogRecord, ResourceLogs, ScopeLogs}; use opentelemetry_proto::tonic::metrics::v1::{Gauge, Metric, NumberDataPoint, metric}; use opentelemetry_proto::tonic::resource::v1::Resource; use opentelemetry_proto::tonic::trace::v1::Span; -use opentelemetry_proto::tonic::trace::v1::span::Event; +use opentelemetry_proto::tonic::trace::v1::span::{Event, Link}; use prost::Message as _; use serde_json::{Map, Value}; @@ -113,6 +113,12 @@ fn held_and_estimated(build: impl FnOnce(&mut Last)) -> (isize, usize) { /// capacity, so a row cloned from such a map held about 10x what `row_bytes` /// counts (a scope of 128 attributes with one key: 25,917 B against 2,613 B). /// Every shared map now holds no more than its entries need before it is cloned. +/// +/// The same holds for a log record's own fields. Span event, span link and metric +/// data point rows are still sized from their own attribute count, repeats +/// included: their slack is bounded by the record's wire bytes and was left +/// alone. They are held to what they measured when this was written (at +/// `98ae3903`: 3.09, 3.25 and 5.03 held/estimated) so that it does not grow. #[test] fn rows_copied_from_maps_with_repeated_keys_hold_what_row_bytes_counts() { let record = LogRecord { @@ -135,11 +141,12 @@ fn rows_copied_from_maps_with_repeated_keys_hold_what_row_bytes_counts() { }], ..span.clone() }; - let gauge = |metadata: Vec| Metric { + let gauge = |metadata: Vec, attributes: Vec| Metric { name: "m".into(), metadata, data: Some(metric::Data::Gauge(Gauge { data_points: vec![NumberDataPoint { + attributes, time_unix_nano: 1_700_000_000_000_000_000, ..Default::default() }], @@ -180,6 +187,31 @@ fn rows_copied_from_maps_with_repeated_keys_hold_what_row_bytes_counts() { }), )); } + // The record's own map is the row (or becomes it), so it must not keep the + // room its repeated keys were counted for either + let repeated_record = LogRecord { + attributes: repeated_keys(), + ..record.clone() + }; + cases.push(( + "logs, record", + Box::new(move |sink: &mut Last| { + let resource_fields = super::logs::resource_log_fields( + resource(vec![kv("service.name", "api")]).as_ref(), + "", + ); + let scope_fields = super::logs::scope_log_fields(scope(vec![]).as_ref(), ""); + let row = super::logs::log_record_row( + &repeated_record, + &scope_fields, + &resource_fields, + &mut FlattenBudget::new(FlattenLimits::DEFAULT), + ) + .unwrap(); + drop((resource_fields, scope_fields)); + sink.row(row).unwrap(); + }), + )); for (name, resource_attributes, scope_attributes, span) in [ ("traces, resource", repeated_keys(), vec![], span.clone()), ("traces, scope", vec![], repeated_keys(), span.clone()), @@ -201,6 +233,34 @@ fn rows_copied_from_maps_with_repeated_keys_hold_what_row_bytes_counts() { ..span_with_event.clone() }, ), + ( + "traces, event", + vec![kv("service.name", "api")], + vec![], + Span { + attributes: vec![kv("http.method", "GET")], + events: vec![Event { + attributes: repeated_keys(), + ..span_with_event.events[0].clone() + }], + ..span.clone() + }, + ), + ( + "traces, link", + vec![kv("service.name", "api")], + vec![], + Span { + attributes: vec![kv("http.method", "GET")], + links: vec![Link { + trace_id: vec![3; 16], + span_id: vec![4; 8], + attributes: repeated_keys(), + ..Default::default() + }], + ..span.clone() + }, + ), ] { cases.push(( name, @@ -224,12 +284,13 @@ fn rows_copied_from_maps_with_repeated_keys_hold_what_row_bytes_counts() { }), )); } - for (name, resource_attributes, scope_attributes, metadata, target_info) in [ + for (name, resource_attributes, scope_attributes, metadata, point, target_info) in [ ( "metrics, resource", with_identity(repeated_keys()), vec![], vec![], + vec![], false, ), ( @@ -237,6 +298,7 @@ fn rows_copied_from_maps_with_repeated_keys_hold_what_row_bytes_counts() { with_identity(repeated_keys()), vec![], vec![], + vec![], true, ), ( @@ -244,6 +306,7 @@ fn rows_copied_from_maps_with_repeated_keys_hold_what_row_bytes_counts() { with_identity(vec![]), repeated_keys(), vec![], + vec![], false, ), ( @@ -251,10 +314,19 @@ fn rows_copied_from_maps_with_repeated_keys_hold_what_row_bytes_counts() { with_identity(vec![]), vec![], repeated_keys(), + vec![], + false, + ), + ( + "metrics, data point", + with_identity(vec![]), + vec![], + vec![], + repeated_keys(), false, ), ] { - let metric = gauge(metadata); + let metric = gauge(metadata, point); cases.push(( name, Box::new(move |sink: &mut Last| { @@ -281,7 +353,13 @@ fn rows_copied_from_maps_with_repeated_keys_hold_what_row_bytes_counts() { println!( "REGRESSION repeated keys, {name}: row holds {held} B, row_bytes {estimated} B, held/estimated {ratio:.2}" ); - if ratio > 2.0 { + let bound = match *name { + "traces, event" => 3.2, + "traces, link" => 3.35, + "metrics, data point" => 5.15, + _ => 2.0, + }; + if ratio > bound { failed.push(*name); } } @@ -319,7 +397,10 @@ fn rows_copied_from_maps_with_repeated_keys_hold_what_row_bytes_counts() { mb(allocated.peak), mb(PEAK_BOUND) ); - assert!(failed.is_empty(), "rows hold over 2x row_bytes: {failed:?}"); + assert!( + failed.is_empty(), + "rows hold more than their bound over row_bytes: {failed:?}" + ); assert_eq!(rows, 1 << 16); assert!( allocated.peak <= PEAK_BOUND, From 9846231f0ee5df2b600cb8901907af6108d4b94d Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Tue, 24 Nov 2026 02:39:39 -0600 Subject: [PATCH 25/31] perf(otel): hash the metric series identity without copying its labels compute_series_hash ran once per data point. It collected every label as a Cow: a non-string label (an int or bool attribute, a start time) was formatted into its own String, so one row allocated one string per such label. The known-field set was a SipHash HashSet, the sort was stable, and the hash was written from the Cow text. Collect &Value references instead and hash a number from a reused buffer with the same bytes Value::to_string prints; look up a known field in an FxHashSet; sort unstably (keys are unique). The hash value is unchanged: the metrics rows digest f12385b9f510100b still passes. Flatten benchmark, instructions:u per row, A/B/B/A x 4 on one box, OTEL_BENCH_ITERS 10 vs 110: metrics 69,741-69,780 -> 63,382-63,383 (-9.1%). Logs and traces do not call this function. Verified by Claude Opus 5.5 on top of 98ae3903: the hash bytes are the same for every label kind (serde_json prints a Number through the same itoa/zmij formatters in Display and in Value::to_string; bool, null, arrays and objects unchanged); the unstable sort only sees distinct map keys; FxHashSet comes from rustc-hash, already a dependency. The seeded corpus digests (logs 5247f2af863c6427, metrics b299fcc3bdad0047, traces 2f813bb532c511a5) and bench digests unchanged; a mutation hashing doubles with Rust's float formatting changes the metrics corpus digest, so double labels are covered. Memory tests unchanged. Release flatten bench, instructions:u per row, A/B/B/A x 4 against 98ae3903: metrics 69,734-69,760 -> 63,317 (-9.2%); logs and traces 0.00%. Co-Authored-By: DeepSeek V4.1 Flash 1017 Co-Authored-By: Claude Opus 5.5 --- src/otel/metrics.rs | 41 +++++++++++++++++++++++++++++------------ 1 file changed, 29 insertions(+), 12 deletions(-) diff --git a/src/otel/metrics.rs b/src/otel/metrics.rs index 5523dbaa2..022ea1151 100644 --- a/src/otel/metrics.rs +++ b/src/otel/metrics.rs @@ -27,9 +27,7 @@ use opentelemetry_proto::tonic::metrics::v1::{ use opentelemetry_proto::tonic::resource::v1::Resource; use serde_json::{Map, Value}; -use rustc_hash::FxHasher; -use std::borrow::Cow; -use std::collections::HashSet; +use rustc_hash::{FxHashSet, FxHasher}; use std::hash::Hasher; use tracing::info_span; @@ -96,7 +94,7 @@ pub const OTEL_METRICS_KNOWN_FIELD_LIST: [&str; 39] = [ SERIES_HASH_COLUMN, ]; -static OTEL_METRICS_KNOWN_FIELDS: Lazy> = +static OTEL_METRICS_KNOWN_FIELDS: Lazy> = Lazy::new(|| OTEL_METRICS_KNOWN_FIELD_LIST.iter().copied().collect()); const SERVICE_NAME_ATTRIBUTE: &str = "service.name"; @@ -178,33 +176,52 @@ fn target_info_record( /// non-cryptographic) and feeds keys in sorted order so the hash /// doesn't depend on JSON Map iteration order. pub fn compute_series_hash(dp: &Map) -> u64 { - let mut label_pairs: Vec<(&str, Cow<'_, str>)> = Vec::with_capacity(dp.len()); + // Only references are collected: a non-string label is hashed as the text + // `Value` would print, not formatted into a string first (that allocated + // one string per non-string label of every data point). + let mut label_pairs: Vec<(&str, &Value)> = Vec::with_capacity(dp.len()); + let mut metric_name: Option<&str> = None; for (key, value) in dp { + if key == "metric_name" + && let Value::String(name) = value + { + metric_name = Some(name.as_str()); + } if OTEL_METRICS_KNOWN_FIELDS.contains(key.as_str()) { continue; } if key.starts_with("exemplars_") { continue; } - let value = match value { - Value::String(s) => Cow::Borrowed(s.as_str()), - other => Cow::Owned(other.to_string()), - }; label_pairs.push((key.as_str(), value)); } - label_pairs.sort_by(|a, b| a.0.cmp(b.0)); + // Keys are unique, so an unstable sort leaves the same order + label_pairs.sort_unstable_by(|a, b| a.0.cmp(b.0)); let mut hasher = FxHasher::default(); // Include metric_name in the identity. Without it, two different // metrics with identical label sets would collide into one series. - if let Some(Value::String(name)) = dp.get("metric_name") { + if let Some(name) = metric_name { hasher.write(name.as_bytes()); hasher.write(b"\0"); } + let mut number = String::new(); for (k, v) in &label_pairs { hasher.write(k.as_bytes()); hasher.write(b"="); - hasher.write(v.as_bytes()); + match v { + Value::String(s) => hasher.write(s.as_bytes()), + Value::Bool(b) => hasher.write(if *b { b"true" } else { b"false" }), + Value::Null => hasher.write(b"null"), + Value::Number(n) => { + // `Value` prints a number as this `Display` does + number.clear(); + std::fmt::Write::write_fmt(&mut number, format_args!("{n}")).unwrap(); + hasher.write(number.as_bytes()); + } + // An array or object, as `Value` prints it + other => hasher.write(other.to_string().as_bytes()), + } hasher.write(b"\0"); } hasher.finish() From 711fd00f4ce8a21473b2a35109a818ac48b88689 Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Tue, 24 Nov 2026 02:45:38 -0600 Subject: [PATCH 26/31] perf(otel): size each row map for every field merged into it A row is built by merging maps one after the other, and serde_json's Map has no reserve: every merge could rehash the whole row. A 60-entry trace row grew two or three times, and `reserve_rehash` was 4.1% of the traces flatten benchmark, 4.6% of metrics and 4.1% of logs. Size the map for all the entries it will hold, from the lengths of the maps merged into it, then fill it without growing: - logs: `log_record_row` sizes the row for scope + record + resource fields and clones the two shared maps in entry by entry, instead of cloning the scope map and extending it. - traces: `event_row`, `link_row` and `flatten_span_fields` take the number of scope, schema URL, resource and span fields that are merged over them; `SpanParents::finish` inserts the resource fields one by one instead of cloning the resource map first. - metrics: `metric_rows` takes the envelope length and passes it through the data point row builders, which add the metric fields' size to their capacity. `event_row` also stops copying the 30-byte event timestamp it just formatted (`.to_string()` on a String). Flatten benchmark, instructions:u per row, A/B/B/A x 4 on one box, OTEL_BENCH_ITERS 10 vs 110, spread under 0.06%: logs 68,585-68,590 -> 66,275 (-3.4%); traces 93,148 -> 85,803 (-7.9%); metrics on top of the previous commit 63,382 -> 58,247 (-8.1%), against f0f75899 69,730-69,826 -> 58,247 (-16.5%). The rows digests a4cec43f538fd2cd, f12385b9f510100b and a2c661dfe91e9cde still pass. Changed in verification (Claude Opus 5.5, on top of 98ae3903): sizing a span event, span link or metric data point row for the merged fields made the room counted for repeated attribute keys stay empty: with 128 attributes of one key those rows went from 3.09/3.25/5.03 to 3.56/3.76/5.43 times what row_bytes counts. The fields merged later used to fill that room. Those rows now give it back like the shared maps do since e77e6b51 (`insert_attributes_fitted`, and `fit_map` for the prefixed event and link attributes), which also fixes the old excess: 0.85/0.88/0.89. The span map counted 40 fixed slots that already allowed for the scope and resource fields, so adding them again left span rows at 1.42; it now counts its 20 own fields (0.87). The repeated-keys regression test covers these rows at the 2x bound. The rustfmt of the original 6242f2b1 is folded in. Verified: seeded corpus digests (logs 5247f2af863c6427, metrics b299fcc3bdad0047, traces 2f813bb532c511a5) and bench digests unchanged. Memory tests (peak, bound 40 MiB), 98ae3903 -> this commit: events of one span 14.8 -> 13.6 MiB, links 16.2 -> 14.4, points 15.2 -> 15.2, tiny copied fields 20.7 -> 12.6, repeated-key request 21.8 -> 13.7. Row allocated/estimated: realistic 1.02 -> 0.80, tiny fields 1.25 -> 0.77 (rows are no longer grown by doubling, so they hold less than row_bytes counts). Release flatten bench, instructions:u per row, A/B/B/A x 4 against 98ae3903, on top of the previous commit: logs 68,923-68,928 -> 66,553 (-3.4%), metrics 63,317 -> 58,334 (-7.9%), traces 93,296 -> 85,809 (-8.0%). Co-Authored-By: DeepSeek V4.1 Flash 1017 Co-Authored-By: Claude Opus 5.5 --- src/otel/logs.rs | 8 +++-- src/otel/metrics.rs | 59 ++++++++++++++++++++++++------------ src/otel/otel_utils.rs | 9 +++++- src/otel/regression_tests.rs | 20 +++--------- src/otel/traces.rs | 58 ++++++++++++++++++++++++----------- 5 files changed, 98 insertions(+), 56 deletions(-) diff --git a/src/otel/logs.rs b/src/otel/logs.rs index ec4329e9a..62a4dbb9c 100644 --- a/src/otel/logs.rs +++ b/src/otel/logs.rs @@ -569,9 +569,13 @@ pub fn log_record_row( budget: &mut FlattenBudget, ) -> Result, JsonFlattenError> { let log_record_json = flatten_log_record(log_record, budget)?; - let mut row = scope_fields.clone(); + // Sized so that the two merges below never have to grow the map: a growth + // rehashes every entry of the row. + let mut row = + Map::with_capacity(scope_fields.len() + log_record_json.len() + resource_fields.len()); + row.extend(scope_fields.iter().map(|(k, v)| (k.clone(), v.clone()))); row.extend(log_record_json); - row.extend(resource_fields.clone()); + row.extend(resource_fields.iter().map(|(k, v)| (k.clone(), v.clone()))); Ok(row) } diff --git a/src/otel/metrics.rs b/src/otel/metrics.rs index 022ea1151..416363938 100644 --- a/src/otel/metrics.rs +++ b/src/otel/metrics.rs @@ -316,13 +316,16 @@ fn insert_exemplars(map: &mut Map, exemplars: &[Exemplar], flatte } } -/// The own fields of the row of one number data point (gauge or sum) +/// The own fields of the row of one number data point (gauge or sum); `extra` is +/// the capacity the metric and envelope fields merged over it will take fn number_data_point_row( data_point: &NumberDataPoint, flatten_exemplars: bool, + extra: usize, ) -> Map { - let mut data_point_json = Map::with_capacity(attribute_capacity(&data_point.attributes) + 8); - insert_attributes(&mut data_point_json, &data_point.attributes); + let capacity = attribute_capacity(&data_point.attributes) + 8 + extra; + let mut data_point_json = Map::with_capacity(capacity); + insert_attributes_fitted(&mut data_point_json, &data_point.attributes, capacity); data_point_json.insert( "start_time_unix_nano".to_string(), Value::String(convert_epoch_nano_to_timestamp( @@ -369,8 +372,9 @@ fn sum_data_point_row( sum: &Sum, data_point: &NumberDataPoint, flatten_exemplars: bool, + extra: usize, ) -> Map { - let mut dp = number_data_point_row(data_point, flatten_exemplars); + let mut dp = number_data_point_row(data_point, flatten_exemplars, extra); insert_aggregation_temporality(&mut dp, sum.aggregation_temporality); dp.insert("is_monotonic".to_string(), Value::Bool(sum.is_monotonic)); dp @@ -381,9 +385,11 @@ fn histogram_data_point_row( histogram: &Histogram, data_point: &HistogramDataPoint, flatten_exemplars: bool, + extra: usize, ) -> Map { - let mut data_point_json = Map::with_capacity(attribute_capacity(&data_point.attributes) + 10); - insert_attributes(&mut data_point_json, &data_point.attributes); + let capacity = attribute_capacity(&data_point.attributes) + 10 + extra; + let mut data_point_json = Map::with_capacity(capacity); + insert_attributes_fitted(&mut data_point_json, &data_point.attributes, capacity); data_point_json.insert( "start_time_unix_nano".to_string(), Value::String(convert_epoch_nano_to_timestamp( @@ -464,9 +470,11 @@ fn exp_histogram_data_point_row( exp_histogram: &ExponentialHistogram, data_point: &ExponentialHistogramDataPoint, flatten_exemplars: bool, + extra: usize, ) -> Map { - let mut data_point_json = Map::with_capacity(attribute_capacity(&data_point.attributes) + 12); - insert_attributes(&mut data_point_json, &data_point.attributes); + let capacity = attribute_capacity(&data_point.attributes) + 12 + extra; + let mut data_point_json = Map::with_capacity(capacity); + insert_attributes_fitted(&mut data_point_json, &data_point.attributes, capacity); data_point_json.insert( "start_time_unix_nano".to_string(), Value::String(convert_epoch_nano_to_timestamp( @@ -515,9 +523,10 @@ fn exp_histogram_data_point_row( } /// The own fields of the row of one summary data point -fn summary_data_point_row(data_point: &SummaryDataPoint) -> Map { - let mut data_point_json = Map::with_capacity(attribute_capacity(&data_point.attributes) + 6); - insert_attributes(&mut data_point_json, &data_point.attributes); +fn summary_data_point_row(data_point: &SummaryDataPoint, extra: usize) -> Map { + let capacity = attribute_capacity(&data_point.attributes) + 6 + extra; + let mut data_point_json = Map::with_capacity(capacity); + insert_attributes_fitted(&mut data_point_json, &data_point.attributes, capacity); data_point_json.insert( "start_time_unix_nano".to_string(), Value::String(convert_epoch_nano_to_timestamp( @@ -600,10 +609,13 @@ impl MetricFields { /// Hands the rows of one metric to `emit` one at a time: one per data point, each /// built once the one before it was handed over, or one for a metric that has data -/// but no data points. A metric without data has no rows. +/// but no data points. A metric without data has no rows. `merged` is the number of +/// fields the caller merges over every row after this (a scope's envelope); rows +/// are sized for them so that merging never has to grow a row map. pub fn metric_rows( metrics_record: &Metric, flatten_exemplars: bool, + merged: usize, mut emit: impl FnMut(MetricRow) -> Result<(), E>, ) -> Result<(), E> { let Some(data) = &metrics_record.data else { @@ -628,13 +640,16 @@ pub fn metric_rows( metric_type: Value::String(metric_type.to_string()), metadata, }; + let extra = 4 + fields.metadata.len() + merged; let points = match data { metric::Data::Gauge(gauge) => { for dp in &gauge.data_points { - emit(MetricRow::Point( - fields.apply(number_data_point_row(dp, flatten_exemplars)), - ))?; + emit(MetricRow::Point(fields.apply(number_data_point_row( + dp, + flatten_exemplars, + extra, + ))))?; } gauge.data_points.len() } @@ -644,6 +659,7 @@ pub fn metric_rows( sum, dp, flatten_exemplars, + extra, ))))?; } sum.data_points.len() @@ -654,6 +670,7 @@ pub fn metric_rows( histogram, dp, flatten_exemplars, + extra, ))))?; } histogram.data_points.len() @@ -661,14 +678,16 @@ pub fn metric_rows( metric::Data::ExponentialHistogram(exp_histogram) => { for dp in &exp_histogram.data_points { emit(MetricRow::Point(fields.apply( - exp_histogram_data_point_row(exp_histogram, dp, flatten_exemplars), + exp_histogram_data_point_row(exp_histogram, dp, flatten_exemplars, extra), )))?; } exp_histogram.data_points.len() } metric::Data::Summary(summary) => { for dp in &summary.data_points { - emit(MetricRow::Point(fields.apply(summary_data_point_row(dp))))?; + emit(MetricRow::Point( + fields.apply(summary_data_point_row(dp, extra)), + ))?; } summary.data_points.len() } @@ -682,7 +701,7 @@ pub fn metric_rows( metric_type, metadata, } = fields; - let mut single = Map::with_capacity(metadata.len() + 8); + let mut single = Map::with_capacity(metadata.len() + 8 + merged); single.insert("metric_name".to_string(), name); single.insert("metric_description".to_string(), description); single.insert("metric_unit".to_string(), unit); @@ -716,7 +735,7 @@ pub fn flatten_metrics_record( ) -> Vec> { let mut rows = Vec::new(); let Ok(()) = - metric_rows::(metrics_record, flatten_exemplars, |row| { + metric_rows::(metrics_record, flatten_exemplars, 0, |row| { rows.push(match row { MetricRow::Point(row) | MetricRow::NoPoints(row) => row, }); @@ -822,7 +841,7 @@ pub fn metric_rows_into( latest: &mut Option, sink: &mut S, ) -> Result<(), S::Error> { - metric_rows(metric, flatten_exemplars, |row| { + metric_rows(metric, flatten_exemplars, envelope.len(), |row| { let (mut dp, point) = match row { MetricRow::Point(dp) => (dp, true), MetricRow::NoPoints(dp) => (dp, false), diff --git a/src/otel/otel_utils.rs b/src/otel/otel_utils.rs index 8c6864556..a5bd4dc49 100644 --- a/src/otel/otel_utils.rs +++ b/src/otel/otel_utils.rs @@ -300,7 +300,14 @@ pub fn insert_attributes_fitted( let counted = attribute_capacity(attributes); let before = map.len(); insert_attributes(map, attributes); - let added = map.len().saturating_sub(before); + fit_map(map, capacity, counted, map.len().saturating_sub(before)); +} + +/// Rebuilds `map`, created with room for `capacity` entries of which `counted` +/// were for entries that only `added` turned out to make (repeated keys, or keys +/// its own fields already had), with room for that many fewer. Does nothing when +/// `added` is at least `counted`, so attributes with distinct keys rebuild nothing. +pub fn fit_map(map: &mut Map, capacity: usize, counted: usize, added: usize) { if added < counted { let mut fitted = Map::with_capacity(capacity.saturating_sub(counted - added)); fitted.extend(std::mem::take(map)); diff --git a/src/otel/regression_tests.rs b/src/otel/regression_tests.rs index 0934bcc2d..3f4f6745c 100644 --- a/src/otel/regression_tests.rs +++ b/src/otel/regression_tests.rs @@ -114,11 +114,8 @@ fn held_and_estimated(build: impl FnOnce(&mut Last)) -> (isize, usize) { /// counts (a scope of 128 attributes with one key: 25,917 B against 2,613 B). /// Every shared map now holds no more than its entries need before it is cloned. /// -/// The same holds for a log record's own fields. Span event, span link and metric -/// data point rows are still sized from their own attribute count, repeats -/// included: their slack is bounded by the record's wire bytes and was left -/// alone. They are held to what they measured when this was written (at -/// `98ae3903`: 3.09, 3.25 and 5.03 held/estimated) so that it does not grow. +/// The same holds for the maps that are rows themselves: a log record's own +/// fields, a span event, a span link and a metric data point. #[test] fn rows_copied_from_maps_with_repeated_keys_hold_what_row_bytes_counts() { let record = LogRecord { @@ -353,13 +350,7 @@ fn rows_copied_from_maps_with_repeated_keys_hold_what_row_bytes_counts() { println!( "REGRESSION repeated keys, {name}: row holds {held} B, row_bytes {estimated} B, held/estimated {ratio:.2}" ); - let bound = match *name { - "traces, event" => 3.2, - "traces, link" => 3.35, - "metrics, data point" => 5.15, - _ => 2.0, - }; - if ratio > bound { + if ratio > 2.0 { failed.push(*name); } } @@ -397,10 +388,7 @@ fn rows_copied_from_maps_with_repeated_keys_hold_what_row_bytes_counts() { mb(allocated.peak), mb(PEAK_BOUND) ); - assert!( - failed.is_empty(), - "rows hold more than their bound over row_bytes: {failed:?}" - ); + assert!(failed.is_empty(), "rows hold over 2x row_bytes: {failed:?}"); assert_eq!(rows, 1 << 16); assert!( allocated.peak <= PEAK_BOUND, diff --git a/src/otel/traces.rs b/src/otel/traces.rs index 468cf23f9..fc1331d65 100644 --- a/src/otel/traces.rs +++ b/src/otel/traces.rs @@ -32,6 +32,7 @@ use crate::otel::otel_utils::flatten_attributes; use super::otel_utils::attribute_capacity; use super::otel_utils::convert_epoch_nano_to_timestamp; +use super::otel_utils::fit_map; use super::otel_utils::insert_attributes_fitted; use super::sink::RowSink; @@ -124,7 +125,9 @@ impl SpanParents<'_> { "scope_schema_url".to_string(), Value::String(self.scope_schema_url.to_string()), ); - row.extend(self.resource_fields.clone()); + for (key, value) in self.resource_fields { + row.insert(key.clone(), value.clone()); + } row } } @@ -137,19 +140,24 @@ pub fn span_rows( parents: &SpanParents<'_>, sink: &mut S, ) -> Result<(), S::Error> { - let span_record_json = flatten_span_fields(span); + // The scope, schema URL and resource fields every row of the span gets + let extra = parents.scope_fields.len() + 1 + parents.resource_fields.len(); + let span_record_json = flatten_span_fields(span, extra); if span.events.is_empty() && span.links.is_empty() { sink.row(parents.finish(span_record_json))?; } else { + // Sized so that the merges below never have to grow a row map: a growth + // rehashes every entry of the row. + let row_extra = extra + span_record_json.len(); for event in &span.events { - let mut row = event_row(event, span.start_time_unix_nano); + let mut row = event_row(event, span.start_time_unix_nano, row_extra); for (key, value) in &span_record_json { row.insert(key.clone(), value.clone()); } sink.row(parents.finish(row))?; } for link in &span.links { - let mut row = link_row(link); + let mut row = link_row(link, row_extra); for (key, value) in &span_record_json { row.insert(key.clone(), value.clone()); } @@ -212,12 +220,15 @@ pub fn flatten_otel_traces(message: &TracesData, tenant_id: &str) -> Vec collect_resource_spans(&message.resource_spans, tenant_id) } -/// The own fields of the row of one span event -fn event_row(event: &Event, span_start_time_unix_nano: u64) -> Map { - let mut event_json = Map::with_capacity(6 + attribute_capacity(&event.attributes)); +/// The own fields of the row of one span event; `extra` is the capacity the +/// span, scope and resource fields merged over it will take +fn event_row(event: &Event, span_start_time_unix_nano: u64, extra: usize) -> Map { + let counted = attribute_capacity(&event.attributes); + let capacity = 6 + counted + extra; + let mut event_json = Map::with_capacity(capacity); event_json.insert( "event_time_unix_nano".to_string(), - Value::String(convert_epoch_nano_to_timestamp(event.time_unix_nano as i64).to_string()), + Value::String(convert_epoch_nano_to_timestamp(event.time_unix_nano as i64)), ); // add epoch value of event time in json event_json.insert( @@ -235,7 +246,11 @@ fn event_row(event: &Event, span_start_time_unix_nano: u64) -> Map Map Map { - let mut link_json = Map::with_capacity(5 + attribute_capacity(&link.attributes)); +/// The own fields of the row of one span link; `extra` is the capacity the span, +/// scope and resource fields merged over it will take +fn link_row(link: &Link, extra: usize) -> Map { + let counted = attribute_capacity(&link.attributes); + let capacity = 5 + counted + extra; + let mut link_json = Map::with_capacity(capacity); link_json.insert( "link_span_id".to_string(), Value::String(hex::encode(&link.span_id)), @@ -255,7 +273,11 @@ fn link_row(link: &Link) -> Map { Value::String(hex::encode(&link.trace_id)), ); + let before = link_json.len(); insert_links_attributes(&mut link_json, &link.attributes); + // Repeated attribute keys must not leave room in the row + let added = link_json.len() - before; + fit_map(&mut link_json, capacity, counted, added); link_json.insert( "link_dropped_attributes_count".to_string(), Value::Number(link.dropped_attributes_count.into()), @@ -267,13 +289,13 @@ fn link_row(link: &Link) -> Map { fn flatten_events(events: &[Event], span_start_time_unix_nano: u64) -> Vec> { events .iter() - .map(|event| event_row(event, span_start_time_unix_nano)) + .map(|event| event_row(event, span_start_time_unix_nano, 0)) .collect() } #[cfg(test)] fn flatten_links(links: &[Link]) -> Vec> { - links.iter().map(link_row).collect() + links.iter().map(|link| link_row(link, 0)).collect() } /// otel trace event has status @@ -350,10 +372,12 @@ fn flatten_kind(kind: i32) -> Map { kind_json } -/// The fields of one span that every row of it gets -fn flatten_span_fields(span_record: &Span) -> Map { - // Room for the scope and resource fields merged into the span's own row - let capacity = 40 + attribute_capacity(&span_record.attributes); +/// The fields of one span that every row of it gets; `extra` is the capacity the +/// scope and resource fields merged over it will take +fn flatten_span_fields(span_record: &Span, extra: usize) -> Map { + // The span's own 20 fields (the status adds 3 of them), its attributes, and + // the scope and resource fields merged into the span's own row + let capacity = 20 + attribute_capacity(&span_record.attributes) + extra; let mut span_record_json = Map::with_capacity(capacity); span_record_json.insert( "span_trace_id".to_string(), From 10e37b07ff030a57c3482641f560cd3232c6b7a3 Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Tue, 24 Nov 2026 02:50:56 -0600 Subject: [PATCH 27/31] perf(otel): insert attribute values by reference instead of cloning them Every attribute of a record, data point, span event or link was cloned as a whole OTEL `AnyValue` before conversion: for the array-valued attributes common in HTTP telemetry that copied the field's `Vec` and the strings inside it, and the copy was thrown away right after. Key-value lists were cloned again for every element of an array of lists. Add `insert_json_from_ref`, which converts from `&OtelValue` (copying only the strings that end up in the row), and use it from `insert_attributes`, `flatten_attributes`, `collect_json_from_values` and the key-value list converter. The consuming `insert_json_from_value` keeps its move for the one caller that has an owned value. Flatten benchmark, instructions:u per row, A/B/B/A x 4 on one box, OTEL_BENCH_ITERS 10 vs 110, spread under 0.01%: logs 66,275 -> 65,212 (-1.6%, one array attribute per record), metrics 58,247 -> 58,044 (-0.35%), traces 85,803 -> 85,724 (-0.09%, no array attribute in the benchmark). Rows digests a4cec43f538fd2cd, f12385b9f510100b and a2c661dfe91e9cde still pass. Verified by Claude Opus 5.5 on top of 98ae3903: insert_json_from_ref converts every value kind as insert_json_from_value does (a string is cloned with capacity equal to its length, as prost and serde leave it). The seeded corpus digests (logs 5247f2af863c6427, metrics b299fcc3bdad0047, traces 2f813bb532c511a5) and bench digests unchanged. Memory tests unchanged except the valueless-attributes span peak, 3,206,027 -> 11,065 B. Release flatten bench, instructions:u per row, A/B/B/A x 4 against 98ae3903, on top of the previous commit: logs 66,553 -> 65,469 (-1.6%), metrics 58,334 -> 57,529 (-1.4%), traces 85,809 -> 85,661 (-0.2%). Co-Authored-By: DeepSeek V4.1 Flash 1017 Co-Authored-By: Claude Opus 5.5 --- src/otel/otel_utils.rs | 106 ++++++++++++++++++++++++++++------------- 1 file changed, 73 insertions(+), 33 deletions(-) diff --git a/src/otel/otel_utils.rs b/src/otel/otel_utils.rs index a5bd4dc49..2f9dede0f 100644 --- a/src/otel/otel_utils.rs +++ b/src/otel/otel_utils.rs @@ -86,6 +86,62 @@ pub fn collect_json_from_value(key: &str, value: OtelValue) -> Map, key: &str, value: &OtelValue) { + match value { + OtelValue::StringValue(str_val) => { + map.insert(key.to_string(), Value::String(str_val.clone())); + } + OtelValue::BoolValue(bool_val) => { + map.insert(key.to_string(), Value::Bool(*bool_val)); + } + OtelValue::IntValue(int_val) => { + map.insert(key.to_string(), Value::String(int_val.to_string())); + } + OtelValue::DoubleValue(double_val) => insert_json_double(map, key, *double_val), + OtelValue::ArrayValue(array_val) => insert_json_array(map, key, array_val), + OtelValue::KvlistValue(kv_list_val) => { + // Create a JSON object to store the key-value list + let kv_object = collect_json_from_key_value_list(kv_list_val); + map.extend(kv_object); + } + OtelValue::BytesValue(bytes_val) => { + map.insert( + key.to_string(), + Value::String(String::from_utf8_lossy(bytes_val).to_string()), + ); + } + OtelValue::StringValueStrindex(str_index) => { + tracing::warn!( + "StringValueStrindex is not supported in key-value lists, index: {str_index}" + ); + } + } +} + +fn insert_json_double(map: &mut Map, key: &str, double_val: f64) { + if let Some(number) = serde_json::Number::from_f64(double_val) { + map.insert(key.to_string(), Value::Number(number)); + } +} + +fn insert_json_array(map: &mut Map, key: &str, array_val: &ArrayValue) { + let json_array_value = collect_json_from_array_value(array_val); + // Convert the array to a JSON string + let json_array_string = match serde_json::to_string(&json_array_value) { + Ok(s) => s, + Err(e) => { + tracing::warn!("failed to serialise array value: {e}"); + String::default() + } + }; + // Insert the array into the result map + map.insert(key.to_string(), Value::String(json_array_string)); +} + fn insert_json_from_value(map: &mut Map, key: &str, value: OtelValue) { match value { OtelValue::StringValue(str_val) => { @@ -97,27 +153,11 @@ fn insert_json_from_value(map: &mut Map, key: &str, value: OtelVa OtelValue::IntValue(int_val) => { map.insert(key.to_string(), Value::String(int_val.to_string())); } - OtelValue::DoubleValue(double_val) => { - if let Some(number) = serde_json::Number::from_f64(double_val) { - map.insert(key.to_string(), Value::Number(number)); - } - } - OtelValue::ArrayValue(array_val) => { - let json_array_value = collect_json_from_array_value(&array_val); - // Convert the array to a JSON string - let json_array_string = match serde_json::to_string(&json_array_value) { - Ok(s) => s, - Err(e) => { - tracing::warn!("failed to serialise array value: {e}"); - String::default() - } - }; - // Insert the array into the result map - map.insert(key.to_string(), Value::String(json_array_string)); - } + OtelValue::DoubleValue(double_val) => insert_json_double(map, key, double_val), + OtelValue::ArrayValue(array_val) => insert_json_array(map, key, &array_val), OtelValue::KvlistValue(kv_list_val) => { // Create a JSON object to store the key-value list - let kv_object = collect_json_from_key_value_list(kv_list_val); + let kv_object = collect_json_from_key_value_list(&kv_list_val); map.extend(kv_object); } OtelValue::BytesValue(bytes_val) => { @@ -170,7 +210,7 @@ fn collect_json_from_array_value(array_value: &ArrayValue) -> Value { } OtelValue::KvlistValue(kv_list) => { // Recursively collect JSON from nested key-value lists - let nested_json = collect_json_from_key_value_list(kv_list.clone()); + let nested_json = collect_json_from_key_value_list(kv_list); json_array.push(Value::Object(nested_json)); } OtelValue::StringValueStrindex(str_index) => { @@ -187,13 +227,13 @@ fn collect_json_from_array_value(array_value: &ArrayValue) -> Value { /// Recursively converts an OpenTelemetry KeyValueList into a JSON Map /// The function iterates through the key-value pairs in the list /// and collects their JSON representations into a single Map -fn collect_json_from_key_value_list(key_value_list: KeyValueList) -> Map { +fn collect_json_from_key_value_list(key_value_list: &KeyValueList) -> Map { let mut kv_list_json: Map = Map::with_capacity(attribute_capacity(&key_value_list.values)); - for key_value in key_value_list.values { - if let Some(val) = key_value.value { - if let Some(val) = val.value { - insert_json_from_value(&mut kv_list_json, &key_value.key, val); + for key_value in &key_value_list.values { + if let Some(val) = &key_value.value { + if let Some(val) = &val.value { + insert_json_from_ref(&mut kv_list_json, &key_value.key, val); } else { tracing::warn!("Key '{}' has no value in key-value list", key_value.key); } @@ -211,8 +251,8 @@ pub fn collect_json_from_values(values: &Option, key: &str) -> Map = Map::with_capacity(1); for value in values.iter() { - if let Some(value) = value.value.clone() { - insert_json_from_value(&mut value_json, key, value); + if let Some(value) = value.value.as_ref() { + insert_json_from_ref(&mut value_json, key, value); } } @@ -231,10 +271,10 @@ pub fn flatten_attributes(attributes: &[KeyValue]) -> Map { let mut attributes_json: Map = Map::with_capacity(attribute_capacity(attributes)); for attribute in attributes { - if let Some(value) = &attribute.value - && let Some(value) = value.value.clone() + if let Some(value) = attribute.value.as_ref() + && let Some(value) = value.value.as_ref() { - insert_json_from_value(&mut attributes_json, &attribute.key, value); + insert_json_from_ref(&mut attributes_json, &attribute.key, value); } } attributes_json @@ -317,10 +357,10 @@ pub fn fit_map(map: &mut Map, capacity: usize, counted: usize, ad pub fn insert_attributes(map: &mut Map, attributes: &[KeyValue]) { for attribute in attributes { - if let Some(value) = &attribute.value - && let Some(value) = value.value.clone() + if let Some(value) = attribute.value.as_ref() + && let Some(value) = value.value.as_ref() { - insert_json_from_value(map, &attribute.key, value); + insert_json_from_ref(map, &attribute.key, value); } } } From d4c84425713b79c6c86982853d72a4502dca359f Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Tue, 24 Nov 2026 02:56:03 -0600 Subject: [PATCH 28/31] perf(otel): build a log record row in place instead of in a scratch map `log_record_row` built the record's fields into a map of their own and then moved them into the row: every record key was hashed twice, a second hash table was allocated and grown, and its entries were copied and freed before the row was handed over. `flatten_log_record_into` now inserts the record's fields straight into the row, after the scope fields and before the resource fields, in the same order as before. `flatten_log_record` stays as the wrapper that makes the standalone record map the tests use. Flatten benchmark, instructions:u per row, A/B/B/A x 4 on one box, OTEL_BENCH_ITERS 10 vs 110, spread under 0.01%: logs 65,212-65,213 -> 56,020-56,021 (-14.1%). Metrics and traces do not take this path. The rows digest a4cec43f538fd2cd still passes. Changed in verification (Claude Opus 5.5, on top of 98ae3903): the row is now created with room for 16 + attribute_capacity of the record, and it is kept as the row; before, the record's own map held that room and was moved into a row that grew to its real size. A record of 128 attributes of one key made its row hold 6.12 times what row_bytes counts (1.19 before). The record's attributes are now inserted with `insert_attributes_fitted`, which gives back what repeated keys, and keys the scope fields already have, did not use: 1.05. Verified: insertion order and which value wins on a collision are as before (every record field is inserted in the same order; a key keeps the position of its first insertion and the value of its last, merged into a scratch map first or not); seeded corpus digests (logs 5247f2af863c6427, metrics b299fcc3bdad0047, traces 2f813bb532c511a5) and bench digests unchanged. Memory tests: row allocated/estimated realistic 0.80 -> 0.88, tiny fields 0.77 -> 0.78 (the 16 fixed slots), repeated-key request 13.7 -> 18.1 MiB (98ae3903: 21.8, bound 40). Release flatten bench, instructions:u per row, A/B/B/A x 4 against 98ae3903, on top of the previous commit: logs 65,469 -> 56,216 (-14.1%); metrics and traces unchanged. Co-Authored-By: DeepSeek V4.1 Flash 1017 Co-Authored-By: Claude Opus 5.5 --- src/otel/logs.rs | 40 +++++++++++++++++++++++++++++----------- 1 file changed, 29 insertions(+), 11 deletions(-) diff --git a/src/otel/logs.rs b/src/otel/logs.rs index 62a4dbb9c..a899b150d 100644 --- a/src/otel/logs.rs +++ b/src/otel/logs.rs @@ -18,7 +18,6 @@ use super::otel_utils::attribute_capacity; use super::otel_utils::collect_json_from_values; use super::otel_utils::convert_epoch_nano_to_timestamp; -use super::otel_utils::insert_attributes; use super::otel_utils::insert_attributes_fitted; use super::sink::{CHUNK_LIMITS, RowSink, VALUE_BYTES, heap_bytes}; use crate::metrics::increment_logs_collected_by_date; @@ -394,8 +393,23 @@ pub fn flatten_log_record( ) -> Result, JsonFlattenError> { // Fixed fields plus the record attributes; body fields can add more, but // one growth is cheaper than the four an empty map needs for these - let mut log_record_json: Map = - Map::with_capacity(16 + attribute_capacity(&log_record.attributes)); + let capacity = 16 + attribute_capacity(&log_record.attributes); + let mut log_record_json: Map = Map::with_capacity(capacity); + flatten_log_record_into(log_record, budget, &mut log_record_json, capacity)?; + Ok(log_record_json) +} + +/// The fields of `flatten_log_record`, inserted into `log_record_json` (which is +/// a finished row when the record is one of a scope). `capacity` is the room the +/// map was created with, `attribute_capacity` of the record's attributes included: +/// what repeated attribute keys did not use is given back, because the map is +/// kept as the row. +fn flatten_log_record_into( + log_record: &LogRecord, + budget: &mut FlattenBudget, + log_record_json: &mut Map, + capacity: usize, +) -> Result<(), JsonFlattenError> { log_record_json.insert( "time_unix_nano".to_string(), Value::String(convert_epoch_nano_to_timestamp( @@ -488,7 +502,7 @@ pub fn flatten_log_record( } } - insert_attributes(&mut log_record_json, &log_record.attributes); + insert_attributes_fitted(log_record_json, &log_record.attributes, capacity); // Insert after attributes so a client-sent "p_log_category" cannot override log_record_json.insert( @@ -513,7 +527,7 @@ pub fn flatten_log_record( Value::String(hex::encode(&log_record.trace_id)), ); - Ok(log_record_json) + Ok(()) } /// Fields every row of one `ScopeLogs` gets, before the record's own fields @@ -568,13 +582,17 @@ pub fn log_record_row( resource_fields: &Map, budget: &mut FlattenBudget, ) -> Result, JsonFlattenError> { - let log_record_json = flatten_log_record(log_record, budget)?; - // Sized so that the two merges below never have to grow the map: a growth - // rehashes every entry of the row. - let mut row = - Map::with_capacity(scope_fields.len() + log_record_json.len() + resource_fields.len()); + // Sized so that the record inserts and the resource merge below never have to + // grow the map: a growth rehashes every entry of the row. The record's own + // fields go straight into the row instead of a scratch map that is hashed a + // second time when it is merged. + let capacity = scope_fields.len() + + resource_fields.len() + + 16 + + attribute_capacity(&log_record.attributes); + let mut row = Map::with_capacity(capacity); row.extend(scope_fields.iter().map(|(k, v)| (k.clone(), v.clone()))); - row.extend(log_record_json); + flatten_log_record_into(log_record, budget, &mut row, capacity)?; row.extend(resource_fields.iter().map(|(k, v)| (k.clone(), v.clone()))); Ok(row) } From 9977636961687e09083b42c9b5dcfdf8a2bcb7c2 Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Tue, 24 Nov 2026 03:04:29 -0600 Subject: [PATCH 29/31] perf(otel): insert the fixed severity, flags, kind and status fields directly `flatten_severity`, `flatten_flags`, `flatten_kind` and `flatten_status` built a map of two or three fixed fields only for the caller to extend the record with it: the map was allocated, each key hashed and the key/value moved and hashed again. Logs also cloned the severity text a second time. Insert the same fields, in the same order, straight into the record. The helper maps stay for the tests that check their values. Flatten benchmark, instructions:u per row, A/B/B/A x 4 on one box, OTEL_BENCH_ITERS 10 vs 110, spread under 0.01%: logs 56,020-56,021 -> 54,360-54,361 (-3.0%); traces 85,724 -> 83,161-83,162 (-3.0%). Metrics do not take this path. Rows digests a4cec43f538fd2cd and a2c661dfe91e9cde still pass. Verified by Claude Opus 5.5 on top of 98ae3903: the fields are inserted in the order the helper maps had (severity number, text; flags, description; kind, description; status message, code, description), and an insert over an existing key keeps its position as the merge did. The seeded corpus digests (logs 5247f2af863c6427, metrics b299fcc3bdad0047, traces 2f813bb532c511a5) and bench digests unchanged. Memory tests unchanged. Release flatten bench, instructions:u per row, A/B/B/A x 4 against 98ae3903, on top of the previous commit: logs 56,216 -> 54,531 (-3.0%), traces 85,661 -> 83,135 (-2.9%). Metrics 57,529 -> 58,133 (+1.05%) although no metrics code changed: in this build the known-field set lookup in compute_series_hash is no longer inlined (HashMap::contains_key is 2.9% of the profile). The whole series, against 98ae3903: logs -20.9%, metrics -16.7%, traces -10.9%. Co-Authored-By: DeepSeek V4.1 Flash 1017 Co-Authored-By: Claude Opus 5.5 --- src/otel/logs.rs | 20 +++------- src/otel/traces.rs | 92 +++++++++++++++++++++++++++++++++------------- 2 files changed, 71 insertions(+), 41 deletions(-) diff --git a/src/otel/logs.rs b/src/otel/logs.rs index a899b150d..f001f3845 100644 --- a/src/otel/logs.rs +++ b/src/otel/logs.rs @@ -118,20 +118,6 @@ fn severity_number_from_text(severity_text: &str) -> Option { } } -/// Add the normalized severity fields to the flattened JSON. -fn flatten_severity(severity_number: i32, severity_text: &str) -> Map { - let mut severity_json: Map = Map::new(); - severity_json.insert( - "severity_number".to_string(), - Value::Number(severity_number.into()), - ); - severity_json.insert( - "severity_text".to_string(), - Value::String(severity_text.to_string()), - ); - severity_json -} - /// Maps OTel severity_number (0–24) to a log category. /// See https://opentelemetry.io/docs/specs/otel/logs/data-model/#severity-fields fn category_from_severity(severity_number: i32) -> Option<&'static str> { @@ -425,7 +411,11 @@ fn flatten_log_record_into( let (severity_number, severity_text) = normalize_severity(log_record.severity_number, &log_record.severity_text); - log_record_json.extend(flatten_severity(severity_number, &severity_text)); + log_record_json.insert( + "severity_number".to_string(), + Value::Number(severity_number.into()), + ); + log_record_json.insert("severity_text".to_string(), Value::String(severity_text)); // Primary: derive category from the normalized severity_number let mut log_category = category_from_severity(severity_number); diff --git a/src/otel/traces.rs b/src/otel/traces.rs index fc1331d65..8ee032d3f 100644 --- a/src/otel/traces.rs +++ b/src/otel/traces.rs @@ -21,6 +21,7 @@ use opentelemetry_proto::tonic::common::v1::KeyValue; use opentelemetry_proto::tonic::resource::v1::Resource; use opentelemetry_proto::tonic::trace::v1::ResourceSpans; use opentelemetry_proto::tonic::trace::v1::Span; +#[cfg(test)] use opentelemetry_proto::tonic::trace::v1::Status; use opentelemetry_proto::tonic::trace::v1::TracesData; use opentelemetry_proto::tonic::trace::v1::span::Event; @@ -302,6 +303,7 @@ fn flatten_links(links: &[Link]) -> Vec> { /// there is a mapping of status code to status description provided in proto /// this function fetches the status description from the status code /// and adds it to the flattened json +#[cfg(test)] fn flatten_status(status: &Status) -> Map { let mut status_json = Map::new(); status_json.insert( @@ -312,50 +314,67 @@ fn flatten_status(status: &Status) -> Map { "span_status_code".to_string(), Value::Number(status.code.into()), ); - let description = match status.code { - 0 => "UNSET", - 1 => "OK", - 2 => "ERROR", - _ => "", - }; status_json.insert( "span_status_description".to_string(), - Value::String(description.to_string()), + Value::String(status_description(status.code).to_string()), ); status_json } +fn status_description(code: i32) -> &'static str { + match code { + 0 => "UNSET", + 1 => "OK", + 2 => "ERROR", + _ => "", + } +} + /// otel log event has flags /// there is a mapping of flags to flags description provided in proto /// this function fetches the flags description from the flags /// and adds it to the flattened json +#[cfg(test)] fn flatten_flags(flags: u32) -> Map { let mut flags_json = Map::new(); flags_json.insert("span_flags".to_string(), Value::Number(flags.into())); - let description = match flags { - 0 => "DO_NOT_USE", - 255 => "TRACE_FLAGS_MASK", - 256 => "CONTEXT_HAS_IS_REMOTE_MASK", - 512 => "CONTEXT_IS_REMOTE_MASK", - _ => "", - }; flags_json.insert( "span_flags_description".to_string(), - Value::String(description.to_string()), + Value::String(flags_description(flags).to_string()), ); flags_json } +fn flags_description(flags: u32) -> &'static str { + match flags { + 0 => "DO_NOT_USE", + 255 => "TRACE_FLAGS_MASK", + 256 => "CONTEXT_HAS_IS_REMOTE_MASK", + 512 => "CONTEXT_IS_REMOTE_MASK", + _ => "", + } +} + /// otel span event has kind /// there is a mapping of kind to kind description provided in proto /// this function fetches the kind description from the kind /// and adds it to the flattened json +#[cfg(test)] fn flatten_kind(kind: i32) -> Map { let mut kind_json = Map::new(); kind_json.insert("span_kind".to_string(), Value::Number(kind.into())); - let description = match kind { + kind_json.insert( + "span_kind_description".to_string(), + Value::String(kind_description(kind).to_string()), + ); + + kind_json +} + +fn kind_description(kind: i32) -> &'static str { + match kind { 0 => "UNSPECIFIED", 1 => "INTERNAL", 2 => "SERVER", @@ -363,13 +382,7 @@ fn flatten_kind(kind: i32) -> Map { 4 => "PRODUCER", 5 => "CONSUMER", _ => "", - }; - kind_json.insert( - "span_kind_description".to_string(), - Value::String(description.to_string()), - ); - - kind_json + } } /// The fields of one span that every row of it gets; `extra` is the capacity the @@ -395,12 +408,28 @@ fn flatten_span_fields(span_record: &Span, extra: usize) -> Map { "span_parent_span_id".to_string(), Value::String(hex::encode(&span_record.parent_span_id)), ); - span_record_json.extend(flatten_flags(span_record.flags)); + // The flags, kind and status fields are inserted directly: a map of their + // own only to be merged into this one bought their keys a second hash + span_record_json.insert( + "span_flags".to_string(), + Value::Number(span_record.flags.into()), + ); + span_record_json.insert( + "span_flags_description".to_string(), + Value::String(flags_description(span_record.flags).to_string()), + ); span_record_json.insert( "span_name".to_string(), Value::String(span_record.name.clone()), ); - span_record_json.extend(flatten_kind(span_record.kind)); + span_record_json.insert( + "span_kind".to_string(), + Value::Number(span_record.kind.into()), + ); + span_record_json.insert( + "span_kind_description".to_string(), + Value::String(kind_description(span_record.kind).to_string()), + ); span_record_json.insert( "span_start_time_unix_nano".to_string(), Value::String(convert_epoch_nano_to_timestamp( @@ -448,7 +477,18 @@ fn flatten_span_fields(span_record: &Span, extra: usize) -> Map { Value::Number(span_record.dropped_links_count.into()), ); if let Some(status) = &span_record.status { - span_record_json.extend(flatten_status(status)); + span_record_json.insert( + "span_status_message".to_string(), + Value::String(status.message.clone()), + ); + span_record_json.insert( + "span_status_code".to_string(), + Value::Number(status.code.into()), + ); + span_record_json.insert( + "span_status_description".to_string(), + Value::String(status_description(status.code).to_string()), + ); } span_record_json } From 0d9fab2af4646a114042f6c97f73daf3729f633f Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Tue, 24 Nov 2026 08:02:05 -0600 Subject: [PATCH 30/31] fix(otel): cap what one request stages at 1024 times the payload limit The expansion cap was 4096 times the length of the body with no upper bound, so one body of the full payload limit (10 MiB) could stage 40 GiB of estimated rows, about 6 GiB of record batches held in staging. Keep the factor, which gives ordinary requests 8x headroom over the largest realistic expansion measured, and add a ceiling of 1024 times P_MAX_EVENT_PAYLOAD_SIZE (10 GiB by default). The ceiling decides for bodies over a quarter of the payload limit. The largest realistic request measured at the limit takes 4.1 GiB, 2.4x under it. Co-Authored-By: Claude Fable 5.2 --- src/handlers/http/modal/utils/ingest_utils.rs | 19 ++++++---- .../utils/ingest_utils/otel_protobuf_props.rs | 8 +++-- .../ingest_utils/otel_regression_tests.rs | 27 +++++++++----- src/otel/realistic_tests.rs | 33 ++++++++++++----- src/otel/sink.rs | 35 ++++++++++++++----- 5 files changed, 88 insertions(+), 34 deletions(-) diff --git a/src/handlers/http/modal/utils/ingest_utils.rs b/src/handlers/http/modal/utils/ingest_utils.rs index 91b48a0e3..97fdee1e6 100644 --- a/src/handlers/http/modal/utils/ingest_utils.rs +++ b/src/handlers/http/modal/utils/ingest_utils.rs @@ -66,8 +66,8 @@ use crate::{ refusal, }, sink::{ - CHUNK_LIMITS, ChunkLimits, Chunker, EXPANSION_FACTOR, MIN_EXPANDED_BYTES, RowSink, - Staged, max_expanded_bytes, + CHUNK_LIMITS, ChunkLimits, Chunker, EXPANSION_CEILING_FACTOR, EXPANSION_FACTOR, + MIN_EXPANDED_BYTES, RowSink, Staged, max_expanded_bytes, }, traces::flatten_traces_into, }, @@ -439,7 +439,7 @@ impl OtelResources<'_> { /// The refusal of a request whose rows hold more than `max` estimated bytes in all fn expansion_error(max: u64) -> PostError { PostError::Invalid(anyhow::anyhow!( - "The rows of the request take more than the {max} bytes allowed ({EXPANSION_FACTOR} times the length of its body, at least {MIN_EXPANDED_BYTES}). Split the batch into smaller requests, or send fewer resource, scope and span attributes per record" + "The rows of the request take more than the {max} bytes allowed ({EXPANSION_FACTOR} times the length of its body, at least {MIN_EXPANDED_BYTES} and at most {EXPANSION_CEILING_FACTOR} times the payload limit). Split the batch into smaller requests, or send fewer resource, scope and span attributes per record" )) } @@ -453,11 +453,12 @@ struct StageLimits { } impl StageLimits { - /// The limits of staging a request whose body (decompressed) is `body_len` bytes - fn for_body(body_len: usize, flatten: FlattenLimits) -> Self { + /// The limits of staging a request whose body (decompressed) is `body_len` + /// bytes, under a payload limit of `max_payload` bytes + fn for_body(body_len: usize, max_payload: usize, flatten: FlattenLimits) -> Self { Self { chunk: CHUNK_LIMITS, - max_expanded: max_expanded_bytes(body_len), + max_expanded: max_expanded_bytes(body_len, max_payload), flatten, } } @@ -567,7 +568,11 @@ fn ingest_otel_rows( return Ok(OtelIngested::Full); } let tenant_str = target.tenant_id.as_deref().unwrap_or(DEFAULT_TENANT); - let limits = StageLimits::for_body(body_len, FlattenLimits::from_config()); + let limits = StageLimits::for_body( + body_len, + max_event_payload_size(), + FlattenLimits::from_config(), + ); let mut staging = Staging::new(target.stream_name, target.tenant_id)?; let (result, staged) = stage_otel_rows(limits, flatten, |rows| { staging.push( diff --git a/src/handlers/http/modal/utils/ingest_utils/otel_protobuf_props.rs b/src/handlers/http/modal/utils/ingest_utils/otel_protobuf_props.rs index 0cc4814d7..f8fbef649 100644 --- a/src/handlers/http/modal/utils/ingest_utils/otel_protobuf_props.rs +++ b/src/handlers/http/modal/utils/ingest_utils/otel_protobuf_props.rs @@ -86,7 +86,11 @@ const PROTOBUF_OPTIONS: ProtobufOptions = ProtobufOptions { /// The staging limits of the server defaults, for a body at the payload limit fn test_limits() -> StageLimits { - StageLimits::for_body(PROTOBUF_OPTIONS.max_payload, FlattenLimits::DEFAULT) + StageLimits::for_body( + PROTOBUF_OPTIONS.max_payload, + PROTOBUF_OPTIONS.max_payload, + FlattenLimits::DEFAULT, + ) } // --------------------------------------------------------------------------- @@ -3890,7 +3894,7 @@ mod streamed { for (outcome, counted) in [&protobuf, &json] { assert!(counted.chunks > 0 && counted.records < 2000, "{counted:?}"); let message = format!( - "Invalid Request: The rows of the request take more than the {cap} bytes allowed (4096 times the length of its body, at least 16777216). Split the batch into smaller requests, or send fewer resource, scope and span attributes per record" + "Invalid Request: The rows of the request take more than the {cap} bytes allowed (4096 times the length of its body, at least 16777216 and at most 1024 times the payload limit). Split the batch into smaller requests, or send fewer resource, scope and span attributes per record" ); assert_eq!( outcome.as_ref().unwrap(), diff --git a/src/handlers/http/modal/utils/ingest_utils/otel_regression_tests.rs b/src/handlers/http/modal/utils/ingest_utils/otel_regression_tests.rs index aecba5fc4..5ca50ede4 100644 --- a/src/handlers/http/modal/utils/ingest_utils/otel_regression_tests.rs +++ b/src/handlers/http/modal/utils/ingest_utils/otel_regression_tests.rs @@ -71,20 +71,31 @@ fn target<'a>( /// The staging limits ingestion uses for a body of `body_len` bytes fn limits_for(body_len: usize) -> StageLimits { - StageLimits::for_body(body_len, FlattenLimits::DEFAULT) + StageLimits::for_body(body_len, PAYLOAD, FlattenLimits::DEFAULT) } /// Review finding 8: the expansion cap was 1024 x `P_MAX_EVENT_PAYLOAD_SIZE` /// (10 GiB) whatever the size of the body, so a body of a few KiB could stage -/// gigabytes of rows. It is now 4096 x the length of the body, with a floor. +/// gigabytes of rows. It is now 4096 x the length of the body, with a floor, and +/// that 10 GiB (1024 x the payload limit) is kept as a ceiling, which decides for +/// bodies over a quarter of the limit: without it a body of the full limit could +/// stage 40 GiB of rows. #[test] -fn expansion_cap_is_4096_times_the_body_with_a_floor() { - use crate::otel::sink::{EXPANSION_FACTOR, MIN_EXPANDED_BYTES}; +fn expansion_cap_is_4096_times_the_body_with_a_floor_and_a_ceiling() { + use crate::otel::sink::{EXPANSION_CEILING_FACTOR, EXPANSION_FACTOR, MIN_EXPANDED_BYTES}; assert_eq!(EXPANSION_FACTOR, 4096); - assert_eq!(max_expanded_bytes(0), MIN_EXPANDED_BYTES); - assert_eq!(max_expanded_bytes(1000), MIN_EXPANDED_BYTES); - assert_eq!(max_expanded_bytes(1 << 20), 4u64 << 30); - assert_eq!(max_expanded_bytes(PAYLOAD), 40u64 << 30); + assert_eq!(EXPANSION_CEILING_FACTOR, 1024); + assert_eq!(max_expanded_bytes(0, PAYLOAD), MIN_EXPANDED_BYTES); + assert_eq!(max_expanded_bytes(1000, PAYLOAD), MIN_EXPANDED_BYTES); + assert_eq!(max_expanded_bytes(1 << 20, PAYLOAD), 4u64 << 30); + assert_eq!(max_expanded_bytes(PAYLOAD / 4, PAYLOAD), 10u64 << 30); + assert_eq!(max_expanded_bytes(PAYLOAD / 4 + 1, PAYLOAD), 10u64 << 30); + assert_eq!(max_expanded_bytes(PAYLOAD, PAYLOAD), 10u64 << 30); + // The ceiling follows the payload limit, and is never under the floor + assert_eq!(max_expanded_bytes(4 * PAYLOAD, 4 * PAYLOAD), 40u64 << 30); + assert_eq!(max_expanded_bytes(usize::MAX, usize::MAX), u64::MAX); + assert_eq!(max_expanded_bytes(1 << 20, 1024), MIN_EXPANDED_BYTES); + assert_eq!(max_expanded_bytes(1 << 20, 0), MIN_EXPANDED_BYTES); } /// Review finding 8, as a request: a body of 47 KiB whose rows expand past 4096x diff --git a/src/otel/realistic_tests.rs b/src/otel/realistic_tests.rs index a57334ff3..7aab1e7b3 100644 --- a/src/otel/realistic_tests.rs +++ b/src/otel/realistic_tests.rs @@ -40,7 +40,10 @@ use prost::Message; use serde_json::{Map, Value}; use super::protobuf_stream::{Signal, flatten_request, max_record_bytes, outline}; -use super::sink::{EXPANSION_FACTOR, MIN_EXPANDED_BYTES, RowSink, max_expanded_bytes, row_bytes}; +use super::sink::{ + EXPANSION_CEILING_FACTOR, EXPANSION_FACTOR, MIN_EXPANDED_BYTES, RowSink, max_expanded_bytes, + row_bytes, +}; use crate::utils::json::flatten::{FlattenBudget, FlattenLimits, JsonFlattenError}; /// `P_MAX_EVENT_PAYLOAD_SIZE` default @@ -522,8 +525,11 @@ pub(crate) fn shapes() -> Vec { } /// Every realistic shape at the payload limit is under the expansion cap for its -/// body with at least 8x headroom, counted as staging counts it: the `row_bytes` -/// of every row. So is the same shape with 1, 10 and 100 records. +/// body, counted as staging counts it: the `row_bytes` of every row. There the +/// ceiling of the cap decides, and leaves at least 2x headroom. The same shape +/// with 1, 10 and 100 records, and with as many records as fill a quarter of the +/// payload limit (counted from the rows of the full body, which all hold about +/// the same), has at least 8x. #[test] fn realistic_requests_at_the_payload_limit_are_under_the_expansion_cap() { use rayon::prelude::*; @@ -537,7 +543,7 @@ fn realistic_requests_at_the_payload_limit_are_under_the_expansion_cap() { }) .collect(); for (shape, totals) in measured { - let cap = max_expanded_bytes(shape.body.len()); + let cap = max_expanded_bytes(shape.body.len(), PAYLOAD); let ratio = totals.bytes as f64 / shape.body.len() as f64; worst = worst.max(ratio); println!( @@ -551,8 +557,17 @@ fn realistic_requests_at_the_payload_limit_are_under_the_expansion_cap() { 100.0 * totals.bytes as f64 / cap as f64 ); assert!( - totals.bytes.saturating_mul(8) <= cap, - "{} is under 8x headroom", + totals.bytes.saturating_mul(2) <= cap, + "{} is under 2x headroom at the payload limit", + shape.name + ); + // A quarter of the payload limit of the same records: the factor decides + let quarter = (PAYLOAD / 4) as u64; + let quarter_bytes = + (totals.bytes as u128 * quarter as u128 / shape.body.len() as u128) as u64; + assert!( + quarter_bytes.saturating_mul(8) <= max_expanded_bytes(PAYLOAD / 4, PAYLOAD), + "{} is under 8x headroom at a quarter of the payload limit", shape.name ); for body in &shape.small { @@ -566,7 +581,7 @@ fn realistic_requests_at_the_payload_limit_are_under_the_expansion_cap() { small.bytes ); assert!( - small.bytes.saturating_mul(8) <= max_expanded_bytes(body.len()), + small.bytes.saturating_mul(8) <= max_expanded_bytes(body.len(), PAYLOAD), "{} with {} records", shape.name, small.records @@ -574,7 +589,7 @@ fn realistic_requests_at_the_payload_limit_are_under_the_expansion_cap() { } } println!( - "EXPANSION worst {worst:.1} row bytes per body byte, cap {EXPANSION_FACTOR} per body byte, at least {MIN_EXPANDED_BYTES}" + "EXPANSION worst {worst:.1} row bytes per body byte, cap {EXPANSION_FACTOR} per body byte, at least {MIN_EXPANDED_BYTES}, at most {EXPANSION_CEILING_FACTOR} per byte of the payload limit" ); } @@ -610,7 +625,7 @@ fn copied_fields_over_tiny_records_are_over_the_expansion_cap() { bytes as f64 / (1u64 << 30) as f64 ); assert!(request.encoded_len() <= PAYLOAD); - assert!(bytes > max_expanded_bytes(request.encoded_len())); + assert!(bytes > max_expanded_bytes(request.encoded_len(), PAYLOAD)); } /// Writes the body of every shape to `OTLP_DUMP_DIR`, named after its signal diff --git a/src/otel/sink.rs b/src/otel/sink.rs index 2cc03d15c..aba486cce 100644 --- a/src/otel/sink.rs +++ b/src/otel/sink.rs @@ -160,8 +160,9 @@ pub struct Staged { /// Row bytes per body byte one request may expand to: the rows of a request may /// hold at most `EXPANSION_FACTOR` times the length of its body (decompressed) of -/// estimated memory ([`row_bytes`]) in all, counted while they are staged, and at -/// least [`MIN_EXPANDED_BYTES`]. +/// estimated memory ([`row_bytes`]) in all, counted while they are staged, at +/// least [`MIN_EXPANDED_BYTES`] and at most [`EXPANSION_CEILING_FACTOR`] times +/// the payload limit. /// /// Every row carries its own copy of the resource, scope, span and metric fields, /// so a small request can expand to a very large number of row bytes: 15 KB of @@ -171,9 +172,9 @@ pub struct Staged { /// below 500 row bytes per body byte (short log records or bare gauge points under /// 30 Kubernetes resource attributes; ordinary k8s logs, spans and metrics expand /// 40-110x, see `realistic_tests`), and a request of such records expands less the -/// fewer records share its resource, so 4096 leaves at least 8x headroom at every -/// body size, and stops the requests that copy kilobytes of shared fields into -/// millions of records of a few bytes. +/// fewer records share its resource, so 4096 leaves at least 8x headroom wherever +/// the ceiling does not decide, and stops the requests that copy kilobytes of +/// shared fields into millions of records of a few bytes. pub const EXPANSION_FACTOR: u64 = 4096; /// Estimated bytes of rows any request may expand to, whatever the length of its @@ -183,12 +184,30 @@ pub const EXPANSION_FACTOR: u64 = 4096; /// per body byte), 8x under it. pub const MIN_EXPANDED_BYTES: u64 = CHUNK_LIMITS.bytes as u64; +/// Estimated row bytes per byte of the payload limit (`P_MAX_EVENT_PAYLOAD_SIZE`) +/// that no request may pass, however long its body: 10 GiB at the default limit +/// of 10 MiB. +/// +/// What a request stages stays in the staging buffers until they are converted, as +/// record batches of about a sixth of the estimate (1.6 GiB measured for 10 GiB of +/// rows), so `EXPANSION_FACTOR` alone would let one body of the full payload limit +/// add 40 GiB of rows, 6 GiB of record batches. The ceiling decides for bodies +/// over a quarter of the payload limit. The largest realistic request measured, +/// short log records under 30 Kubernetes resource attributes filling the payload +/// limit, takes 4.1 GiB, so the ceiling leaves 2.4x headroom there, and the 8x of +/// `EXPANSION_FACTOR` up to a quarter of the limit: 138,000 such records, 16 times +/// the 8192 records of a collector's default batch. +pub const EXPANSION_CEILING_FACTOR: u64 = 1024; + /// Estimated bytes of rows one request may expand to, for a body of `body_len` -/// bytes -pub fn max_expanded_bytes(body_len: usize) -> u64 { +/// bytes (decompressed) under a payload limit of `max_payload` bytes +pub fn max_expanded_bytes(body_len: usize, max_payload: usize) -> u64 { + let ceiling = (max_payload as u64) + .saturating_mul(EXPANSION_CEILING_FACTOR) + .max(MIN_EXPANDED_BYTES); (body_len as u64) .saturating_mul(EXPANSION_FACTOR) - .max(MIN_EXPANDED_BYTES) + .clamp(MIN_EXPANDED_BYTES, ceiling) } /// Collects rows into chunks and passes every full chunk to `stage`, with the From 76dbb2ae5fb8b73c972e69dcb4f7998ebaec0416 Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Tue, 24 Nov 2026 08:02:43 -0600 Subject: [PATCH 31/31] docs(otel): drop a pointer to a report that is not in the repository Co-Authored-By: Claude Fable 5.2 --- src/otel/sink.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/otel/sink.rs b/src/otel/sink.rs index aba486cce..3b35228ac 100644 --- a/src/otel/sink.rs +++ b/src/otel/sink.rs @@ -136,8 +136,7 @@ pub struct ChunkLimits { pub bytes: usize, } -/// Default chunk limits, see `REPORT.md` of the change that introduced them for the -/// measurements. A chunk is full at 8192 rows (the default batch size of the +/// Default chunk limits. A chunk is full at 8192 rows (the default batch size of the /// OpenTelemetry collector) or 16 MiB of estimated row memory, whichever comes first. /// Rows of realistic requests hold 1-10 KiB each, so the memory limit usually decides. pub const CHUNK_LIMITS: ChunkLimits = ChunkLimits {