From 906c43e3a015d04fcc9d64d9e4fcab1a1270ad8b Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Mon, 23 Nov 2026 15:16:54 -0600 Subject: [PATCH 1/7] test(otel): add release-profile flattening micro-benchmarks Ignored tests that flatten a fixed OTLP protobuf request for logs, metrics and traces, plus per-function timings for timestamp formatting, attribute conversion, row cloning and the metrics series hash. Each benchmark reports nanoseconds per row and a digest of the rows, dumps them with OTEL_BENCH_DUMP and never reads the PARSEABLE global, so a test-name filter can run it. Written by a DeepSeek V4.1 Flash agent; reviewed and re-measured by Claude. Co-Authored-By: Claude Fable 5.2 --- src/otel.rs | 79 ++++++++++++++++ src/otel/logs.rs | 194 +++++++++++++++++++++++++++++++++++++++ src/otel/metrics.rs | 201 +++++++++++++++++++++++++++++++++++++++++ src/otel/otel_utils.rs | 70 ++++++++++++++ src/otel/traces.rs | 174 +++++++++++++++++++++++++++++++++++ 5 files changed, 718 insertions(+) diff --git a/src/otel.rs b/src/otel.rs index 72261ecfb..9accb4622 100644 --- a/src/otel.rs +++ b/src/otel.rs @@ -20,3 +20,82 @@ pub mod logs; pub mod metrics; pub mod otel_utils; pub mod traces; + +/// 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: +/// +/// ```text +/// cargo test --release --lib -- --ignored --exact otel::logs::tests::bench_flatten_otel_protobuf_logs --nocapture +/// ``` +/// +/// Every iteration must flatten the same input to the same rows, so a digest of +/// the rows is printed (and, with `OTEL_BENCH_DUMP=`, written out) next to +/// the per-row wall time for `perf stat` to turn into instruction counts. +#[cfg(test)] +pub(crate) mod bench { + use std::time::Instant; + + /// Runs `body` `iters` times, requiring identical output every time, and + /// prints the rows, their digest and the nanoseconds spent per row. + pub fn run(name: &str, iters: usize, mut body: F) + where + F: FnMut() -> Vec, + { + // 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(); + let rows = first.len(); + let expected = rows_digest(&first); + if let Some(dir) = dump_dir() { + std::fs::write( + format!("{dir}/{name}.json"), + serde_json::to_vec(&first).expect("benchmark rows serialise"), + ) + .expect("benchmark rows dump"); + } + + let start = Instant::now(); + for _ in 0..iters { + std::hint::black_box(body()); + } + let elapsed = start.elapsed(); + + let last = body(); + assert_eq!( + rows_digest(&last), + expected, + "{name}: repeated iterations produced different rows" + ); + println!( + "{name}: rows={rows} iters={iters} ns_per_row={:.1} bytes={} digest={:016x}", + elapsed.as_secs_f64() * 1e9 / (rows * iters) as f64, + expected.0, + expected.1 + ); + } + + fn rows_digest(rows: &[serde_json::Value]) -> (usize, u64) { + use std::hash::Hasher; + let bytes = serde_json::to_vec(rows).expect("benchmark rows serialise"); + let mut hasher = rustc_hash::FxHasher::default(); + hasher.write(&bytes); + (bytes.len(), hasher.finish()) + } + + /// Times `iters` repetitions of `body` and prints the nanoseconds per call. + pub fn time_calls(name: &str, iters: usize, mut body: F) { + let start = Instant::now(); + for i in 0..iters { + body(i); + } + println!( + "{name}: iters={iters} ns_per_call={:.1}", + start.elapsed().as_secs_f64() * 1e9 / iters as f64 + ); + } + + fn dump_dir() -> Option { + std::env::var("OTEL_BENCH_DUMP").ok() + } +} diff --git a/src/otel/logs.rs b/src/otel/logs.rs index 14acac4c6..e571703b5 100644 --- a/src/otel/logs.rs +++ b/src/otel/logs.rs @@ -913,4 +913,198 @@ mod tests { } ); } + + // 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 + // 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; + use opentelemetry_proto::tonic::common::v1::{ + AnyValue, ArrayValue, InstrumentationScope, KeyValue, any_value, + }; + use opentelemetry_proto::tonic::logs::v1::{LogRecord, ResourceLogs, ScopeLogs}; + use opentelemetry_proto::tonic::resource::v1::Resource; + + const RECORDS_PER_SCOPE: usize = 250; + const ITERS: usize = 20; + + fn string_kv(key: &str, value: impl Into) -> KeyValue { + KeyValue { + key: key.to_string(), + value: Some(AnyValue { + value: Some(any_value::Value::StringValue(value.into())), + }), + ..Default::default() + } + } + + fn int_kv(key: &str, value: i64) -> KeyValue { + KeyValue { + key: key.to_string(), + value: Some(AnyValue { + value: Some(any_value::Value::IntValue(value)), + }), + ..Default::default() + } + } + + fn bool_kv(key: &str, value: bool) -> KeyValue { + KeyValue { + key: key.to_string(), + value: Some(AnyValue { + value: Some(any_value::Value::BoolValue(value)), + }), + ..Default::default() + } + } + + fn array_kv(key: &str) -> KeyValue { + KeyValue { + key: key.to_string(), + value: Some(AnyValue { + value: Some(any_value::Value::ArrayValue(ArrayValue { + values: vec![ + AnyValue { + value: Some(any_value::Value::StringValue("keep-alive".into())), + }, + AnyValue { + value: Some(any_value::Value::StringValue("gzip".into())), + }, + AnyValue { + value: Some(any_value::Value::IntValue(3)), + }, + ], + })), + }), + ..Default::default() + } + } + + fn record(i: usize) -> LogRecord { + // Every tenth body is a JSON object, which the log flattener parses and expands + let body = if i % 10 == 0 { + format!( + r#"{{"event":"checkout","user":{{"id":{i}}},"items":[{{"sku":"a","qty":1}},{{"sku":"b","qty":2}}],"ok":true}}"# + ) + } else { + format!("request {i} completed in {} ms", i % 500) + }; + LogRecord { + time_unix_nano: 1_700_000_000_000_000_000 + i as u64 * 1_000_000, + observed_time_unix_nano: 1_700_000_000_000_000_100 + i as u64 * 1_000_000, + severity_number: 9, + severity_text: "INFO".to_string(), + body: Some(AnyValue { + value: Some(any_value::Value::StringValue(body)), + }), + attributes: vec![ + string_kv("http.method", "GET"), + int_kv("http.status_code", (i % 500) as i64), + string_kv("http.target", format!("/api/v1/items/{i}")), + string_kv("net.host.name", "checkout.example.com"), + string_kv("user_agent.original", "Mozilla/5.0 (compatible; bench)"), + bool_kv("cache.hit", i % 3 == 0), + string_kv("http.request.header.x-request-id", format!("req-{i:016x}")), + array_kv("http.request.header.accept-encoding"), + ], + dropped_attributes_count: 0, + flags: 1, + trace_id: vec![0xab; 16], + span_id: vec![0xcd; 8], + event_name: String::new(), + } + } + + fn request() -> ExportLogsServiceRequest { + let resource_logs = (0..4) + .map(|resource_index| ResourceLogs { + resource: Some(Resource { + attributes: vec![ + string_kv("service.name", "checkout"), + string_kv("service.version", "1.42.0"), + string_kv("deployment.environment", "production"), + string_kv("host.name", format!("checkout-{resource_index}")), + int_kv("process.pid", 4242 + resource_index as i64), + ], + dropped_attributes_count: 0, + entity_refs: vec![], + }), + scope_logs: (0..2) + .map(|scope_index| ScopeLogs { + scope: Some(InstrumentationScope { + name: "io.opentelemetry.contrib.bench".to_string(), + version: "0.31.0".to_string(), + attributes: vec![ + string_kv("scope.kind", "server"), + string_kv("scope.extra", format!("{resource_index}-{scope_index}")), + int_kv("scope.ordinal", scope_index), + ], + dropped_attributes_count: 0, + }), + log_records: (0..RECORDS_PER_SCOPE) + .map(|record_index| { + record(resource_index as usize * 1000 + scope_index as usize * 100 + record_index) + }) + .collect(), + schema_url: "https://opentelemetry.io/schemas/1.24.0".to_string(), + }) + .collect(), + schema_url: "https://opentelemetry.io/schemas/1.24.0".to_string(), + }) + .collect(); + ExportLogsServiceRequest { resource_logs } + } + + fn flatten(request: &ExportLogsServiceRequest) -> Vec { + let mut budget = FlattenBudget::new(FlattenLimits::DEFAULT); + flatten_otel_protobuf(request, "perfbench", &mut budget).expect("benchmark rows flatten") + } + + #[test] + #[ignore = "performance benchmark"] + fn bench_flatten_otel_protobuf_logs() { + let request = request(); + bench::run("bench_flatten_otel_protobuf_logs", ITERS, || { + flatten(&request) + }); + } + + /// The rows of the benchmark request, pinned so that a refactor changing + /// them fails a normal `cargo test --lib` run. The digest is of + /// `serde_json::to_vec` of the rows; it was first recorded from the + /// unoptimised flatteners. + #[test] + fn benchmark_request_rows_are_stable() { + let rows = flatten(&request()); + let bytes = serde_json::to_vec(&rows).unwrap(); + use std::hash::Hasher; + let mut hasher = rustc_hash::FxHasher::default(); + hasher.write(&bytes); + assert_eq!(rows.len(), 2000); + assert_eq!( + (bytes.len(), hasher.finish()), + (2_288_617, 0xa4ce_c43f_538f_d2cd), + "flattened rows of the benchmark request changed" + ); + } + + /// Cost of one flattened row clone, the per-record work the row + /// assembly in `process_resource_logs` repeats. + #[test] + #[ignore = "performance benchmark"] + fn bench_row_clone() { + let rows = flatten(&request()); + let row = rows[0].as_object().expect("object row"); + let mut sum = 0usize; + bench::time_calls("bench_row_clone", 200_000, |_| { + let clone = row.clone(); + sum += clone.len(); + }); + assert!(sum > 0); + } + } } diff --git a/src/otel/metrics.rs b/src/otel/metrics.rs index 6684dd1bf..d4566d7c1 100644 --- a/src/otel/metrics.rs +++ b/src/otel/metrics.rs @@ -1461,4 +1461,205 @@ mod tests { ); } } + + // Release-profile micro-benchmarks. Run with a filter, for example: + // cargo test --release --lib -- --ignored --exact otel::metrics::tests::benches::bench_flatten_otel_metrics_protobuf --nocapture + // They call `process_resource_metrics` directly with `flatten_exemplars` + // false, as the PROTOBUF entry point does, so they never read PARSEABLE. + mod benches { + use crate::otel::bench; + use opentelemetry_proto::tonic::collector::metrics::v1::ExportMetricsServiceRequest; + use opentelemetry_proto::tonic::common::v1::{ + AnyValue, InstrumentationScope, KeyValue, any_value, + }; + use opentelemetry_proto::tonic::metrics::v1::{ + Exemplar, Gauge, Metric, NumberDataPoint, ResourceMetrics, ScopeMetrics, metric, + number_data_point, + }; + use opentelemetry_proto::tonic::resource::v1::Resource; + + use super::super::{compute_series_hash, process_resource_metrics}; + + const DATA_POINTS_PER_METRIC: usize = 10; + const METRICS_PER_SCOPE: usize = 50; + const ITERS: usize = 20; + + fn string_kv(key: &str, value: impl Into) -> KeyValue { + KeyValue { + key: key.to_string(), + value: Some(AnyValue { + value: Some(any_value::Value::StringValue(value.into())), + }), + ..Default::default() + } + } + + fn int_kv(key: &str, value: i64) -> KeyValue { + KeyValue { + key: key.to_string(), + value: Some(AnyValue { + value: Some(any_value::Value::IntValue(value)), + }), + ..Default::default() + } + } + + fn bool_kv(key: &str, value: bool) -> KeyValue { + KeyValue { + key: key.to_string(), + value: Some(AnyValue { + value: Some(any_value::Value::BoolValue(value)), + }), + ..Default::default() + } + } + + fn data_point(i: usize) -> NumberDataPoint { + let exemplars = if i % 5 == 0 { + vec![Exemplar { + filtered_attributes: vec![ + string_kv("exemplar.trace_id", format!("{i:032x}")), + string_kv("exemplar.span_id", format!("{i:016x}")), + ], + time_unix_nano: 1_700_000_000_000_000_000 + i as u64 * 1_000, + value: Some( + opentelemetry_proto::tonic::metrics::v1::exemplar::Value::AsDouble(1.5), + ), + span_id: vec![0x11; 8], + trace_id: vec![0x22; 16], + }] + } else { + Vec::new() + }; + NumberDataPoint { + attributes: vec![ + string_kv("http.method", "GET"), + string_kv("http.route", "/api/v1/items/:id"), + string_kv("http.status_code", format!("{}", 200 + i % 5)), + string_kv("net.peer.name", "checkout.internal"), + int_kv("retry.count", (i % 3) as i64), + bool_kv("cache.hit", i % 2 == 0), + ], + start_time_unix_nano: 1_700_000_000_000_000_000, + time_unix_nano: 1_700_000_000_000_000_000 + i as u64 * 1_000_000, + exemplars, + flags: 0, + value: Some(number_data_point::Value::AsDouble(i as f64 / 7.0)), + } + } + + fn metric(metric_index: usize, resource_index: usize) -> Metric { + Metric { + name: format!("http.server.request.duration.{metric_index}"), + description: "Duration of HTTP server requests".to_string(), + unit: "s".to_string(), + data: Some(metric::Data::Gauge(Gauge { + data_points: (0..DATA_POINTS_PER_METRIC) + .map(|i| data_point(resource_index * 1000 + metric_index * 10 + i)) + .collect(), + })), + metadata: vec![ + string_kv("otel.scope.name", "bench"), + string_kv("otel.scope.version", "1.2.3"), + ], + } + } + + fn request() -> ExportMetricsServiceRequest { + let resource_metrics = (0..2) + .map(|resource_index| ResourceMetrics { + resource: Some(Resource { + attributes: vec![ + string_kv("service.name", "checkout"), + string_kv("service.namespace", "shop"), + string_kv("service.instance.id", format!("checkout-{resource_index}")), + string_kv("deployment.environment", "production"), + int_kv("process.pid", 4242 + resource_index as i64), + ], + dropped_attributes_count: 0, + entity_refs: vec![], + }), + scope_metrics: (0..2) + .map(|scope_index| ScopeMetrics { + scope: Some(InstrumentationScope { + name: "io.opentelemetry.contrib.bench".to_string(), + version: "0.31.0".to_string(), + attributes: vec![ + string_kv("scope.kind", "server"), + string_kv("scope.extra", format!("{resource_index}-{scope_index}")), + int_kv("scope.ordinal", scope_index), + ], + dropped_attributes_count: 0, + }), + metrics: (0..METRICS_PER_SCOPE) + .map(|metric_index| { + metric(metric_index, resource_index as usize * 10 + scope_index as usize) + }) + .collect(), + schema_url: "https://opentelemetry.io/schemas/1.24.0".to_string(), + }) + .collect(), + schema_url: "https://opentelemetry.io/schemas/1.24.0".to_string(), + }) + .collect(); + ExportMetricsServiceRequest { resource_metrics } + } + + 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, + ) + } + + #[test] + #[ignore = "performance benchmark"] + fn bench_flatten_otel_metrics_protobuf() { + let request = request(); + bench::run("bench_flatten_otel_metrics_protobuf", ITERS, || { + flatten(&request) + }); + } + + /// The rows of the benchmark request, pinned so that a refactor changing + /// them fails a normal `cargo test --lib` run. The digest is of + /// `serde_json::to_vec` of the rows; it was first recorded from the + /// unoptimised flatteners. + #[test] + fn benchmark_request_rows_are_stable() { + let rows = flatten(&request()); + let bytes = serde_json::to_vec(&rows).unwrap(); + use std::hash::Hasher; + let mut hasher = rustc_hash::FxHasher::default(); + hasher.write(&bytes); + // 2000 data points plus one target_info sample per resource + assert_eq!(rows.len(), 2002); + assert_eq!( + (bytes.len(), hasher.finish()), + (2_357_124, 0xf123_85b9_f510_100b), + "flattened rows of the benchmark request changed" + ); + } + + /// Cost of the per-data-point series hash over a typical flattened row. + #[test] + #[ignore = "performance benchmark"] + fn bench_compute_series_hash() { + let rows = flatten(&request()); + let row = rows[0].as_object().expect("object row"); + let mut sum = 0u64; + bench::time_calls("bench_compute_series_hash", 200_000, |_| { + sum = sum.wrapping_add(compute_series_hash(row)); + }); + assert_ne!(sum, 0); + } + } } diff --git a/src/otel/otel_utils.rs b/src/otel/otel_utils.rs index c267235a1..271a1f57c 100644 --- a/src/otel/otel_utils.rs +++ b/src/otel/otel_utils.rs @@ -349,4 +349,74 @@ mod tests { Some(OtelValue::ArrayValue(ArrayValue { values })) if values.is_empty() )); } + + // Release-profile micro-benchmarks, see `crate::otel::bench`. Run with a filter: + // cargo test --release --lib -- --ignored --exact otel::otel_utils::tests::benches::bench_convert_epoch_nano_to_timestamp --nocapture + mod benches { + use super::super::{convert_epoch_nano_to_timestamp, insert_attributes}; + use opentelemetry_proto::tonic::common::v1::{AnyValue, KeyValue, any_value}; + use crate::otel::bench; + + fn string_kv(key: &str, value: &str) -> KeyValue { + KeyValue { + key: key.to_string(), + value: Some(AnyValue { + value: Some(any_value::Value::StringValue(value.to_string())), + }), + ..Default::default() + } + } + + fn bench_attributes() -> Vec { + vec![ + string_kv("http.method", "GET"), + KeyValue { + key: "http.status_code".to_string(), + value: Some(AnyValue { + value: Some(any_value::Value::IntValue(200)), + }), + ..Default::default() + }, + string_kv("http.target", "/api/v1/items/42"), + string_kv("net.host.name", "checkout.example.com"), + string_kv("user_agent.original", "Mozilla/5.0 (compatible; bench)"), + KeyValue { + key: "cache.hit".to_string(), + value: Some(AnyValue { + value: Some(any_value::Value::BoolValue(true)), + }), + ..Default::default() + }, + string_kv("http.request.header.x-request-id", "req-00000000deadbeef"), + string_kv("messaging.system", "kafka"), + ] + } + + #[test] + #[ignore = "performance benchmark"] + fn bench_convert_epoch_nano_to_timestamp() { + let mut len = 0usize; + // Every call formats a distinct nanosecond, as a real batch does + bench::time_calls("bench_convert_epoch_nano_to_timestamp", 200_000, |i| { + len += convert_epoch_nano_to_timestamp( + 1_700_000_000_000_000_000 + i as i64 * 1_000_000, + ) + .len(); + }); + assert_eq!(len, 200_000 * 30); + } + + #[test] + #[ignore = "performance benchmark"] + fn bench_insert_attributes() { + let attributes = bench_attributes(); + let mut sum = 0usize; + bench::time_calls("bench_insert_attributes", 200_000, |_| { + let mut map = serde_json::Map::with_capacity(attributes.len()); + insert_attributes(&mut map, &attributes); + sum += map.len(); + }); + assert_eq!(sum, 200_000 * attributes.len()); + } + } } diff --git a/src/otel/traces.rs b/src/otel/traces.rs index 5aba0b248..2ee22ce02 100644 --- a/src/otel/traces.rs +++ b/src/otel/traces.rs @@ -1159,4 +1159,178 @@ mod tests { "Link records must be enriched with span fields" ); } + + // Release-profile micro-benchmarks. Run with a filter, for example: + // cargo test --release --lib -- --ignored --exact otel::traces::tests::benches::bench_flatten_otel_traces_protobuf --nocapture + // They never touch PARSEABLE: every timestamp is set, so the rows are deterministic. + mod benches { + use crate::otel::bench; + use opentelemetry_proto::tonic::collector::trace::v1::ExportTraceServiceRequest; + use opentelemetry_proto::tonic::common::v1::{ + AnyValue, InstrumentationScope, KeyValue, any_value, + }; + 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 super::super::flatten_otel_traces_protobuf; + + const SPANS_PER_SCOPE: usize = 250; + const ITERS: usize = 20; + + fn string_kv(key: &str, value: impl Into) -> KeyValue { + KeyValue { + key: key.to_string(), + value: Some(AnyValue { + value: Some(any_value::Value::StringValue(value.into())), + }), + ..Default::default() + } + } + + fn int_kv(key: &str, value: i64) -> KeyValue { + KeyValue { + key: key.to_string(), + value: Some(AnyValue { + value: Some(any_value::Value::IntValue(value)), + }), + ..Default::default() + } + } + + fn bool_kv(key: &str, value: bool) -> KeyValue { + KeyValue { + key: key.to_string(), + value: Some(AnyValue { + value: Some(any_value::Value::BoolValue(value)), + }), + ..Default::default() + } + } + + fn span(i: usize) -> Span { + Span { + trace_id: vec![0xab; 16], + span_id: vec![0xcd; 8], + trace_state: "congo=t61rcWkgMzE".to_string(), + parent_span_id: vec![0xef; 8], + flags: 256, + name: format!("POST /api/v1/items/{i}"), + kind: 2, + start_time_unix_nano: 1_700_000_000_000_000_000 + i as u64 * 1_000_000, + end_time_unix_nano: 1_700_000_000_005_000_000 + i as u64 * 1_000_000, + attributes: vec![ + string_kv("http.method", "POST"), + int_kv("http.status_code", (i % 500) as i64), + string_kv("http.route", format!("/api/v1/items/{i}")), + string_kv("net.peer.name", "checkout.internal"), + string_kv("user_agent.original", "bench/1.0"), + bool_kv("sampled", true), + string_kv("messaging.system", "kafka"), + int_kv("messaging.batch_size", (i % 32) as i64), + ], + dropped_attributes_count: 0, + events: vec![Event { + time_unix_nano: 1_700_000_000_001_000_000 + i as u64 * 1_000_000, + name: "request.headers".to_string(), + attributes: vec![ + string_kv("event.kind", "request"), + string_kv("event.target", format!("/api/v1/items/{i}")), + bool_kv("event.ok", i % 2 == 0), + ], + dropped_attributes_count: 0, + }], + dropped_events_count: 0, + links: vec![Link { + trace_id: vec![0x12; 16], + span_id: vec![0x34; 8], + trace_state: String::new(), + attributes: vec![ + string_kv("link.kind", "follows-from"), + int_kv("link.count", 1), + ], + dropped_attributes_count: 0, + flags: 0, + }], + dropped_links_count: 0, + status: Some(Status { + message: String::new(), + code: 1, + }), + } + } + + fn request() -> ExportTraceServiceRequest { + let resource_spans = (0..2) + .map(|resource_index| ResourceSpans { + resource: Some(Resource { + attributes: vec![ + string_kv("service.name", "checkout"), + string_kv("service.version", "1.42.0"), + string_kv("deployment.environment", "production"), + string_kv("host.name", format!("checkout-{resource_index}")), + int_kv("process.pid", 4242 + resource_index as i64), + ], + dropped_attributes_count: 0, + entity_refs: vec![], + }), + scope_spans: (0..2) + .map(|scope_index| ScopeSpans { + scope: Some(InstrumentationScope { + name: "io.opentelemetry.contrib.bench".to_string(), + version: "0.31.0".to_string(), + attributes: vec![ + string_kv("scope.kind", "client"), + string_kv("scope.extra", format!("{resource_index}-{scope_index}")), + int_kv("scope.ordinal", scope_index), + ], + dropped_attributes_count: 0, + }), + spans: (0..SPANS_PER_SCOPE) + .map(|span_index| { + span(resource_index as usize * 1000 + scope_index as usize * 100 + span_index) + }) + .collect(), + schema_url: "https://opentelemetry.io/schemas/1.24.0".to_string(), + }) + .collect(), + schema_url: "https://opentelemetry.io/schemas/1.24.0".to_string(), + }) + .collect(); + ExportTraceServiceRequest { resource_spans } + } + + fn flatten(request: &ExportTraceServiceRequest) -> Vec { + flatten_otel_traces_protobuf(request, "perfbench") + } + + #[test] + #[ignore = "performance benchmark"] + fn bench_flatten_otel_traces_protobuf() { + let request = request(); + bench::run("bench_flatten_otel_traces_protobuf", ITERS, || { + flatten(&request) + }); + } + + /// The rows of the benchmark request, pinned so that a refactor changing + /// them fails a normal `cargo test --lib` run. The digest is of + /// `serde_json::to_vec` of the rows; it was first recorded from the + /// unoptimised flatteners. + #[test] + fn benchmark_request_rows_are_stable() { + let rows = flatten(&request()); + let bytes = serde_json::to_vec(&rows).unwrap(); + use std::hash::Hasher; + let mut hasher = rustc_hash::FxHasher::default(); + hasher.write(&bytes); + // One row per event and one per link of every span + assert_eq!(rows.len(), 2000); + assert_eq!( + (bytes.len(), hasher.finish()), + (3_329_399, 0xa2c6_61df_e91e_9cde), + "flattened rows of the benchmark request changed" + ); + } + } } From 3f02ccd57c846679ae6c317e74855556710a8618 Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Mon, 23 Nov 2026 15:20:29 -0600 Subject: [PATCH 2/7] perf(otel): move flattened rows instead of cloning them process_resource_logs and process_resource_spans built every row, merged the resource-level fields into it, then deep-cloned the finished row into the output vector and dropped the original. The rows vector is local and used up here, so take each row by value and move it into the output instead. Rows, field names and field order are unchanged. Logs benchmark: 126,443 -> 89,218 instructions/row (-29.4%) Traces benchmark: 161,803 -> 110,797 instructions/row (-31.5%) Written by a DeepSeek V4.1 Flash agent; reviewed and re-measured by Claude. Co-Authored-By: Claude Fable 5.2 --- src/otel/logs.rs | 4 ++-- src/otel/traces.rs | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/otel/logs.rs b/src/otel/logs.rs index e571703b5..6f9b7af3c 100644 --- a/src/otel/logs.rs +++ b/src/otel/logs.rs @@ -382,9 +382,9 @@ where Value::String(get_schema_url(resource_log).to_string()), ); - for resource_logs_json in &mut vec_resource_logs_json { + 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.clone())); + vec_otel_json.push(Value::Object(resource_logs_json)); } } diff --git a/src/otel/traces.rs b/src/otel/traces.rs index 2ee22ce02..98cde1e17 100644 --- a/src/otel/traces.rs +++ b/src/otel/traces.rs @@ -146,9 +146,9 @@ where ); // Merge resource-level fields into each span record - for resource_spans_json in &mut vec_resource_spans_json { + 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.clone())); + vec_otel_json.push(Value::Object(resource_spans_json)); } } From 659a3e7e2d57b4741a0c3dca25891e80ca6ca034 Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Mon, 23 Nov 2026 15:27:16 -0600 Subject: [PATCH 3/7] perf(otel): size the per-record maps up front flatten_log_record, flatten_span_record and the event, link, scope and resource maps were built from an empty serde_json Map, which rehashes the keys already inserted at each growth step (0, 3, 7, 14, 28, ...). Give them the capacity their fixed fields and attributes need, and size the per-resource and per-scope row vectors from the record counts. Logs benchmark: 89,218 -> 85,048 instructions/row (-4.7%) Traces benchmark: 110,797 -> 107,149 instructions/row (-3.3%) Written by a DeepSeek V4.1 Flash agent; reviewed and re-measured by Claude. Co-Authored-By: Claude Fable 5.2 --- src/otel/logs.rs | 27 +++++++++++++++++++++------ src/otel/traces.rs | 31 ++++++++++++++++++++++--------- 2 files changed, 43 insertions(+), 15 deletions(-) diff --git a/src/otel/logs.rs b/src/otel/logs.rs index 6f9b7af3c..579c4044b 100644 --- a/src/otel/logs.rs +++ b/src/otel/logs.rs @@ -178,7 +178,10 @@ pub fn flatten_log_record( log_record: &LogRecord, budget: &mut FlattenBudget, ) -> Result, JsonFlattenError> { - let mut log_record_json: Map = Map::new(); + // 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 + log_record.attributes.len()); log_record_json.insert( "time_unix_nano".to_string(), Value::String(convert_epoch_nano_to_timestamp( @@ -313,8 +316,13 @@ fn flatten_scope_log( scope_log: &ScopeLogs, budget: &mut FlattenBudget, ) -> Result>, JsonFlattenError> { - let mut vec_scope_log_json = Vec::new(); - let mut scope_log_json = Map::new(); + 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| scope.attributes.len()), + ); if let Some(scope) = &scope_log.scope { scope_log_json.insert("scope_name".to_string(), Value::String(scope.name.clone())); scope_log_json.insert( @@ -358,10 +366,12 @@ where let mut logs_collected: u64 = 0; for resource_log in resource_logs { - let mut resource_log_json = Map::new(); + let resource = get_resource(resource_log); + let mut resource_log_json = + Map::with_capacity(4 + resource.map_or(0, |resource| resource.attributes.len())); // Process resource attributes if present - if let Some(resource) = get_resource(resource_log) { + if let Some(resource) = resource { insert_attributes(&mut resource_log_json, &resource.attributes); resource_log_json.insert( "resource_dropped_attributes_count".to_string(), @@ -369,8 +379,13 @@ where ); } - let mut vec_resource_logs_json = Vec::new(); 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)?); diff --git a/src/otel/traces.rs b/src/otel/traces.rs index 98cde1e17..33661c6b3 100644 --- a/src/otel/traces.rs +++ b/src/otel/traces.rs @@ -68,8 +68,13 @@ pub const OTEL_TRACES_KNOWN_FIELD_LIST: [&str; 32] = [ /// 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::new(); - let mut scope_span_json = Map::new(); + 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| scope.attributes.len()), + ); for span in &scope_span.spans { let span_record_json = flatten_span_record(span); vec_scope_span_json.extend(span_record_json); @@ -121,10 +126,12 @@ where let mut vec_otel_json = Vec::new(); for resource_span in resource_spans { - let mut resource_span_json = Map::new(); + let resource = get_resource(resource_span); + let mut resource_span_json = + Map::with_capacity(4 + resource.map_or(0, |resource| resource.attributes.len())); // Process resource attributes if present - if let Some(resource) = get_resource(resource_span) { + if let Some(resource) = resource { insert_attributes(&mut resource_span_json, &resource.attributes); resource_span_json.insert( "resource_dropped_attributes_count".to_string(), @@ -133,8 +140,14 @@ where } // Process scope spans - let mut vec_resource_spans_json = Vec::new(); - for scope_span in get_scope_spans(resource_span) { + 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); } @@ -188,7 +201,7 @@ fn flatten_events(events: &[Event], span_start_time_unix_nano: u64) -> Vec Vec> { links .iter() .map(|link| { - let mut link_json = Map::new(); + let mut link_json = Map::with_capacity(5 + link.attributes.len()); link_json.insert( "link_span_id".to_string(), Value::String(hex::encode(&link.span_id)), @@ -327,7 +340,7 @@ fn flatten_kind(kind: i32) -> Map { /// 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(); - let mut span_record_json = Map::new(); + let mut span_record_json = Map::with_capacity(40 + span_record.attributes.len()); span_record_json.insert( "span_trace_id".to_string(), Value::String(hex::encode(&span_record.trace_id)), From 97d17cf0d317691a84051241d1ffc7b440c7de9b Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Mon, 23 Nov 2026 15:32:11 -0600 Subject: [PATCH 4/7] perf(otel): format OTLP timestamps without the strftime machinery convert_epoch_nano_to_timestamp runs twice per log record, metric data point and span, and chrono's formatter reparses the format string and builds a DelayedFormat for every one of them: 252 ns per call. Convert the timestamp with the same chrono call as before, then write the fields into a 30 byte buffer with two-digit digit pairs: 24 ns per call. Years outside 0..=9999, where %Y needs a sign, keep using the formatter; an i64 of nanoseconds cannot reach them. A differential test compares both paths over the ends of the range, every second of a day, hours across the range and 20k pseudorandom values. Logs benchmark: 85,048 -> 77,287 instructions/row (-9.1%) Metrics benchmark: 86,317 -> 77,335 instructions/row (-10.4%) Traces benchmark: 107,149 -> 101,727 instructions/row (-5.1%) Written by a DeepSeek V4.1 Flash agent; reviewed and re-measured by Claude. Co-Authored-By: Claude Fable 5.2 --- src/otel/otel_utils.rs | 143 +++++++++++++++++++++++++++++++++++++++-- 1 file changed, 139 insertions(+), 4 deletions(-) diff --git a/src/otel/otel_utils.rs b/src/otel/otel_utils.rs index 271a1f57c..f1a066df1 100644 --- a/src/otel/otel_utils.rs +++ b/src/otel/otel_utils.rs @@ -16,7 +16,7 @@ * */ -use chrono::DateTime; +use chrono::{Datelike, DateTime, Timelike}; use opentelemetry_proto::tonic::common::v1::{ AnyValue, ArrayValue, KeyValue, KeyValueList, any_value::Value as OtelValue, }; @@ -263,11 +263,79 @@ pub fn insert_attributes(map: &mut Map, attributes: &[KeyValue]) pub fn convert_epoch_nano_to_timestamp(epoch_ns: i64) -> String { if epoch_ns == 0 { return chrono::Utc::now() - .format("%Y-%m-%dT%H:%M:%S%.9fZ") + .format(TIMESTAMP_FORMAT) .to_string(); } - let dt = DateTime::from_timestamp_nanos(epoch_ns).naive_utc(); - dt.format("%Y-%m-%dT%H:%M:%S%.9fZ").to_string() + let timestamp = DateTime::from_timestamp_nanos(epoch_ns).naive_utc(); + // The strftime machinery costs about 200 ns per call; writing the same + // fields of the already-converted timestamp costs a couple of ns. `%Y` + // needs a sign outside 0..=9999 (which an i64 of nanoseconds cannot reach), + // so anything outside keeps using the formatter. + if !(0..=9999).contains(×tamp.year()) { + return timestamp.format(TIMESTAMP_FORMAT).to_string(); + } + format_timestamp(×tamp) +} + +/// `%Y-%m-%dT%H:%M:%S%.9fZ` for a timestamp whose year has four digits +fn format_timestamp(timestamp: &chrono::NaiveDateTime) -> String { + let mut buf = [0u8; TIMESTAMP_LEN]; + let mut pos = 0; + let year = timestamp.year() as u32; + write_two_digits(&mut buf, &mut pos, year / 100); + write_two_digits(&mut buf, &mut pos, year % 100); + buf[pos] = b'-'; + pos += 1; + write_two_digits(&mut buf, &mut pos, timestamp.month()); + buf[pos] = b'-'; + pos += 1; + write_two_digits(&mut buf, &mut pos, timestamp.day()); + buf[pos] = b'T'; + pos += 1; + write_two_digits(&mut buf, &mut pos, timestamp.hour()); + buf[pos] = b':'; + pos += 1; + write_two_digits(&mut buf, &mut pos, timestamp.minute()); + buf[pos] = b':'; + pos += 1; + write_two_digits(&mut buf, &mut pos, timestamp.second()); + buf[pos] = b'.'; + pos += 1; + let nanos = timestamp.nanosecond(); + buf[pos] = b'0' + (nanos / 100_000_000) as u8; + pos += 1; + write_two_digits(&mut buf, &mut pos, (nanos / 1_000_000) % 100); + write_two_digits(&mut buf, &mut pos, (nanos / 10_000) % 100); + write_two_digits(&mut buf, &mut pos, (nanos / 100) % 100); + write_two_digits(&mut buf, &mut pos, nanos % 100); + buf[pos] = b'Z'; + pos += 1; + debug_assert_eq!(pos, TIMESTAMP_LEN); + + String::from_utf8(buf.to_vec()).expect("a timestamp is ASCII") +} + +/// `YYYY-MM-DDTHH:MM:SS.nnnnnnnnnZ` +const TIMESTAMP_FORMAT: &str = "%Y-%m-%dT%H:%M:%S%.9fZ"; +const TIMESTAMP_LEN: usize = 30; + +/// Two-digit decimal pairs `00`..`99` +const DIGIT_PAIRS: [u8; 200] = { + let mut pairs = [0u8; 200]; + let mut value = 0; + while value < 100 { + pairs[value * 2] = b'0' + (value / 10) as u8; + pairs[value * 2 + 1] = b'0' + (value % 10) as u8; + value += 1; + } + pairs +}; + +fn write_two_digits(buf: &mut [u8; TIMESTAMP_LEN], pos: &mut usize, value: u32) { + let pair = value as usize * 2; + buf[*pos] = DIGIT_PAIRS[pair]; + buf[*pos + 1] = DIGIT_PAIRS[pair + 1]; + *pos += 2; } #[cfg(test)] @@ -296,6 +364,73 @@ mod tests { ); } + /// The direct formatter must produce exactly what the strftime path produces, + /// for every kind of value an i64 of nanoseconds can hold: the ends of the + /// range, the whole of one day second by second, hours across the range + /// around the epoch and deterministic pseudorandom values. + #[test] + fn fast_timestamp_matches_strftime() { + let slow = |ns: i64| { + chrono::DateTime::from_timestamp_nanos(ns) + .naive_utc() + .format("%Y-%m-%dT%H:%M:%S%.9fZ") + .to_string() + }; + let mut values = vec![ + i64::MIN, + i64::MIN + 1, + i64::MIN + 999, + i64::MAX, + i64::MAX - 1, + i64::MIN / 2, + i64::MAX / 2, + 1, + -1, + 999_999_999, + 1_000_000_000, + -999_999_999, + -1_000_000_000, + // leap day, year boundaries, month ends + 951_782_400_000_000_000, + 1_709_164_799_999_999_999, + 1_709_164_800_000_000_000, + 1_735_689_599_999_999_999, + 1_735_689_600_000_000_000, + ]; + // every second of one day + for second in 0..86_400 { + values.push(1_700_000_000_000_000_000 + second * 1_000_000_000); + } + // every hour of the first and last thousand hours the range can hold, + // and of the thousand hours around the epoch + for hour in 0..1_000 { + values.push(i64::MIN + hour * 3_600_000_000_000); + values.push(i64::MAX - hour * 3_600_000_000_000); + values.push(hour * 3_600_000_000_000); + values.push(-hour * 3_600_000_000_000); + } + // SplitMix64, as the deterministic-simulation conventions use + let mut state = 0x9e37_79b9_7f4a_7c15u64; + for _ in 0..20_000 { + state = state.wrapping_add(0x9e37_79b9_7f4a_7c15); + let mut z = state; + z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9); + z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb); + values.push((z ^ (z >> 31)) as i64); + } + + for ns in values { + if ns == 0 { + continue; // filled from the wall clock + } + assert_eq!( + convert_epoch_nano_to_timestamp(ns), + slow(ns), + "timestamp for {ns} ns differs" + ); + } + } + fn logs_with_omitted_empty_collection_values() -> Value { serde_json::json!({ "resourceLogs": [{ From 92e93a53cd20c5e14c96a703d877bcd747253a63 Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Mon, 23 Nov 2026 15:33:22 -0600 Subject: [PATCH 5/7] style(otel): rustfmt Written by a DeepSeek V4.1 Flash agent; reviewed and re-measured by Claude. Co-Authored-By: Claude Fable 5.2 --- src/otel/logs.rs | 14 +++++++++++--- src/otel/metrics.rs | 10 ++++++++-- src/otel/otel_utils.rs | 8 +++----- src/otel/traces.rs | 11 +++++++++-- 4 files changed, 31 insertions(+), 12 deletions(-) diff --git a/src/otel/logs.rs b/src/otel/logs.rs index 579c4044b..3a3b12187 100644 --- a/src/otel/logs.rs +++ b/src/otel/logs.rs @@ -1055,14 +1055,21 @@ mod tests { version: "0.31.0".to_string(), attributes: vec![ string_kv("scope.kind", "server"), - string_kv("scope.extra", format!("{resource_index}-{scope_index}")), + string_kv( + "scope.extra", + format!("{resource_index}-{scope_index}"), + ), int_kv("scope.ordinal", scope_index), ], dropped_attributes_count: 0, }), log_records: (0..RECORDS_PER_SCOPE) .map(|record_index| { - record(resource_index as usize * 1000 + scope_index as usize * 100 + record_index) + record( + resource_index as usize * 1000 + + scope_index as usize * 100 + + record_index, + ) }) .collect(), schema_url: "https://opentelemetry.io/schemas/1.24.0".to_string(), @@ -1076,7 +1083,8 @@ mod tests { fn flatten(request: &ExportLogsServiceRequest) -> Vec { let mut budget = FlattenBudget::new(FlattenLimits::DEFAULT); - flatten_otel_protobuf(request, "perfbench", &mut budget).expect("benchmark rows flatten") + flatten_otel_protobuf(request, "perfbench", &mut budget) + .expect("benchmark rows flatten") } #[test] diff --git a/src/otel/metrics.rs b/src/otel/metrics.rs index d4566d7c1..588f3e0d3 100644 --- a/src/otel/metrics.rs +++ b/src/otel/metrics.rs @@ -1586,14 +1586,20 @@ mod tests { version: "0.31.0".to_string(), attributes: vec![ string_kv("scope.kind", "server"), - string_kv("scope.extra", format!("{resource_index}-{scope_index}")), + string_kv( + "scope.extra", + format!("{resource_index}-{scope_index}"), + ), int_kv("scope.ordinal", scope_index), ], dropped_attributes_count: 0, }), metrics: (0..METRICS_PER_SCOPE) .map(|metric_index| { - metric(metric_index, resource_index as usize * 10 + scope_index as usize) + metric( + metric_index, + resource_index as usize * 10 + scope_index as usize, + ) }) .collect(), schema_url: "https://opentelemetry.io/schemas/1.24.0".to_string(), diff --git a/src/otel/otel_utils.rs b/src/otel/otel_utils.rs index f1a066df1..ff8224de7 100644 --- a/src/otel/otel_utils.rs +++ b/src/otel/otel_utils.rs @@ -16,7 +16,7 @@ * */ -use chrono::{Datelike, DateTime, Timelike}; +use chrono::{DateTime, Datelike, Timelike}; use opentelemetry_proto::tonic::common::v1::{ AnyValue, ArrayValue, KeyValue, KeyValueList, any_value::Value as OtelValue, }; @@ -262,9 +262,7 @@ pub fn insert_attributes(map: &mut Map, attributes: &[KeyValue]) pub fn convert_epoch_nano_to_timestamp(epoch_ns: i64) -> String { if epoch_ns == 0 { - return chrono::Utc::now() - .format(TIMESTAMP_FORMAT) - .to_string(); + return chrono::Utc::now().format(TIMESTAMP_FORMAT).to_string(); } let timestamp = DateTime::from_timestamp_nanos(epoch_ns).naive_utc(); // The strftime machinery costs about 200 ns per call; writing the same @@ -489,8 +487,8 @@ mod tests { // cargo test --release --lib -- --ignored --exact otel::otel_utils::tests::benches::bench_convert_epoch_nano_to_timestamp --nocapture mod benches { use super::super::{convert_epoch_nano_to_timestamp, insert_attributes}; - use opentelemetry_proto::tonic::common::v1::{AnyValue, KeyValue, any_value}; use crate::otel::bench; + use opentelemetry_proto::tonic::common::v1::{AnyValue, KeyValue, any_value}; fn string_kv(key: &str, value: &str) -> KeyValue { KeyValue { diff --git a/src/otel/traces.rs b/src/otel/traces.rs index 33661c6b3..c07bc7741 100644 --- a/src/otel/traces.rs +++ b/src/otel/traces.rs @@ -1294,14 +1294,21 @@ mod tests { version: "0.31.0".to_string(), attributes: vec![ string_kv("scope.kind", "client"), - string_kv("scope.extra", format!("{resource_index}-{scope_index}")), + string_kv( + "scope.extra", + format!("{resource_index}-{scope_index}"), + ), int_kv("scope.ordinal", scope_index), ], dropped_attributes_count: 0, }), spans: (0..SPANS_PER_SCOPE) .map(|span_index| { - span(resource_index as usize * 1000 + scope_index as usize * 100 + span_index) + span( + resource_index as usize * 1000 + + scope_index as usize * 100 + + span_index, + ) }) .collect(), schema_url: "https://opentelemetry.io/schemas/1.24.0".to_string(), From b473384d2a9881097ffc7ba66579570d9b718986 Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:14:57 -0600 Subject: [PATCH 6/7] style(otel): use is_multiple_of in the flattening benchmarks Co-Authored-By: Claude Fable 5.2 --- src/otel/logs.rs | 4 ++-- src/otel/metrics.rs | 4 ++-- src/otel/traces.rs | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/otel/logs.rs b/src/otel/logs.rs index 3a3b12187..593b79b92 100644 --- a/src/otel/logs.rs +++ b/src/otel/logs.rs @@ -1001,7 +1001,7 @@ mod tests { fn record(i: usize) -> LogRecord { // Every tenth body is a JSON object, which the log flattener parses and expands - let body = if i % 10 == 0 { + let body = if i.is_multiple_of(10) { format!( r#"{{"event":"checkout","user":{{"id":{i}}},"items":[{{"sku":"a","qty":1}},{{"sku":"b","qty":2}}],"ok":true}}"# ) @@ -1022,7 +1022,7 @@ mod tests { string_kv("http.target", format!("/api/v1/items/{i}")), string_kv("net.host.name", "checkout.example.com"), string_kv("user_agent.original", "Mozilla/5.0 (compatible; bench)"), - bool_kv("cache.hit", i % 3 == 0), + bool_kv("cache.hit", i.is_multiple_of(3)), string_kv("http.request.header.x-request-id", format!("req-{i:016x}")), array_kv("http.request.header.accept-encoding"), ], diff --git a/src/otel/metrics.rs b/src/otel/metrics.rs index 588f3e0d3..e1ee4aac5 100644 --- a/src/otel/metrics.rs +++ b/src/otel/metrics.rs @@ -1515,7 +1515,7 @@ mod tests { } fn data_point(i: usize) -> NumberDataPoint { - let exemplars = if i % 5 == 0 { + let exemplars = if i.is_multiple_of(5) { vec![Exemplar { filtered_attributes: vec![ string_kv("exemplar.trace_id", format!("{i:032x}")), @@ -1538,7 +1538,7 @@ mod tests { string_kv("http.status_code", format!("{}", 200 + i % 5)), string_kv("net.peer.name", "checkout.internal"), int_kv("retry.count", (i % 3) as i64), - bool_kv("cache.hit", i % 2 == 0), + bool_kv("cache.hit", i.is_multiple_of(2)), ], start_time_unix_nano: 1_700_000_000_000_000_000, time_unix_nano: 1_700_000_000_000_000_000 + i as u64 * 1_000_000, diff --git a/src/otel/traces.rs b/src/otel/traces.rs index c07bc7741..19e9865e5 100644 --- a/src/otel/traces.rs +++ b/src/otel/traces.rs @@ -1249,7 +1249,7 @@ mod tests { attributes: vec![ string_kv("event.kind", "request"), string_kv("event.target", format!("/api/v1/items/{i}")), - bool_kv("event.ok", i % 2 == 0), + bool_kv("event.ok", i.is_multiple_of(2)), ], dropped_attributes_count: 0, }], From 5ce26d0bb4881a637405e4157e1c7bc58124f9f8 Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:03:38 -0600 Subject: [PATCH 7/7] fix(otel): do not size row maps from the raw attribute count The pre-sizing added earlier on this branch took the capacity of resource, scope and span maps from the request's attribute count. Those maps are cloned into every row with their capacity, and an attribute without a value is two bytes on the wire and is never inserted. A 0.5 MiB body of 200k valueless scope attributes and 10k records made every row carry a map for 200k entries: about 3.1 GiB of resident memory, against 32 MiB with this change. The hint now counts only the attributes that will be inserted and is capped at 128; larger maps grow as their entries arrive. Rows are unchanged, and the flatten benchmarks move by at most +0.6% (logs 77,677 -> 78,177 instructions per row; still -38.6% against main). Found by an Opus 5.5 review of a later change. Co-Authored-By: Claude Fable 5.2 --- src/otel/logs.rs | 69 +++++++++++++++++++++++++++++++++++++++--- src/otel/otel_utils.rs | 60 ++++++++++++++++++++++++++++++++++++ src/otel/traces.rs | 14 +++++---- 3 files changed, 133 insertions(+), 10 deletions(-) diff --git a/src/otel/logs.rs b/src/otel/logs.rs index 593b79b92..ca3a98eb7 100644 --- a/src/otel/logs.rs +++ b/src/otel/logs.rs @@ -15,6 +15,7 @@ * along with this program. If not, see . * */ +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; @@ -181,7 +182,7 @@ pub fn flatten_log_record( // 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 + log_record.attributes.len()); + Map::with_capacity(16 + attribute_capacity(&log_record.attributes)); log_record_json.insert( "time_unix_nano".to_string(), Value::String(convert_epoch_nano_to_timestamp( @@ -321,7 +322,7 @@ fn flatten_scope_log( 5 + scope_log .scope .as_ref() - .map_or(0, |scope| scope.attributes.len()), + .map_or(0, |scope| attribute_capacity(&scope.attributes)), ); if let Some(scope) = &scope_log.scope { scope_log_json.insert("scope_name".to_string(), Value::String(scope.name.clone())); @@ -367,8 +368,9 @@ where 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| resource.attributes.len())); + 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 { @@ -456,6 +458,65 @@ mod tests { use opentelemetry_proto::tonic::logs::v1::{LogRecord, LogsData, ResourceLogs, ScopeLogs}; use serde_json::json; + /// Resident memory of this process in bytes + #[cfg(target_os = "linux")] + fn resident_bytes() -> usize { + let statm = std::fs::read_to_string("/proc/self/statm").unwrap(); + let pages: usize = statm.split_whitespace().nth(1).unwrap().parse().unwrap(); + pages * 4096 + } + + // The scope map is cloned into every record's row, capacity included. Sized + // by the raw attribute count, 200k valueless scope attributes (two bytes + // each on the wire) made every one of 10k rows carry a map for 200k + // entries: a body of half a megabyte held about 3 GiB. + #[test] + #[cfg(target_os = "linux")] + #[ignore = "measures the resident memory of the process; run it alone"] + fn valueless_scope_attributes_do_not_inflate_every_row() { + use opentelemetry_proto::tonic::common::v1::InstrumentationScope; + + let logs = LogsData { + resource_logs: vec![ResourceLogs { + scope_logs: vec![ScopeLogs { + scope: Some(InstrumentationScope { + attributes: vec![KeyValue::default(); 200_000], + ..Default::default() + }), + log_records: (0..10_000u64) + .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, + ..Default::default() + }) + .collect(), + ..Default::default() + }], + ..Default::default() + }], + }; + + let before = resident_bytes(); + let rows = flatten_otel_logs( + &logs, + "tenant", + &mut FlattenBudget::new(crate::utils::json::flatten::GENEROUS_LIMITS), + ) + .unwrap(); + let grown = resident_bytes().saturating_sub(before); + println!( + "{} rows hold {} MiB of resident memory", + rows.len(), + grown / (1024 * 1024) + ); + assert_eq!(rows.len(), 10_000); + assert!( + grown < 256 * 1024 * 1024, + "{} MiB for 10k rows without attributes", + grown / (1024 * 1024) + ); + } + fn flatten_record( number: i32, text: &str, diff --git a/src/otel/otel_utils.rs b/src/otel/otel_utils.rs index ff8224de7..5b6ed5616 100644 --- a/src/otel/otel_utils.rs +++ b/src/otel/otel_utils.rs @@ -250,6 +250,29 @@ pub fn insert_bool_if_some(map: &mut Map, key: &str, option: &Opt } } +/// Largest capacity hint taken from the attribute count of one message +const ATTRIBUTE_CAPACITY_HINT_MAX: usize = 128; + +/// Capacity hint for a map that `insert_attributes` fills from `attributes`. +/// +/// The count comes from the request, and resource, scope and span maps sized by +/// it are cloned into every row they belong to, capacity included. So only the +/// attributes that will be inserted are counted (one without a value is two +/// bytes on the wire), and the hint is capped: a larger map still grows as its +/// entries arrive. +pub fn attribute_capacity(attributes: &[KeyValue]) -> usize { + attributes + .iter() + .filter(|attribute| { + attribute + .value + .as_ref() + .is_some_and(|value| value.value.is_some()) + }) + .take(ATTRIBUTE_CAPACITY_HINT_MAX) + .count() +} + pub fn insert_attributes(map: &mut Map, attributes: &[KeyValue]) { for attribute in attributes { if let Some(value) = &attribute.value @@ -362,6 +385,43 @@ mod tests { ); } + // A capacity hint that followed the raw attribute count would let a request + // of valueless attributes (two bytes each) size a scope map that is then + // cloned, capacity and all, into every row. + #[test] + fn attribute_capacity_counts_inserted_attributes_and_is_capped() { + let valued = |key: &str| KeyValue { + key: key.to_string(), + value: Some(AnyValue { + value: Some(OtelValue::StringValue("v".to_string())), + }), + ..Default::default() + }; + let empty_any = KeyValue { + key: "k".to_string(), + value: Some(AnyValue { value: None }), + ..Default::default() + }; + + assert_eq!(attribute_capacity(&[]), 0); + assert_eq!(attribute_capacity(&vec![KeyValue::default(); 200_000]), 0); + assert_eq!(attribute_capacity(&vec![empty_any; 1_000]), 0); + assert_eq!( + attribute_capacity(&[valued("a"), KeyValue::default(), valued("b")]), + 2 + ); + assert_eq!( + attribute_capacity(&vec![valued("a"); 10_000]), + ATTRIBUTE_CAPACITY_HINT_MAX + ); + + // The hint never changes what is inserted + let attributes = vec![valued("a"), KeyValue::default(), valued("b")]; + let mut map = Map::with_capacity(attribute_capacity(&attributes)); + insert_attributes(&mut map, &attributes); + assert_eq!(map.len(), 2); + } + /// The direct formatter must produce exactly what the strftime path produces, /// for every kind of value an i64 of nanoseconds can hold: the ends of the /// range, the whole of one day second by second, hours across the range diff --git a/src/otel/traces.rs b/src/otel/traces.rs index 19e9865e5..b0c142081 100644 --- a/src/otel/traces.rs +++ b/src/otel/traces.rs @@ -28,6 +28,7 @@ use serde_json::{Map, Value}; use crate::metrics::increment_traces_collected_by_date; 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; @@ -73,7 +74,7 @@ fn flatten_scope_span(scope_span: &ScopeSpans, tenant_id: &str) -> Vec Vec Vec> { links .iter() .map(|link| { - let mut link_json = Map::with_capacity(5 + link.attributes.len()); + 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)), @@ -340,7 +342,7 @@ fn flatten_kind(kind: i32) -> Map { /// 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(); - let mut span_record_json = Map::with_capacity(40 + span_record.attributes.len()); + let mut span_record_json = Map::with_capacity(40 + attribute_capacity(&span_record.attributes)); span_record_json.insert( "span_trace_id".to_string(), Value::String(hex::encode(&span_record.trace_id)),