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..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; @@ -178,7 +179,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 + attribute_capacity(&log_record.attributes)); log_record_json.insert( "time_unix_nano".to_string(), Value::String(convert_epoch_nano_to_timestamp( @@ -313,8 +317,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| attribute_capacity(&scope.attributes)), + ); 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 +367,13 @@ 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| attribute_capacity(&resource.attributes)), + ); // 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 +381,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)?); @@ -382,9 +399,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)); } } @@ -441,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, @@ -913,4 +989,206 @@ 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.is_multiple_of(10) { + 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.is_multiple_of(3)), + 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..e1ee4aac5 100644 --- a/src/otel/metrics.rs +++ b/src/otel/metrics.rs @@ -1461,4 +1461,211 @@ 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.is_multiple_of(5) { + 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.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, + 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..5b6ed5616 100644 --- a/src/otel/otel_utils.rs +++ b/src/otel/otel_utils.rs @@ -16,7 +16,7 @@ * */ -use chrono::DateTime; +use chrono::{DateTime, Datelike, Timelike}; use opentelemetry_proto::tonic::common::v1::{ AnyValue, ArrayValue, KeyValue, KeyValueList, any_value::Value as OtelValue, }; @@ -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 @@ -262,12 +285,78 @@ 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") - .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 + // 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(); } - let dt = DateTime::from_timestamp_nanos(epoch_ns).naive_utc(); - dt.format("%Y-%m-%dT%H:%M:%S%.9fZ").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 +385,110 @@ 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 + /// 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": [{ @@ -349,4 +542,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 crate::otel::bench; + use opentelemetry_proto::tonic::common::v1::{AnyValue, KeyValue, any_value}; + + 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..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; @@ -68,8 +69,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| attribute_capacity(&scope.attributes)), + ); for span in &scope_span.spans { let span_record_json = flatten_span_record(span); vec_scope_span_json.extend(span_record_json); @@ -121,10 +127,13 @@ 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| attribute_capacity(&resource.attributes)), + ); // 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 +142,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); } @@ -146,9 +161,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)); } } @@ -188,7 +203,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 + attribute_capacity(&link.attributes)); link_json.insert( "link_span_id".to_string(), Value::String(hex::encode(&link.span_id)), @@ -327,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::new(); + 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)), @@ -1159,4 +1174,185 @@ 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.is_multiple_of(2)), + ], + 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" + ); + } + } }