diff --git a/src/handlers/http/ingest.rs b/src/handlers/http/ingest.rs index e9b01930e..9a0c1e786 100644 --- a/src/handlers/http/ingest.rs +++ b/src/handlers/http/ingest.rs @@ -34,7 +34,7 @@ use crate::event::format::known_schema::{self, KNOWN_SCHEMA_LIST}; use crate::event::format::{self, EventFormat, LogSource, LogSourceEntry}; use crate::event::{self, FORMAT_KEY, USER_AGENT_KEY}; use crate::handlers::http::modal::utils::ingest_utils::{ - ingest_helper, otel_success_response, process_otel_content, validate_stream_for_ingestion, + ingest_helper, otel_response, process_otel_content, validate_stream_for_ingestion, }; use crate::handlers::{ DatasetTag, EXTRACT_LOG_KEY, LOG_SOURCE_KEY, STREAM_NAME_HEADER_KEY, TELEMETRY_TYPE_KEY, @@ -312,9 +312,10 @@ pub async fn handle_otel_logs_ingestion( e })?; - process_otel_content(&req, body, &stream_name, &log_source, TelemetryType::Logs).await?; + let ingested = + process_otel_content(&req, body, &stream_name, &log_source, TelemetryType::Logs).await?; - Ok(otel_success_response(&req)) + Ok(otel_response(&req, TelemetryType::Logs, &ingested)) } // Handler for POST /v1/metrics to ingest OTEL metrics @@ -338,7 +339,7 @@ pub async fn handle_otel_metrics_ingestion( e })?; - process_otel_content( + let ingested = process_otel_content( &req, body, &stream_name, @@ -347,7 +348,7 @@ pub async fn handle_otel_metrics_ingestion( ) .await?; - Ok(otel_success_response(&req)) + Ok(otel_response(&req, TelemetryType::Metrics, &ingested)) } // Handler for POST /v1/traces to ingest OTEL traces @@ -371,9 +372,10 @@ pub async fn handle_otel_traces_ingestion( e })?; - process_otel_content(&req, body, &stream_name, &log_source, TelemetryType::Traces).await?; + let ingested = + process_otel_content(&req, body, &stream_name, &log_source, TelemetryType::Traces).await?; - Ok(otel_success_response(&req)) + Ok(otel_response(&req, TelemetryType::Traces, &ingested)) } // Handler for POST /api/v1/logstream/{logstream} diff --git a/src/handlers/http/kinesis.rs b/src/handlers/http/kinesis.rs index 7625a41a3..239ed50ac 100644 --- a/src/handlers/http/kinesis.rs +++ b/src/handlers/http/kinesis.rs @@ -376,8 +376,18 @@ mod tests { .iter() .map(|row| { let mut row = row.clone(); - crate::utils::json::flatten::flatten(&mut row, "_", None, None, None, false) - .unwrap(); + crate::utils::json::flatten::flatten( + &mut row, + "_", + None, + None, + None, + false, + &mut crate::utils::json::flatten::FlattenBudget::new( + crate::utils::json::flatten::GENEROUS_LIMITS, + ), + ) + .unwrap(); serde_json::to_vec(&row).unwrap().len() }) .sum(); diff --git a/src/handlers/http/logstream.rs b/src/handlers/http/logstream.rs index 7105f572f..a845ef3e6 100644 --- a/src/handlers/http/logstream.rs +++ b/src/handlers/http/logstream.rs @@ -150,7 +150,15 @@ pub async fn detect_schema(Json(json): Json) -> Result Result<(), PostError> { +) -> Result { let p_custom_fields = get_otel_custom_fields_from_header(req, log_source); let content_type = req .headers() @@ -126,18 +143,35 @@ pub async fn process_otel_content( let _ = s.send(r); }); - if let Err(e) = r.await.map_err(|e| PostError::CustomError(e.to_string()))? { - Err(e) - } else { - Ok(()) - } + r.await.map_err(|e| PostError::CustomError(e.to_string()))? } -/// Response for an OTEL export request that was ingested in full. OTLP/HTTP +/// How an OTEL export request that was not refused was ingested +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum OtelIngested { + /// Every record was staged + Full, + /// Only some records were staged: a client error stopped the request after + /// at least one chunk of its rows was staged + Partial { + /// Log records, data points or spans not staged + rejected: i64, + /// Why the rest was not staged + message: String, + }, +} + +/// Response for an OTEL export request that was not refused. OTLP/HTTP /// answers in the encoding of the request: for protobuf that is an /// `Export*ServiceResponse`, whose full-success form encodes to zero bytes. -/// JSON requests keep the empty response they always had. -pub fn otel_success_response(req: &HttpRequest) -> HttpResponse { +/// JSON requests keep the empty response they always had when ingested in +/// full. A partial success sets `partial_success` (OTLP/HTTP requires status +/// 200 for it), in the request's own encoding. +pub fn otel_response( + req: &HttpRequest, + telemetry_type: TelemetryType, + ingested: &OtelIngested, +) -> HttpResponse { let protobuf = req .headers() .get(CONTENT_TYPE) @@ -148,7 +182,71 @@ pub fn otel_success_response(req: &HttpRequest) -> HttpResponse { if protobuf { response.content_type(CONTENT_TYPE_PROTOBUF); } - response.finish() + match ingested { + OtelIngested::Full => response.finish(), + OtelIngested::Partial { rejected, message } => { + if !protobuf { + response.content_type(CONTENT_TYPE_JSON); + } + response.body(partial_success_body( + telemetry_type, + *rejected, + message, + protobuf, + )) + } + } +} + +/// The `Export*ServiceResponse` of a partial success, encoded +fn partial_success_body( + telemetry_type: TelemetryType, + rejected: i64, + message: &str, + protobuf: bool, +) -> Vec { + use opentelemetry_proto::tonic::collector::{ + logs::v1::{ExportLogsPartialSuccess, ExportLogsServiceResponse}, + metrics::v1::{ExportMetricsPartialSuccess, ExportMetricsServiceResponse}, + trace::v1::{ExportTracePartialSuccess, ExportTraceServiceResponse}, + }; + fn encode(message: M, protobuf: bool) -> Vec { + if protobuf { + message.encode_to_vec() + } else { + serde_json::to_vec(&message).expect("OTLP responses serialise") + } + } + let error_message = message.to_string(); + match telemetry_type { + TelemetryType::Metrics => encode( + ExportMetricsServiceResponse { + partial_success: Some(ExportMetricsPartialSuccess { + rejected_data_points: rejected, + error_message, + }), + }, + protobuf, + ), + TelemetryType::Traces => encode( + ExportTraceServiceResponse { + partial_success: Some(ExportTracePartialSuccess { + rejected_spans: rejected, + error_message, + }), + }, + protobuf, + ), + _ => encode( + ExportLogsServiceResponse { + partial_success: Some(ExportLogsPartialSuccess { + rejected_log_records: rejected, + error_message, + }), + }, + protobuf, + ), + } } /// Payload encodings accepted by the OTEL HTTP endpoints. @@ -187,7 +285,14 @@ fn handle_otel_ingestion( telemetry_type: TelemetryType, content_type: Option, tenant_id: Option, -) -> Result<(), PostError> { +) -> Result { + let target = OtelTarget { + stream_name: &stream_name, + log_source: &log_source, + p_custom_fields: &p_custom_fields, + telemetry_type, + tenant_id: &tenant_id, + }; match content_type { Some(content_type) => match classify_otel_content_type(&content_type) { Some(OtelContentType::Json) => { @@ -200,54 +305,368 @@ fn handle_otel_ingestion( return Err(PostError::SerdeError(e)); } }; - if let Err(e) = flatten_and_push_logs( - json, - &stream_name, - &log_source, - &p_custom_fields, - None, - telemetry_type, - &tenant_id, - ) { + ingest_otel_json(json, body.len(), &target).inspect_err(|e| { error!("Ingestion failed for stream {stream_name}: {e}"); - return Err(e); - } + }) } Some(OtelContentType::Protobuf) => { - if let Err(e) = flatten_and_push_otel_protobuf( - &body, - &stream_name, - &log_source, - &p_custom_fields, - telemetry_type, - &tenant_id, - ) { + flatten_and_push_otel_protobuf(body, &target, || ProtobufOptions { + max_payload: max_event_payload_size(), + flatten_exemplars: PARSEABLE.options.otel_flatten_exemplars, + }) + .inspect_err(|e| { error!("Ingestion failed for stream {stream_name}: {e}"); - return Err(e); - } + }) } None => { error!( "Ingestion failed for stream {stream_name}: Unsupported Content-Type: {content_type}. Expected application/json or application/x-protobuf" ); - return Err(PostError::Invalid(anyhow::anyhow!( + Err(PostError::Invalid(anyhow::anyhow!( "Ingestion failed for stream {stream_name}: Unsupported Content-Type: {content_type}. Expected application/json or application/x-protobuf" - ))); + ))) } }, None => { error!( "Ingestion failed for stream {stream_name}: Missing Content-Type header. Expected application/json or application/x-protobuf" ); - return Err(PostError::Invalid(anyhow::anyhow!( + Err(PostError::Invalid(anyhow::anyhow!( "Ingestion failed for stream {stream_name}: Missing Content-Type header. Expected application/json or application/x-protobuf" - ))); + ))) } } - Ok(()) } -/// An OTLP/HTTP export request decoded from its protobuf encoding. +/// Where the rows of one OTEL request are staged +struct OtelTarget<'a> { + stream_name: &'a str, + log_source: &'a LogSource, + p_custom_fields: &'a HashMap, + telemetry_type: TelemetryType, + tenant_id: &'a Option, +} + +/// The resources of a decoded OTLP request, from either encoding +#[derive(Debug, Clone, Copy)] +enum OtelResources<'a> { + Logs(&'a [ResourceLogs]), + Metrics(&'a [ResourceMetrics]), + Traces(&'a [ResourceSpans]), +} + +impl OtelResources<'_> { + /// What a partial success counts as rejected, for the whole request: log + /// records, data points or spans + fn total(&self) -> u64 { + let count = |n: usize| n as u64; + match self { + Self::Logs(resources) => resources + .iter() + .flat_map(|r| &r.scope_logs) + .map(|s| count(s.log_records.len())) + .sum(), + Self::Metrics(resources) => resources + .iter() + .flat_map(|r| &r.scope_metrics) + .flat_map(|s| &s.metrics) + .map(|metric| { + use opentelemetry_proto::tonic::metrics::v1::metric::Data; + count(match &metric.data { + Some(Data::Gauge(m)) => m.data_points.len(), + Some(Data::Sum(m)) => m.data_points.len(), + Some(Data::Histogram(m)) => m.data_points.len(), + Some(Data::ExponentialHistogram(m)) => m.data_points.len(), + Some(Data::Summary(m)) => m.data_points.len(), + None => 0, + }) + }) + .sum(), + Self::Traces(resources) => resources + .iter() + .flat_map(|r| &r.scope_spans) + .map(|s| count(s.spans.len())) + .sum(), + } + } + + /// Leaf records of the request: log records, metrics or spans. A request + /// without any has no rows. + fn records(&self) -> u64 { + let count = |n: usize| n as u64; + match self { + Self::Logs(resources) => resources + .iter() + .flat_map(|r| &r.scope_logs) + .map(|s| count(s.log_records.len())) + .sum(), + Self::Metrics(resources) => resources + .iter() + .flat_map(|r| &r.scope_metrics) + .map(|s| count(s.metrics.len())) + .sum(), + Self::Traces(resources) => resources + .iter() + .flat_map(|r| &r.scope_spans) + .map(|s| count(s.spans.len())) + .sum(), + } + } + + /// Hands the rows of the request to `sink`, one at a time + fn flatten_into( + &self, + budget: &mut FlattenBudget, + flatten_exemplars: bool, + sink: &mut S, + ) -> Result<(), S::Error> { + match self { + Self::Logs(resources) => flatten_logs_into(resources, budget, sink), + Self::Metrics(resources) => flatten_metrics_into(resources, flatten_exemplars, sink), + Self::Traces(resources) => flatten_traces_into(resources, sink), + } + } + + fn signal(&self) -> Signal { + match self { + Self::Logs(_) => Signal::Logs, + Self::Metrics(_) => Signal::Metrics, + Self::Traces(_) => Signal::Traces, + } + } +} + +/// The refusal of a request whose rows hold more than `max` estimated bytes in all +fn expansion_error(max: u64) -> PostError { + PostError::Invalid(anyhow::anyhow!( + "The rows of the request take more than the {max} bytes allowed ({EXPANSION_FACTOR} times the length of its body, at least {MIN_EXPANDED_BYTES} and at most {EXPANSION_CEILING_FACTOR} times the payload limit). Split the batch into smaller requests, or send fewer resource, scope and span attributes per record" + )) +} + +/// Limits of staging one OTEL request +#[derive(Debug, Clone, Copy)] +struct StageLimits { + chunk: ChunkLimits, + /// Estimated row bytes the request may stage in all, see `max_expanded_bytes` + max_expanded: u64, + flatten: FlattenLimits, +} + +impl StageLimits { + /// The limits of staging a request whose body (decompressed) is `body_len` + /// bytes, under a payload limit of `max_payload` bytes + fn for_body(body_len: usize, max_payload: usize, flatten: FlattenLimits) -> Self { + Self { + chunk: CHUNK_LIMITS, + max_expanded: max_expanded_bytes(body_len, max_payload), + flatten, + } + } +} + +/// Flattens one OTEL request and hands its rows to `stage` in chunks (see +/// `Chunker`), so that they are never all held at once. The rows passed on are +/// counted against `limits.max_expanded` as they go: the chunk that would pass +/// it is refused with `expansion_error`, like any other chunk `stage` refuses. +/// Stops at the first error. Needs no server state. +/// +/// Each chunk is staged as an event of its own, so its column types are inferred +/// against the schema the stream has then, which includes what the chunk before +/// it committed. When the type of a value changes between the records of a +/// request cut into several chunks, the value can land in a differently named +/// column than if the request were staged as one batch: `{"x": true}` then +/// `{"x": "on"}` give `x` (Boolean) and `x_utf8` in two chunks, but `x` (Utf8) +/// and `x_bool` in one. That is exactly what two separate requests give. A +/// request that fits in one chunk is staged as one batch. +fn stage_otel_rows( + limits: StageLimits, + flatten: impl FnOnce( + &mut FlattenBudget, + &mut dyn RowSink, + ) -> Result<(), PostError>, + mut stage: impl FnMut(Vec) -> Result<(), PostError>, +) -> (Result<(), PostError>, Staged) { + // The JSON log bodies of every record of the request share one budget + let mut budget = FlattenBudget::new(limits.flatten); + let mut expanded = 0u64; + let mut chunker = Chunker::new(limits.chunk, |rows: Vec, bytes: usize| { + expanded = expanded.saturating_add(bytes as u64); + if expanded > limits.max_expanded { + return Err(expansion_error(limits.max_expanded)); + } + stage(rows) + }); + let result = flatten(&mut budget, &mut chunker).and_then(|()| chunker.finish()); + let staged = chunker.staged(); + (result, staged) +} + +/// The answer to an OTEL request that `stage_otel_rows` staged as `staged`. +/// +/// Before any chunk is staged, errors are returned as they are. Once at least +/// one chunk is staged, the request stopped at the first failing chunk: +/// - a client error (status 4xx: a schema conflict, the field count limit, a +/// flatten limit, the expansion cap, a protobuf record that does not decode +/// or is too large) becomes a partial success that reports every record not +/// staged in full as rejected, answered with status 200 as OTLP/HTTP requires. +/// `total` gives the rejected unit for the whole request (log records, data +/// points or spans), and is only asked for here; +/// - a server error keeps its 5xx status, and the chunks already staged stay +/// staged. OTLP/HTTP exporters retry only 429, 502, 503 and 504: after a 500 +/// (most staging errors) the client counts the whole batch as failed and does +/// not send it again, so the rows staged are kept but counted as not delivered; +/// after a 503 (some object storage errors) it sends the whole request again, +/// and the rows of the chunks already staged are staged twice. +fn otel_outcome( + signal: Signal, + stream_name: &str, + result: Result<(), PostError>, + staged: &Staged, + total: impl FnOnce() -> u64, +) -> Result { + match result { + Ok(()) => Ok(OtelIngested::Full), + Err(error) + if staged.chunks > 0 + && actix_web::ResponseError::status_code(&error).is_client_error() => + { + let staged_units = match signal { + Signal::Metrics => staged.points, + Signal::Logs | Signal::Traces => staged.records, + }; + let rejected = total().saturating_sub(staged_units) as i64; + warn!( + "Ingestion into stream {stream_name} stopped after {} rows: {error}. {rejected} records rejected", + staged.rows + ); + Ok(OtelIngested::Partial { + rejected, + message: error.to_string(), + }) + } + Err(error) => Err(error), + } +} + +/// Stages the rows of one OTEL request of `records` leaf records (log records, +/// metrics or spans), whose body is `body_len` bytes, in chunks into its stream, +/// see `stage_otel_rows` and `otel_outcome`. The caller has checked the dataset +/// field count (`verify_otel_fields_count`). A request without records has no +/// rows, and is answered without the stream. +fn ingest_otel_rows( + signal: Signal, + target: &OtelTarget<'_>, + body_len: usize, + records: u64, + flatten: impl FnOnce( + &mut FlattenBudget, + &mut dyn RowSink, + ) -> Result<(), PostError>, + total: impl FnOnce() -> u64, +) -> Result { + if records == 0 { + return Ok(OtelIngested::Full); + } + let tenant_str = target.tenant_id.as_deref().unwrap_or(DEFAULT_TENANT); + let limits = StageLimits::for_body( + body_len, + max_event_payload_size(), + FlattenLimits::from_config(), + ); + let mut staging = Staging::new(target.stream_name, target.tenant_id)?; + let (result, staged) = stage_otel_rows(limits, flatten, |rows| { + staging.push( + Value::Array(rows), + target.log_source, + target.p_custom_fields, + None, + target.telemetry_type, + ) + }); + if result.is_ok() || staged.chunks > 0 { + count_collected(signal, staged.records, tenant_str); + } + otel_outcome(signal, target.stream_name, result, &staged, total) +} + +/// `ingest_otel_rows` for a request decoded whole (OTLP JSON) +fn ingest_otel_resources( + resources: OtelResources<'_>, + body_len: usize, + target: &OtelTarget<'_>, +) -> Result { + let flatten_exemplars = PARSEABLE.options.otel_flatten_exemplars; + ingest_otel_rows( + resources.signal(), + target, + body_len, + resources.records(), + |budget, sink| resources.flatten_into(budget, flatten_exemplars, sink), + || resources.total(), + ) +} + +/// Counts for `tenant_id` the leaf records (log records, spans, metrics) whose rows +/// were all staged +fn count_collected(signal: Signal, records: u64, tenant_id: &str) { + if records == 0 { + return; + } + let date = Utc::now().date_naive().to_string(); + match signal { + Signal::Logs => increment_logs_collected_by_date(records, &date, tenant_id), + Signal::Metrics => increment_metrics_collected_by_date(records, &date, tenant_id), + Signal::Traces => increment_traces_collected_by_date(records, &date, tenant_id), + } +} + +/// The OTEL arms of `handle_otel_ingestion` for a JSON body of `body_len` bytes. +/// The dataset field count is checked before the body is decoded into a request. +fn ingest_otel_json( + json: Value, + body_len: usize, + target: &OtelTarget<'_>, +) -> Result { + let normalise = PARSEABLE.options.normalise_otel_payload; + // `{}` is the JSON encoding of an empty request, which the generated types + // refuse for the collection it leaves out; it has no rows + let empty = |json: &Value| -> Result { + verify_otel_fields_count(target.stream_name, target.tenant_id)?; + Ok(json.as_object().is_some_and(|fields| fields.is_empty())) + }; + match target.log_source { + LogSource::OtelLogs | LogSource::OtelMetrics | LogSource::OtelTraces if empty(&json)? => { + Ok(OtelIngested::Full) + } + LogSource::OtelLogs => { + let logs: LogsData = deserialize_otel_json(json, normalise)?; + ingest_otel_resources(OtelResources::Logs(&logs.resource_logs), body_len, target) + } + LogSource::OtelMetrics => { + let metrics: MetricsData = deserialize_otel_json(json, normalise)?; + ingest_otel_resources( + OtelResources::Metrics(&metrics.resource_metrics), + body_len, + target, + ) + } + LogSource::OtelTraces => { + let traces: TracesData = deserialize_otel_json(json, normalise)?; + ingest_otel_resources( + OtelResources::Traces(&traces.resource_spans), + body_len, + target, + ) + } + other => Err(PostError::Invalid(anyhow::anyhow!( + "OTLP ingestion requires an OTLP log source, got {other}" + ))), + } +} + +/// An OTLP/HTTP export request decoded from its protobuf encoding, whole (as the +/// tests compare against; ingestion decodes one record at a time) +#[cfg(test)] #[derive(Debug)] enum OtelProtobufRequest { Logs(ExportLogsServiceRequest), @@ -265,6 +684,7 @@ enum OtelProtobufError { NotOtel(LogSource), } +#[cfg(test)] impl OtelProtobufRequest { /// Decodes the export request that `log_source` selects. The whole body is /// decoded before any row is built, so a body that fails to decode yields @@ -279,56 +699,185 @@ impl OtelProtobufRequest { } } - /// Flattens into the same rows the JSON encoding of this request produces. + /// Flattens into the same rows the JSON encoding of this request produces, + /// all at once + #[cfg(test)] fn flatten( &self, tenant_id: &str, budget: &mut FlattenBudget, - ) -> Result, JsonFlattenError> { + ) -> Result, crate::utils::json::flatten::JsonFlattenError> { match self { - Self::Logs(message) => flatten_otel_logs_protobuf(message, tenant_id, budget), - Self::Metrics(message) => Ok(flatten_otel_metrics_protobuf(message, tenant_id)), - Self::Traces(message) => Ok(flatten_otel_traces_protobuf(message, tenant_id)), + Self::Logs(message) => { + crate::otel::logs::flatten_otel_protobuf(message, tenant_id, budget) + } + Self::Metrics(message) => Ok(crate::otel::metrics::flatten_otel_metrics_protobuf( + message, tenant_id, + )), + Self::Traces(message) => Ok(crate::otel::traces::flatten_otel_traces_protobuf( + message, tenant_id, + )), } } } -/// Protobuf counterpart of the OTEL arms of `flatten_and_push_logs`: the typed -/// request is decoded straight from the body instead of going through a JSON -/// value tree, then shares flattening limits and the staging path with JSON. -/// The body size is capped by the `PayloadConfig` of the OTEL routes. +/// What the protobuf path needs from the server configuration, read by the caller +/// so that a body that does not decode is refused before the configuration is +#[derive(Debug, Clone, Copy)] +struct ProtobufOptions { + /// `P_MAX_EVENT_PAYLOAD_SIZE`, which caps the decoded size of one record + max_payload: usize, + flatten_exemplars: bool, +} + +/// Protobuf counterpart of `ingest_otel_json`. The body is read one leaf record +/// at a time (`protobuf_stream`): `outline` first walks the levels above the +/// records, so a body broken there is refused before anything is staged (and +/// before the configuration is read), then every record is decoded once, its rows +/// handed over in chunks, and dropped. So the decoded request is never held whole. +/// A record that does not decode, or would be too large once decoded, is a client +/// error met while staging: a partial success once chunks were staged. The body +/// size is capped by the `PayloadConfig` of the OTEL routes. fn flatten_and_push_otel_protobuf( - body: &[u8], - stream_name: &str, - log_source: &LogSource, - p_custom_fields: &HashMap, - telemetry_type: TelemetryType, - tenant_id: &Option, + body: web::Bytes, + target: &OtelTarget<'_>, + options: impl FnOnce() -> ProtobufOptions, +) -> Result { + let (signal, outline, options) = outline_otel_protobuf(&body, target, options)?; + verify_otel_fields_count(target.stream_name, target.tenant_id)?; + ingest_otel_rows( + signal, + target, + body.len(), + outline.records, + |budget, sink| flatten_otel_protobuf(&body, signal, &options, target, budget, sink), + || protobuf_total(&body, signal, &outline), + ) +} + +/// The signal and outline of a protobuf body, and the options to read it with, +/// read only once the body is known to be a request (see `refusal`) +fn outline_otel_protobuf( + body: &web::Bytes, + target: &OtelTarget<'_>, + options: impl FnOnce() -> ProtobufOptions, +) -> Result<(Signal, Outline, ProtobufOptions), PostError> { + let signal = match target.log_source { + LogSource::OtelLogs => Signal::Logs, + LogSource::OtelMetrics => Signal::Metrics, + LogSource::OtelTraces => Signal::Traces, + other => { + return Err(stream_error( + target, + OtelProtobufError::NotOtel(other.clone()).to_string(), + )); + } + }; + match outline(body, signal) { + Ok(outline) => Ok((signal, outline, options())), + Err(error) => { + let error = refusal(body, signal, error, || { + max_record_bytes(options().max_payload) + }); + Err(from_stream_error(target, error.widen())) + } + } +} + +/// Hands the rows of a protobuf body that passed `outline` to `sink` +fn flatten_otel_protobuf( + body: &web::Bytes, + signal: Signal, + options: &ProtobufOptions, + target: &OtelTarget<'_>, + budget: &mut FlattenBudget, + sink: &mut dyn RowSink, ) -> Result<(), PostError> { - let request = OtelProtobufRequest::decode(body, log_source).map_err(|e| { - PostError::Invalid(anyhow::anyhow!( - "Ingestion failed for stream {stream_name}: {e}" - )) - })?; - let tenant_str = tenant_id.as_deref().unwrap_or(DEFAULT_TENANT); - // Verify the dataset fields count - verify_dataset_fields_count(stream_name, tenant_id)?; - // Shared by every record of this request - let mut budget = FlattenBudget::new(FlattenLimits::from_config()); - let records = request.flatten(tenant_str, &mut budget)?; - if !records.is_empty() { - push_logs( - stream_name, - Value::Array(records), - log_source, - p_custom_fields, - None, - telemetry_type, - tenant_id, - &mut budget, - )?; + flatten_request( + body, + signal, + max_record_bytes(options.max_payload), + budget, + options.flatten_exemplars, + sink, + ) + .map_err(|e| from_stream_error(target, e)) +} + +/// `flatten_and_push_otel_protobuf` without the server: the rows are handed to +/// `stage` under `limits` instead of being staged into a stream. For tests, +/// which must not touch `PARSEABLE`. +#[cfg(test)] +fn stage_otel_protobuf( + body: web::Bytes, + target: &OtelTarget<'_>, + options: ProtobufOptions, + limits: StageLimits, + stage: impl FnMut(Vec) -> Result<(), PostError>, +) -> (Result, Staged) { + let (signal, outline, options) = match outline_otel_protobuf(&body, target, || options) { + Ok(read) => read, + Err(error) => return (Err(error), Staged::default()), + }; + let (result, staged) = stage_otel_rows( + limits, + |budget, sink| flatten_otel_protobuf(&body, signal, &options, target, budget, sink), + stage, + ); + let outcome = otel_outcome(signal, target.stream_name, result, &staged, || { + protobuf_total(&body, signal, &outline) + }); + (outcome, staged) +} + +/// `ingest_otel_resources` without the server, see `stage_otel_protobuf` +#[cfg(test)] +fn stage_otel_resources( + resources: OtelResources<'_>, + flatten_exemplars: bool, + limits: StageLimits, + stage: impl FnMut(Vec) -> Result<(), PostError>, +) -> (Result, Staged) { + let (result, staged) = stage_otel_rows( + limits, + |budget, sink| resources.flatten_into(budget, flatten_exemplars, sink), + stage, + ); + let outcome = otel_outcome(resources.signal(), "test", result, &staged, || { + resources.total() + }); + (outcome, staged) +} + +/// What a partial success of a protobuf request counts as rejected, for the whole +/// request: its records from the outline, or its data points read from the wire +fn protobuf_total(body: &web::Bytes, signal: Signal, outline: &Outline) -> u64 { + match signal { + Signal::Metrics => count_points(body), + Signal::Logs | Signal::Traces => outline.records, + } +} + +fn stream_error(target: &OtelTarget<'_>, error: String) -> PostError { + PostError::Invalid(anyhow::anyhow!( + "Ingestion failed for stream {}: {error}", + target.stream_name + )) +} + +/// A decode error or an oversized record is a client error (400): the same text +/// whole-request decoding gave for a body that does not decode +fn from_stream_error(target: &OtelTarget<'_>, error: StreamError) -> PostError { + match error { + StreamError::Decode(e) => stream_error(target, OtelProtobufError::Decode(e).to_string()), + StreamError::RecordTooLarge { leaf, limit } => stream_error( + target, + format!( + "one {leaf:?} of the request would take more than {limit} bytes of memory once decoded (16 times P_MAX_EVENT_PAYLOAD_SIZE). Split it into smaller records" + ), + ), + StreamError::Consumer(e) => e, } - Ok(()) } #[instrument( @@ -353,9 +902,13 @@ pub fn flatten_and_push_logs( telemetry_type: TelemetryType, tenant_id: &Option, ) -> Result<(), PostError> { - let tenant_str = tenant_id.as_deref().unwrap_or(DEFAULT_TENANT); - // Verify the dataset fields count - verify_dataset_fields_count(stream_name, tenant_id)?; + if !matches!( + log_source, + LogSource::OtelLogs | LogSource::OtelTraces | LogSource::OtelMetrics + ) { + // Verify the dataset fields count (the OTEL arms do it themselves) + verify_dataset_fields_count(stream_name, tenant_id)?; + } // Shared by every event of this request let mut budget = FlattenBudget::new(FlattenLimits::from_config()); @@ -376,55 +929,23 @@ pub fn flatten_and_push_logs( &mut budget, )?; } - LogSource::OtelLogs => { - let logs: LogsData = - deserialize_otel_json(json, PARSEABLE.options.normalise_otel_payload)?; - let records = flatten_otel_logs(&logs, tenant_str, &mut budget)?; - if !records.is_empty() { - push_logs( - stream_name, - Value::Array(records), - log_source, - p_custom_fields, - None, - telemetry_type, - tenant_id, - &mut budget, - )?; - } - } - LogSource::OtelTraces => { - let traces: TracesData = - deserialize_otel_json(json, PARSEABLE.options.normalise_otel_payload)?; - let records = flatten_otel_traces(&traces, tenant_str); - if !records.is_empty() { - push_logs( - stream_name, - Value::Array(records), - log_source, - p_custom_fields, - None, - telemetry_type, - tenant_id, - &mut budget, - )?; - } - } - LogSource::OtelMetrics => { - let metrics: MetricsData = - deserialize_otel_json(json, PARSEABLE.options.normalise_otel_payload)?; - let records = flatten_otel_metrics(metrics, tenant_str); - if !records.is_empty() { - push_logs( - stream_name, - Value::Array(records), - log_source, - p_custom_fields, - None, - telemetry_type, - tenant_id, - &mut budget, - )?; + // Only reached through `handle_otel_ingestion`, which answers partial + // successes itself; here they fail the request + LogSource::OtelLogs | LogSource::OtelTraces | LogSource::OtelMetrics => { + let target = OtelTarget { + stream_name, + log_source, + p_custom_fields, + telemetry_type, + tenant_id, + }; + // The body's length, as the expansion cap counts it, is that of the + // JSON text of the value + let body_len = json_byte_size(&json) as usize; + if let OtelIngested::Partial { message, .. } = + ingest_otel_json(json, body_len, &target)? + { + return Err(PostError::Invalid(anyhow::Error::msg(message))); } } _ => push_logs( @@ -469,22 +990,146 @@ pub fn push_logs( tenant_id: &Option, budget: &mut FlattenBudget, ) -> Result<(), PostError> { - // Snapshot at request entry. A subscriber attaching later receives ordered - // single-row slices from the grouped path. - let grouped = use_partitioned_ingest_batching( - PARSEABLE.options.partitioned_ingest_batching, - PARSEABLE.options.mode, - &crate::livetail::LIVETAIL, + Staging::new(stream_name, tenant_id)?.push_with_budget( + json, + log_source, + p_custom_fields, + time_partition, + telemetry_type, + budget, + ) +} + +/// The stream one request is staged into, looked up once, and what every part of +/// the request shares: its ingestion time (`p_timestamp`) and whether it uses the +/// grouped path. A request can be staged in several parts (chunks); each part +/// reads the stream's current schema, so it sees the fields the parts before it +/// added, as a later request would. +pub struct Staging<'a> { + stream_name: &'a str, + tenant_id: &'a Option, + stream: std::sync::Arc, + grouped: bool, + p_timestamp: chrono::DateTime, + /// Flattening budget of the parts, shared by all of them + budget: FlattenBudget, +} + +impl<'a> Staging<'a> { + pub fn new(stream_name: &'a str, tenant_id: &'a Option) -> Result { + // Snapshot at request entry. A subscriber attaching later receives ordered + // single-row slices from the grouped path. + let grouped = use_partitioned_ingest_batching( + PARSEABLE.options.partitioned_ingest_batching, + PARSEABLE.options.mode, + &crate::livetail::LIVETAIL, + stream_name, + ); + let stream = PARSEABLE.get_stream(stream_name, tenant_id)?; + Ok(Self { + stream_name, + tenant_id, + stream, + grouped, + p_timestamp: Utc::now(), + budget: FlattenBudget::new(FlattenLimits::from_config()), + }) + } + + /// Stages one part of the request, charging its flattening to the budget + /// all parts share + pub fn push( + &mut self, + json: Value, + log_source: &LogSource, + p_custom_fields: &HashMap, + time_partition: Option, + telemetry_type: TelemetryType, + ) -> Result<(), PostError> { + let Self { + stream_name, + tenant_id, + stream, + grouped, + p_timestamp, + budget, + } = self; + stage_json( + StageInto { + stream_name, + tenant_id, + stream, + grouped: *grouped, + p_timestamp: *p_timestamp, + }, + json, + log_source, + p_custom_fields, + time_partition, + telemetry_type, + budget, + ) + } + + fn push_with_budget( + self, + json: Value, + log_source: &LogSource, + p_custom_fields: &HashMap, + time_partition: Option, + telemetry_type: TelemetryType, + budget: &mut FlattenBudget, + ) -> Result<(), PostError> { + stage_json( + StageInto { + stream_name: self.stream_name, + tenant_id: self.tenant_id, + stream: &self.stream, + grouped: self.grouped, + p_timestamp: self.p_timestamp, + }, + json, + log_source, + p_custom_fields, + time_partition, + telemetry_type, + budget, + ) + } +} + +/// What `stage_json` takes from a `Staging` +struct StageInto<'a> { + stream_name: &'a str, + tenant_id: &'a Option, + stream: &'a Stream, + grouped: bool, + p_timestamp: chrono::DateTime, +} + +/// Stages one part of a request +fn stage_json( + into: StageInto<'_>, + json: Value, + log_source: &LogSource, + p_custom_fields: &HashMap, + time_partition: Option, + telemetry_type: TelemetryType, + budget: &mut FlattenBudget, +) -> Result<(), PostError> { + let StageInto { stream_name, - ); - let stream = PARSEABLE.get_stream(stream_name, tenant_id)?; + tenant_id, + stream, + grouped, + p_timestamp, + } = into; let time_partition_limit = stream.get_time_partition_limit(); let static_schema_flag = stream.get_static_schema_flag(); let custom_partition = stream.get_custom_partition(); let schema_version = stream.get_schema_version(); let schema = stream.get_schema_raw(); let infer_timestamp = stream.get_infer_timestamp(); - let p_timestamp = Utc::now(); let data = convert_array_to_object( json, @@ -736,6 +1381,20 @@ pub fn get_otel_custom_fields_from_header( custom_fields } +/// `verify_dataset_fields_count` for an OTEL request, which may be answered +/// without its stream: a stream that does not exist has no fields to count. +/// Staging a chunk of a request that has rows needs the stream, and fails there +/// as before (404). +fn verify_otel_fields_count( + stream_name: &str, + tenant_id: &Option, +) -> Result<(), PostError> { + match verify_dataset_fields_count(stream_name, tenant_id) { + Err(PostError::StreamNotFound(_)) => Ok(()), + checked => checked, + } +} + fn verify_dataset_fields_count( stream_name: &str, tenant_id: &Option, @@ -815,6 +1474,7 @@ pub fn validate_stream_for_ingestion( #[cfg(test)] mod tests { use super::*; + use crate::otel::{logs::flatten_otel_logs, traces::flatten_otel_traces}; use actix_web::test::TestRequest; #[test] @@ -1152,7 +1812,7 @@ mod tests { } #[test] - fn otel_success_response_answers_in_the_request_encoding() { + fn otel_full_success_response_answers_in_the_request_encoding() { use actix_web::http::header::CONTENT_TYPE; for (request_type, response_type) in [ @@ -1171,7 +1831,11 @@ mod tests { if let Some(value) = request_type { req = req.insert_header((CONTENT_TYPE, value)); } - let resp = otel_success_response(&req.to_http_request()); + let resp = otel_response( + &req.to_http_request(), + TelemetryType::Logs, + &OtelIngested::Full, + ); assert_eq!(resp.status(), actix_web::http::StatusCode::OK); assert_eq!( resp.headers() @@ -1183,6 +1847,68 @@ mod tests { } } + #[actix_web::test] + async fn otel_partial_success_is_answered_in_the_request_encoding() { + use actix_web::body::MessageBody; + use actix_web::http::header::CONTENT_TYPE; + use opentelemetry_proto::tonic::collector::{ + logs::v1::ExportLogsServiceResponse, metrics::v1::ExportMetricsServiceResponse, + trace::v1::ExportTraceServiceResponse, + }; + + let partial = OtelIngested::Partial { + rejected: 7, + message: "schema conflict".to_string(), + }; + let body = |request_type: &str, telemetry_type| { + let req = TestRequest::default() + .insert_header((CONTENT_TYPE, request_type)) + .to_http_request(); + let resp = otel_response(&req, telemetry_type, &partial); + assert_eq!(resp.status(), actix_web::http::StatusCode::OK); + let content_type = resp + .headers() + .get(CONTENT_TYPE) + .map(|v| v.to_str().unwrap().to_string()); + ( + content_type, + resp.into_body().try_into_bytes().ok().unwrap(), + ) + }; + + let (content_type, bytes) = body("application/x-protobuf", TelemetryType::Logs); + assert_eq!(content_type.as_deref(), Some("application/x-protobuf")); + let partial_success = ExportLogsServiceResponse::decode(bytes) + .unwrap() + .partial_success + .unwrap(); + assert_eq!(partial_success.rejected_log_records, 7); + assert_eq!(partial_success.error_message, "schema conflict"); + + let (_, bytes) = body("application/x-protobuf", TelemetryType::Metrics); + let partial_success = ExportMetricsServiceResponse::decode(bytes) + .unwrap() + .partial_success + .unwrap(); + assert_eq!(partial_success.rejected_data_points, 7); + + let (_, bytes) = body("application/x-protobuf", TelemetryType::Traces); + let partial_success = ExportTraceServiceResponse::decode(bytes) + .unwrap() + .partial_success + .unwrap(); + assert_eq!(partial_success.rejected_spans, 7); + + let (content_type, bytes) = body("application/json", TelemetryType::Traces); + assert_eq!(content_type.as_deref(), Some("application/json")); + assert_eq!( + serde_json::from_slice::(&bytes).unwrap(), + serde_json::json!({ + "partialSuccess": { "rejectedSpans": 7, "errorMessage": "schema conflict" } + }) + ); + } + #[test] fn otel_protobuf_decode_rejects_non_otel_log_source() { let err = OtelProtobufRequest::decode(&[], &LogSource::Json).unwrap_err(); @@ -1343,3 +2069,7 @@ mod tests { #[cfg(test)] mod otel_protobuf_props; +#[cfg(test)] +mod otel_regression_tests; +#[cfg(test)] +mod otel_server_state_tests; diff --git a/src/handlers/http/modal/utils/ingest_utils/otel_protobuf_props.rs b/src/handlers/http/modal/utils/ingest_utils/otel_protobuf_props.rs index 42dcec73f..f8fbef649 100644 --- a/src/handlers/http/modal/utils/ingest_utils/otel_protobuf_props.rs +++ b/src/handlers/http/modal/utils/ingest_utils/otel_protobuf_props.rs @@ -41,11 +41,14 @@ //! - `DST_SEED`, `DST_ITERS`: first seed and number of seeds of the DST scenario use super::*; +use crate::otel::logs::flatten_otel_logs; use crate::otel::metrics::{ flatten_otel_metrics_protobuf_with_options, flatten_otel_metrics_with_options, }; use crate::otel::otel_utils::flatten_attributes; -use crate::utils::json::flatten::FlattenCost; +use crate::otel::sink::{ChunkLimits, Chunker}; +use crate::otel::traces::flatten_otel_traces; +use crate::utils::json::flatten::{FlattenCost, JsonFlattenError}; use opentelemetry_proto::tonic::common::v1::{ AnyValue, ArrayValue, InstrumentationScope, KeyValue, KeyValueList, any_value, }; @@ -75,6 +78,21 @@ use std::sync::atomic::{AtomicUsize, Ordering}; const TENANT: &str = "tenant"; +/// The server defaults the protobuf path reads from the configuration +const PROTOBUF_OPTIONS: ProtobufOptions = ProtobufOptions { + max_payload: 10 * 1024 * 1024, + flatten_exemplars: false, +}; + +/// The staging limits of the server defaults, for a body at the payload limit +fn test_limits() -> StageLimits { + StageLimits::for_body( + PROTOBUF_OPTIONS.max_payload, + PROTOBUF_OPTIONS.max_payload, + FlattenLimits::DEFAULT, + ) +} + // --------------------------------------------------------------------------- // Seeds and runners // --------------------------------------------------------------------------- @@ -1452,6 +1470,192 @@ fn otel_pb_wild_requests_flatten_and_agree_where_json_can_carry_them() { assert!(carried > 0 && not_carried > 0, "{carried} / {not_carried}"); } +// --------------------------------------------------------------------------- +// Chunked staging +// --------------------------------------------------------------------------- + +impl Req { + fn resources(&self) -> OtelResources<'_> { + match self { + Self::Logs(data) => OtelResources::Logs(&data.resource_logs), + Self::Metrics(data) => OtelResources::Metrics(&data.resource_metrics), + Self::Traces(data) => OtelResources::Traces(&data.resource_spans), + } + } + + /// Leaf records: log records, spans or metrics + fn record_count(&self) -> u64 { + let n: usize = match self { + Self::Logs(data) => data + .resource_logs + .iter() + .flat_map(|r| &r.scope_logs) + .map(|s| s.log_records.len()) + .sum(), + Self::Metrics(data) => data + .resource_metrics + .iter() + .flat_map(|r| &r.scope_metrics) + .map(|s| s.metrics.len()) + .sum(), + Self::Traces(data) => data + .resource_spans + .iter() + .flat_map(|r| &r.scope_spans) + .map(|s| s.spans.len()) + .sum(), + }; + n as u64 + } + + /// Metric data points + fn point_count(&self) -> u64 { + match self { + Self::Metrics(data) => data + .resource_metrics + .iter() + .flat_map(|r| &r.scope_metrics) + .flat_map(|s| &s.metrics) + .map(|m| metric_points(m) as u64) + .sum(), + Self::Logs(_) | Self::Traces(_) => 0, + } + } +} + +/// The request decoded from `body` in `encoding`, as ingestion decodes it +fn decode_as(request: &Req, protobuf: bool) -> Req { + let source = request.source(); + if protobuf { + Req::from_decoded(OtelProtobufRequest::decode(&request.encode_pb(), &source).unwrap()) + } else { + let json: Value = serde_json::from_slice(&request.encode_json()).unwrap(); + match request { + Req::Logs(_) => Req::Logs(deserialize_otel_json(json, false).unwrap()), + Req::Metrics(_) => Req::Metrics(deserialize_otel_json(json, false).unwrap()), + Req::Traces(_) => Req::Traces(deserialize_otel_json(json, false).unwrap()), + } + } +} + +/// Chunks of at most `rows` rows (and a byte limit small enough to cut chunks of a +/// row or two) give the same rows in the same order as one chunk, for both +/// encodings, and count every record and data point as staged: as many as the +/// request has, which is what a partial success counts its rejected records from +/// (`OtelResources::total`, and for protobuf the outline and the wire count of +/// data points). +fn chunking_keeps_rows( + mut request: Req, + rows: usize, + bytes: usize, + flatten_exemplars: bool, +) -> TestCaseResult { + fill_unset_timestamps(&mut request); + prop_assume!(json_representable(&request)); + let limits = ChunkLimits { rows, bytes }; + for protobuf in [true, false] { + let decoded = decode_as(&request, protobuf); + let resources = decoded.resources(); + let mut whole = Vec::new(); + resources + .flatten_into( + &mut FlattenBudget::new(FlattenLimits::DEFAULT), + flatten_exemplars, + &mut whole, + ) + .unwrap(); + let mut chunks: Vec> = Vec::new(); + let mut chunker = Chunker::new(limits, |rows, _| { + chunks.push(rows); + Ok::<_, JsonFlattenError>(()) + }); + resources + .flatten_into( + &mut FlattenBudget::new(FlattenLimits::DEFAULT), + flatten_exemplars, + &mut chunker, + ) + .unwrap(); + chunker.finish().unwrap(); + let staged = chunker.staged(); + drop(chunker); + + prop_assert!( + chunks + .iter() + .all(|chunk| !chunk.is_empty() && chunk.len() <= rows) + ); + prop_assert_eq!(staged.chunks as usize, chunks.len()); + let chunked: Vec = chunks.into_iter().flatten().collect(); + prop_assert_eq!( + serde_json::to_vec(&chunked).unwrap(), + serde_json::to_vec(&whole).unwrap(), + "chunked rows differ (protobuf: {})", + protobuf + ); + prop_assert_eq!(staged.rows as usize, whole.len()); + prop_assert_eq!(staged.records, decoded.record_count()); + prop_assert_eq!(staged.points, decoded.point_count()); + let units = match decoded { + Req::Metrics(_) => staged.points, + Req::Logs(_) | Req::Traces(_) => staged.records, + }; + prop_assert_eq!(resources.total(), units); + if protobuf { + let body = web::Bytes::from(request.encode_pb()); + let signal = streamed::signal(&decoded); + let outline = crate::otel::protobuf_stream::outline(&body, signal).unwrap(); + prop_assert_eq!(outline.records, staged.records); + if signal == crate::otel::protobuf_stream::Signal::Metrics { + prop_assert_eq!( + crate::otel::protobuf_stream::count_points(&body), + staged.points + ); + } + } + } + Ok(()) +} + +fn chunk_limits() -> impl Strategy { + ( + 1usize..5, + prop_oneof![Just(1usize), Just(4096), Just(usize::MAX)], + ) +} + +#[test] +fn otel_chunked_rows_match_one_chunk_logs() { + check( + "otel_chunked_rows_match_one_chunk_logs", + 64, + (logs_data(false), chunk_limits()), + |(logs, (rows, bytes))| chunking_keeps_rows(Req::Logs(logs), rows, bytes, false), + ); +} + +#[test] +fn otel_chunked_rows_match_one_chunk_traces() { + check( + "otel_chunked_rows_match_one_chunk_traces", + 64, + (traces_data(false), chunk_limits()), + |(traces, (rows, bytes))| chunking_keeps_rows(Req::Traces(traces), rows, bytes, false), + ); +} + +#[test] +fn otel_chunked_rows_match_one_chunk_metrics() { + check( + "otel_chunked_rows_match_one_chunk_metrics", + 64, + (metrics_data(false), chunk_limits(), any::()), + |(metrics, (rows, bytes), flatten_exemplars)| { + chunking_keeps_rows(Req::Metrics(metrics), rows, bytes, flatten_exemplars) + }, + ); +} + // --------------------------------------------------------------------------- // 2. Robustness of the decoder // --------------------------------------------------------------------------- @@ -1500,21 +1704,37 @@ fn decode_is_total( } } Err(error) => { - // Returns before the dataset field check, the first use of `PARSEABLE` - let refused = flatten_and_push_otel_protobuf( - body, - "otel_pb_props", - source, - &HashMap::new(), + let target = OtelTarget { + stream_name: "otel_pb_props", + log_source: source, + p_custom_fields: &HashMap::new(), telemetry_type, - &None, - ) - .expect_err("a body that does not decode is refused"); + tenant_id: &None, + }; + let expected = + format!("Invalid Request: Ingestion failed for stream otel_pb_props: {error}"); + let body = web::Bytes::copy_from_slice(body); + let signal = match source { + LogSource::OtelLogs => crate::otel::protobuf_stream::Signal::Logs, + LogSource::OtelMetrics => crate::otel::protobuf_stream::Signal::Metrics, + _ => crate::otel::protobuf_stream::Signal::Traces, + }; + if crate::otel::protobuf_stream::outline(&body, signal).is_err() { + // Broken above its records: refused before the dataset field check, + // the first use of `PARSEABLE` + let refused = + flatten_and_push_otel_protobuf(body.clone(), &target, || PROTOBUF_OPTIONS) + .expect_err("a body that does not decode is refused"); + prop_assert!(matches!(refused, PostError::Invalid(_)), "{refused:?}"); + prop_assert_eq!(refused.to_string(), expected.clone()); + } + // A broken record is met while staging, before the first chunk is full + let (refused, staged) = + stage_otel_protobuf(body, &target, PROTOBUF_OPTIONS, test_limits(), |_| Ok(())); + let refused = refused.expect_err("a body that does not decode is refused"); prop_assert!(matches!(refused, PostError::Invalid(_)), "{refused:?}"); - prop_assert_eq!( - refused.to_string(), - format!("Invalid Request: Ingestion failed for stream otel_pb_props: {error}") - ); + prop_assert_eq!(refused.to_string(), expected); + prop_assert_eq!(staged.chunks, 0); } } Ok(()) @@ -2375,13 +2595,18 @@ fn run_scenario(seed: u64) -> Result)> { return fail(format!("undamaged body refused: {error}"), &mut trace); } if encoding == Encoding::Protobuf { - let refused = flatten_and_push_otel_protobuf( - &body, - "dst", - &source, - &HashMap::new(), - request.telemetry_type(), - &None, + let (refused, _) = stage_otel_protobuf( + web::Bytes::copy_from_slice(&body), + &OtelTarget { + stream_name: "dst", + log_source: &source, + p_custom_fields: &HashMap::new(), + telemetry_type: request.telemetry_type(), + tenant_id: &None, + }, + PROTOBUF_OPTIONS, + test_limits(), + |_| Ok(()), ); if !matches!(&refused, Err(PostError::Invalid(e)) if e.to_string().ends_with(error.as_str())) { @@ -2541,3 +2766,1325 @@ fn dst_otlp_mixed_encoding_seeds_differ() { .collect(); assert_eq!(digests.len(), 4); } + +// --------------------------------------------------------------------------- +// Streamed decoding (`protobuf_stream`) against whole-request decoding +// --------------------------------------------------------------------------- + +mod streamed { + use super::*; + use crate::otel::decoded_size::{ + Leaf, bytes_per_wire_byte, leaf_decoded_size, leaf_struct_size, + metric_points as wire_points, + }; + use crate::otel::protobuf_stream::{ + Signal, StreamError, count_points, flatten_request, outline, refusal, + }; + use prost::Message as ProstMessage; + use prost::encoding::{WireType, encode_key, encode_varint}; + + /// Damage to one leaf record of a body: byte `at` set to `byte`, or the record + /// cut at `at`, inside the record (its framing is rewritten to fit) + #[derive(Debug, Clone, Copy)] + struct RecordDamage { + index: u64, + at: u64, + byte: u8, + cut: bool, + } + + /// Wire edits applied while re-encoding a request field by field, and the + /// record damage to apply, with the count of records seen so far + struct Edits<'a>(&'a mut SplitMix64, Option, u64); + + impl Edits<'_> { + /// The encoding of the next leaf record, damaged if it is the one to damage + fn record(&mut self, mut encoded: Vec) -> Vec { + let index = self.2; + self.2 += 1; + if let Some(damage) = self.1 + && damage.index == index + && !encoded.is_empty() + { + let at = (damage.at % encoded.len() as u64) as usize; + if damage.cut { + encoded.truncate(at); + } else { + encoded[at] = damage.byte; + } + } + encoded + } + + /// An unknown field (numbers 4-40 or a large one) of a random wire type + fn unknown(&mut self, out: &mut Vec) { + let tag = if self.0.percent(80) { + 4 + self.0.below(37) as u32 + } else { + 1 << 20 + }; + match self.0.below(5) { + 0 => { + encode_key(tag, WireType::Varint, out); + encode_varint(self.0.next_u64() >> self.0.below(64), out); + } + 1 => { + encode_key(tag, WireType::SixtyFourBit, out); + out.extend_from_slice(&self.0.next_u64().to_le_bytes()); + } + 2 => { + encode_key(tag, WireType::ThirtyTwoBit, out); + out.extend_from_slice(&(self.0.next_u64() as u32).to_le_bytes()); + } + 3 => { + let len = self.0.below(12) as usize; + encode_key(tag, WireType::LengthDelimited, out); + encode_varint(len as u64, out); + out.extend((0..len).map(|_| self.0.next_u64() as u8)); + } + _ => { + encode_key(tag, WireType::StartGroup, out); + if self.0.percent(50) { + encode_key(tag + 1, WireType::Varint, out); + encode_varint(7, out); + } + encode_key(tag, WireType::EndGroup, out); + } + } + } + + /// `fields` in a shuffled order, with unknown fields between them + fn level(&mut self, mut fields: Vec>) -> Vec { + for i in (1..fields.len()).rev() { + if self.0.percent(50) { + let j = self.0.below(i as u64 + 1) as usize; + fields.swap(i, j); + } + } + let mut out = Vec::new(); + for field in fields { + if self.0.percent(25) { + self.unknown(&mut out); + } + out.extend(field); + } + if self.0.percent(25) { + self.unknown(&mut out); + } + out + } + + fn len_field(tag: u32, body: &[u8]) -> Vec { + let mut out = Vec::new(); + encode_key(tag, WireType::LengthDelimited, &mut out); + encode_varint(body.len() as u64, &mut out); + out.extend_from_slice(body); + out + } + + /// A singular message field, sometimes split over two occurrences, which + /// prost merges: repeated fields concatenate, the last scalar wins + fn singular( + &mut self, + tag: u32, + msg: &M, + split: impl Fn(&M) -> (M, M), + ) -> Vec> { + if self.0.percent(30) { + let (first, second) = split(msg); + vec![ + Self::len_field(tag, &first.encode_to_vec()), + Self::len_field(tag, &second.encode_to_vec()), + ] + } else { + vec![Self::len_field(tag, &msg.encode_to_vec())] + } + } + + /// `schema_url`, sometimes after an earlier occurrence it replaces + fn schema_url(&mut self, url: &str) -> Vec> { + let mut fields = vec![]; + if self.0.percent(20) { + fields.push(Self::len_field(3, b"https://replaced.example")); + } + if !url.is_empty() || self.0.percent(20) { + fields.push(Self::len_field(3, url.as_bytes())); + } + fields + } + + /// A parent level: `resource`/`scope` (field 1), children (field 2), schema_url (3) + fn parent( + &mut self, + parent: Option<&P>, + split: impl Fn(&P) -> (P, P), + children: Vec>, + url: &str, + ) -> Vec { + let mut fields = vec![]; + if let Some(parent) = parent { + fields.extend(self.singular(1, parent, split)); + } + fields.extend(children.iter().map(|child| Self::len_field(2, child))); + fields.extend(self.schema_url(url)); + self.level(fields) + } + } + + fn split_resource(resource: &Resource) -> (Resource, Resource) { + let at = resource.attributes.len() / 2; + ( + Resource { + attributes: resource.attributes[..at].to_vec(), + dropped_attributes_count: 3, + ..Default::default() + }, + Resource { + attributes: resource.attributes[at..].to_vec(), + ..resource.clone() + }, + ) + } + + fn split_scope(scope: &InstrumentationScope) -> (InstrumentationScope, InstrumentationScope) { + let at = scope.attributes.len() / 2; + ( + InstrumentationScope { + name: "replaced".into(), + attributes: scope.attributes[..at].to_vec(), + ..Default::default() + }, + InstrumentationScope { + attributes: scope.attributes[at..].to_vec(), + ..scope.clone() + }, + ) + } + + /// The protobuf body of `request`, re-encoded field by field with edits drawn + /// from `rng`, with `damage` applied to one of its leaf records + fn edited_body(request: &Req, rng: &mut SplitMix64, damage: Option) -> Vec { + let mut edits = Edits(rng, damage, 0); + let resources: Vec> = match request { + Req::Logs(data) => data + .resource_logs + .iter() + .map(|r| { + let scopes = r + .scope_logs + .iter() + .map(|s| { + let records = s + .log_records + .iter() + .map(|record| edits.record(record.encode_to_vec())) + .collect(); + edits.parent(s.scope.as_ref(), split_scope, records, &s.schema_url) + }) + .collect(); + edits.parent(r.resource.as_ref(), split_resource, scopes, &r.schema_url) + }) + .collect(), + Req::Traces(data) => data + .resource_spans + .iter() + .map(|r| { + let scopes = r + .scope_spans + .iter() + .map(|s| { + let spans = s + .spans + .iter() + .map(|span| edits.record(span.encode_to_vec())) + .collect(); + edits.parent(s.scope.as_ref(), split_scope, spans, &s.schema_url) + }) + .collect(); + edits.parent(r.resource.as_ref(), split_resource, scopes, &r.schema_url) + }) + .collect(), + Req::Metrics(data) => data + .resource_metrics + .iter() + .map(|r| { + let scopes = r + .scope_metrics + .iter() + .map(|s| { + let metrics = s + .metrics + .iter() + .map(|metric| edits.record(metric.encode_to_vec())) + .collect(); + edits.parent(s.scope.as_ref(), split_scope, metrics, &s.schema_url) + }) + .collect(); + edits.parent(r.resource.as_ref(), split_resource, scopes, &r.schema_url) + }) + .collect(), + }; + let fields = resources.iter().map(|r| Edits::len_field(1, r)).collect(); + edits.level(fields) + } + + pub(super) fn signal(request: &Req) -> Signal { + match request { + Req::Logs(_) => Signal::Logs, + Req::Metrics(_) => Signal::Metrics, + Req::Traces(_) => Signal::Traces, + } + } + + fn leaf(request: &Req) -> Leaf { + match request { + Req::Logs(_) => Leaf::LogRecord, + Req::Metrics(_) => Leaf::Metric, + Req::Traces(_) => Leaf::Span, + } + } + + /// The rows the flatteners build for `request`, or the flatten error text + fn rows_of(request: &Req, flatten_exemplars: bool) -> Result, String> { + let mut rows = Vec::new(); + request + .resources() + .flatten_into( + &mut FlattenBudget::new(FlattenLimits::DEFAULT), + flatten_exemplars, + &mut rows, + ) + .map_err(|e| format!("flatten: {e}"))?; + Ok(rows) + } + + /// The rows of `request`, and whether some of them take the wall clock for an + /// unset timestamp (then only their number can be compared) + fn clocked_rows(request: &Req, flatten_exemplars: bool) -> Result<(Vec, bool), String> { + let clock = fill_unset_timestamps(&mut request.clone()); + Ok((rows_of(request, flatten_exemplars)?, clock)) + } + + /// Rows of `body` decoded whole, or prost's error text + fn whole( + request: &Req, + body: &[u8], + flatten_exemplars: bool, + ) -> Result<(Vec, bool), String> { + let decoded = + OtelProtobufRequest::decode(body, &request.source()).map_err(|e| e.to_string())?; + clocked_rows(&Req::from_decoded(decoded), flatten_exemplars) + } + + /// Whether streamed rows are the expected ones: the same, or as many where the + /// wall clock filled a timestamp + fn same_rows(streamed: &[Value], expected: &[Value], clock: bool) -> bool { + if clock { + streamed.len() == expected.len() + } else { + serde_json::to_vec(streamed).unwrap() == serde_json::to_vec(expected).unwrap() + } + } + + /// What reading `body` one record at a time staged, in chunks of one row + #[derive(Debug)] + struct Streamed { + rows: Vec, + staged: Staged, + /// The error text, if it stopped + error: Option, + /// What a partial success counts its rejected records from: the records of + /// the outline, or the data points read from the wire + total: u64, + } + + fn text(e: StreamError) -> String { + match e { + StreamError::Decode(e) => OtelProtobufError::Decode(e).to_string(), + StreamError::RecordTooLarge { .. } => "record too large".to_string(), + StreamError::Consumer(e) => format!("flatten: {e}"), + } + } + + fn streamed(request: &Req, body: &[u8], flatten_exemplars: bool) -> Streamed { + let body = web::Bytes::copy_from_slice(body); + let signal = signal(request); + let outlined = match outline(&body, signal) { + Ok(outlined) => outlined, + Err(error) => { + return Streamed { + rows: Vec::new(), + staged: Staged::default(), + error: Some(text(refusal(&body, signal, error, || usize::MAX).widen())), + total: 0, + }; + } + }; + let mut rows: Vec = Vec::new(); + let mut chunker = Chunker::new( + ChunkLimits { + rows: 1, + bytes: usize::MAX, + }, + |chunk, _| { + rows.extend(chunk); + Ok::<_, JsonFlattenError>(()) + }, + ); + let result = flatten_request( + &body, + signal, + usize::MAX, + &mut FlattenBudget::new(FlattenLimits::DEFAULT), + flatten_exemplars, + &mut chunker, + ) + .and_then(|()| chunker.finish().map_err(StreamError::Consumer)); + let staged = chunker.staged(); + drop(chunker); + Streamed { + rows, + staged, + error: result.err().map(text), + total: match signal { + Signal::Metrics => count_points(&body), + Signal::Logs | Signal::Traces => outlined.records, + }, + } + } + + /// The levels of a request above its leaf records, with the records kept as + /// bytes: prost decodes a body as this exactly when its framing above the + /// records holds, and merges `resource`, `scope` and `schema_url` as it does + /// for the real messages + #[derive(Clone, PartialEq, prost::Message)] + struct ShallowRequest { + #[prost(message, repeated, tag = "1")] + resources: Vec, + } + + #[derive(Clone, PartialEq, prost::Message)] + struct ShallowResource { + #[prost(message, optional, tag = "1")] + resource: Option, + #[prost(message, repeated, tag = "2")] + scopes: Vec, + #[prost(string, tag = "3")] + schema_url: String, + } + + #[derive(Clone, PartialEq, prost::Message)] + struct ShallowScope { + #[prost(message, optional, tag = "1")] + scope: Option, + #[prost(bytes = "vec", repeated, tag = "2")] + records: Vec>, + #[prost(string, tag = "3")] + schema_url: String, + } + + type Scopes = Vec<(Option, String, Vec)>; + + /// A request rebuilt from its shallow decoding, with the records that prost + /// decodes on their own up to the first that it does not + struct Prefix { + resources: Vec<(Option, String, Scopes)>, + /// Position of the first record that does not decode, in body order + failed: Option, + records: u64, + /// Every record, decoded where it decodes + all: Vec>>, + } + + fn prefix(shallow: &ShallowRequest) -> Prefix { + let mut prefix = Prefix { + resources: vec![], + failed: None, + records: 0, + all: vec![], + }; + for resource in &shallow.resources { + if prefix.failed.is_none() { + prefix.resources.push(( + resource.resource.clone(), + resource.schema_url.clone(), + vec![], + )); + } + for scope in &resource.scopes { + if prefix.failed.is_none() { + let scopes = &mut prefix.resources.last_mut().unwrap().2; + scopes.push((scope.scope.clone(), scope.schema_url.clone(), vec![])); + } + for encoded in &scope.records { + let decoded = L::decode(encoded.as_slice()).map_err(|_| encoded.clone()); + if prefix.failed.is_none() { + match &decoded { + Ok(record) => { + let scopes = &mut prefix.resources.last_mut().unwrap().2; + scopes.last_mut().unwrap().2.push(record.clone()); + } + Err(_) => prefix.failed = Some(prefix.records), + } + } + prefix.all.push(decoded); + prefix.records += 1; + } + } + } + prefix + } + + /// What streaming must stage for a body + enum Expected { + /// The framing above the records is broken: nothing is staged + Outer, + Records { + /// The rows of the records before the first that does not decode (all + /// of them if each does), or the flatten error text + rows: Result<(Vec, bool), String>, + failed: Option, + records: u64, + /// Data points of the records before the first that does not decode + staged_points: u64, + /// Data points of every record, those that do not decode read from the wire + total_points: u64, + }, + } + + fn is_target_info(row: &Value) -> bool { + row.get("metric_name") == Some(&json!("target_info")) + && row.get("metric_description") == Some(&json!("Target metadata")) + } + + fn expected(request: &Req, body: &[u8], flatten_exemplars: bool) -> Expected { + let Ok(shallow) = ShallowRequest::decode(body) else { + return Expected::Outer; + }; + let (rows, failed, records, staged_points, total_points) = match request { + Req::Logs(_) => { + let p = prefix::(&shallow); + let request = Req::Logs(LogsData { + resource_logs: p + .resources + .into_iter() + .map(|(resource, schema_url, scopes)| ResourceLogs { + resource, + scope_logs: scopes + .into_iter() + .map(|(scope, schema_url, log_records)| ScopeLogs { + scope, + log_records, + schema_url, + }) + .collect(), + schema_url, + }) + .collect(), + }); + ( + clocked_rows(&request, flatten_exemplars), + p.failed, + p.records, + 0, + 0, + ) + } + Req::Traces(_) => { + let p = prefix::(&shallow); + let request = Req::Traces(TracesData { + resource_spans: p + .resources + .into_iter() + .map(|(resource, schema_url, scopes)| ResourceSpans { + resource, + scope_spans: scopes + .into_iter() + .map(|(scope, schema_url, spans)| ScopeSpans { + scope, + spans, + schema_url, + }) + .collect(), + schema_url, + }) + .collect(), + }); + ( + clocked_rows(&request, flatten_exemplars), + p.failed, + p.records, + 0, + 0, + ) + } + Req::Metrics(_) => { + let p = prefix::(&shallow); + let points = |record: &Result>| match record { + Ok(metric) => metric_points(metric) as u64, + Err(encoded) => wire_points(encoded), + }; + let failed_at = p.failed.unwrap_or(p.records) as usize; + let staged_points = p.all[..failed_at].iter().map(points).sum(); + let total_points = p.all.iter().map(points).sum(); + let resources: Vec = p + .resources + .into_iter() + .map(|(resource, schema_url, scopes)| ResourceMetrics { + resource, + scope_metrics: scopes + .into_iter() + .map(|(scope, schema_url, metrics)| ScopeMetrics { + scope, + metrics, + schema_url, + }) + .collect(), + schema_url, + }) + .collect(); + let clock = fill_unset_timestamps(&mut Req::Metrics(MetricsData { + resource_metrics: resources.clone(), + })); + let rows = if p.failed.is_some() { + // Streaming stops inside the last resource, before its `target_info` row + let (last, complete) = resources.split_last().unwrap(); + let complete = rows_of( + &Req::Metrics(MetricsData { + resource_metrics: complete.to_vec(), + }), + flatten_exemplars, + ); + let last = rows_of( + &Req::Metrics(MetricsData { + resource_metrics: vec![last.clone()], + }), + flatten_exemplars, + ); + complete.and_then(|mut rows| { + let mut last = last?; + if last.last().is_some_and(is_target_info) { + last.pop(); + } + rows.extend(last); + Ok(rows) + }) + } else { + rows_of( + &Req::Metrics(MetricsData { + resource_metrics: resources, + }), + flatten_exemplars, + ) + }; + ( + rows.map(|rows| (rows, clock)), + p.failed, + p.records, + staged_points, + total_points, + ) + } + }; + Expected::Records { + rows, + failed, + records, + staged_points, + total_points, + } + } + + /// Which of the semantics a body met + #[derive(Debug, Clone, Copy, PartialEq, Eq)] + enum Case { + /// Decodes whole: the same rows, every record staged + Decoded, + /// Broken above its records: refused with prost's error, nothing staged + Outer, + /// The first record does not decode: prost's error, nothing staged + FirstRecord, + /// A later record does not decode: prost's error, the rows of the records + /// before it staged, the rest counted as rejected + Partial, + /// Flattening refused a record first + Flatten, + } + + /// The differential property of streamed decoding, for one body: either + /// whole-request decoding and streaming both succeed with identical rows; or + /// streaming stages exactly the rows of the records before the first record + /// prost can not decode and counts the rest rejected; or the framing above the + /// records is broken and nothing is staged. Every failure has prost's text. + /// Also checks the bound on the decoded size of every record of the body. + fn check_body( + request: &Req, + body: &[u8], + flatten_exemplars: bool, + ) -> Result { + let whole = whole(request, body, flatten_exemplars); + let streamed = streamed(request, body, flatten_exemplars); + let leaf = leaf(request); + if let Ok(shallow) = ShallowRequest::decode(body) { + for encoded in shallow + .resources + .iter() + .flat_map(|r| &r.scopes) + .flat_map(|s| &s.records) + { + prop_assert!( + leaf_decoded_size(encoded, leaf) + <= leaf_struct_size(leaf) + bytes_per_wire_byte(leaf) * encoded.len(), + "a {leaf:?} of {} bytes is over the bound", + encoded.len() + ); + } + } + let units = |staged: &Staged| match request { + Req::Metrics(_) => staged.points, + Req::Logs(_) | Req::Traces(_) => staged.records, + }; + match (&whole, expected(request, body, flatten_exemplars)) { + (Ok((rows, clock)), _) => { + prop_assert_eq!(&streamed.error, &None); + prop_assert!( + same_rows(&streamed.rows, rows, *clock), + "whole and streamed rows differ ({} and {})", + rows.len(), + streamed.rows.len() + ); + prop_assert_eq!(streamed.total, units(&streamed.staged)); + Ok(Case::Decoded) + } + (Err(text), Expected::Outer) => { + prop_assert_eq!(streamed.error.as_ref(), Some(text)); + prop_assert!(streamed.rows.is_empty()); + prop_assert_eq!(streamed.staged, Staged::default()); + Ok(Case::Outer) + } + ( + Err(text), + Expected::Records { + rows, + failed, + records, + staged_points, + total_points, + }, + ) => { + let (rows, clock) = match rows { + Ok(rows) => rows, + Err(flatten) => { + prop_assert_eq!(streamed.error, Some(flatten)); + return Ok(Case::Flatten); + } + }; + prop_assert_eq!(streamed.error.as_ref(), Some(text)); + let Some(failed) = failed else { + return Err(TestCaseError::fail(format!( + "whole decoding failed ({text}) but every record decodes on its own" + ))); + }; + prop_assert!( + same_rows(&streamed.rows, &rows, clock), + "streamed did not stage the rows of the records before the broken one ({} of {})", + streamed.rows.len(), + rows.len() + ); + prop_assert_eq!(streamed.staged.records, failed); + let rejected = streamed.total - units(&streamed.staged); + match request { + Req::Metrics(_) => { + prop_assert_eq!(streamed.staged.points, staged_points); + prop_assert_eq!(rejected, total_points - staged_points); + } + Req::Logs(_) | Req::Traces(_) => prop_assert_eq!(rejected, records - failed), + } + Ok(if failed == 0 { + Case::FirstRecord + } else { + Case::Partial + }) + } + } + } + + fn requests() -> BoxedStrategy { + prop_oneof![ + logs_data(true).prop_map(Req::Logs), + traces_data(true).prop_map(Req::Traces), + metrics_data(true).prop_map(Req::Metrics), + ] + .boxed() + } + + /// Counts the cases a property met, by kind + #[derive(Default)] + struct Cases([AtomicUsize; 5]); + + impl Cases { + fn add(&self, case: Case) { + self.0[case as usize].fetch_add(1, Ordering::Relaxed); + } + + fn get(&self, case: Case) -> usize { + self.0[case as usize].load(Ordering::Relaxed) + } + + fn print(&self, name: &str) { + println!( + "{name}: decoded {} outer {} first_record {} partial {} flatten {}", + self.get(Case::Decoded), + self.get(Case::Outer), + self.get(Case::FirstRecord), + self.get(Case::Partial), + self.get(Case::Flatten) + ); + } + } + + #[test] + fn otel_pb_streamed_rows_match_whole_decoding() { + check( + "otel_pb_streamed_rows_match_whole_decoding", + 192, + (requests(), any::(), any::()), + |(mut request, seed, flatten_exemplars)| { + fill_unset_timestamps(&mut request); + let body = edited_body(&request, &mut SplitMix64(seed), None); + let case = check_body(&request, &body, flatten_exemplars)?; + prop_assert_eq!(case, Case::Decoded); + Ok(()) + }, + ); + } + + #[test] + fn otel_pb_streamed_cut_bodies_match_whole_decoding() { + let cases = Cases::default(); + check( + "otel_pb_streamed_cut_bodies_match_whole_decoding", + 192, + (requests(), any::(), any::()), + |(mut request, seed, cut)| { + fill_unset_timestamps(&mut request); + let mut body = edited_body(&request, &mut SplitMix64(seed), None); + body.truncate((cut % (body.len() as u64 + 1)) as usize); + cases.add(check_body(&request, &body, false)?); + Ok(()) + }, + ); + cases.print("otel_pb_streamed_cut_bodies"); + } + + /// Single-byte damage anywhere in the body + #[test] + fn otel_pb_streamed_damaged_bodies_match_whole_decoding() { + let cases = Cases::default(); + check( + "otel_pb_streamed_damaged_bodies_match_whole_decoding", + 192, + (requests(), any::(), any::(), any::()), + |(mut request, seed, at, byte)| { + fill_unset_timestamps(&mut request); + let mut body = edited_body(&request, &mut SplitMix64(seed), None); + if !body.is_empty() { + let at = (at % body.len() as u64) as usize; + body[at] = byte; + } + cases.add(check_body(&request, &body, false)?); + Ok(()) + }, + ); + cases.print("otel_pb_streamed_damaged_bodies"); + } + + /// Damage inside one record, whose framing is rewritten to fit: the framing + /// above the records holds, so the rows of every record before a record that + /// no longer decodes are staged + #[test] + fn otel_pb_streamed_damaged_records_keep_the_rows_before_them() { + let cases = Cases::default(); + check( + "otel_pb_streamed_damaged_records_keep_the_rows_before_them", + 192, + ( + requests(), + any::(), + any::<(u64, u64, u8, bool)>(), + any::(), + ), + |(mut request, seed, (index, at, byte, cut), flatten_exemplars)| { + fill_unset_timestamps(&mut request); + let records = request.record_count(); + prop_assume!(records > 0); + let damage = RecordDamage { + index: index % records, + at, + byte, + cut, + }; + let body = edited_body(&request, &mut SplitMix64(seed), Some(damage)); + let case = check_body(&request, &body, flatten_exemplars)?; + prop_assert!(case != Case::Outer, "record damage broke the levels above"); + cases.add(case); + Ok(()) + }, + ); + cases.print("otel_pb_streamed_damaged_records"); + assert!(cases.get(Case::Partial) > 0, "no partial case was met"); + } + + /// Arbitrary bytes as a record of every kind stay under the bound on decoded + /// bytes per wire byte + #[test] + fn otel_pb_decoded_size_bound_holds_for_arbitrary_records() { + check( + "otel_pb_decoded_size_bound_holds_for_arbitrary_records", + 512, + (vec(any::(), 0..512), 0..3usize), + |(bytes, leaf)| { + let leaf = [Leaf::LogRecord, Leaf::Span, Leaf::Metric][leaf]; + prop_assert!( + leaf_decoded_size(&bytes, leaf) + <= leaf_struct_size(leaf) + bytes_per_wire_byte(leaf) * bytes.len() + ); + Ok(()) + }, + ); + } + + /// The cap on the decoded size of one record refuses the record before it is + /// decoded, and only a record over it + #[test] + fn oversized_records_are_refused_before_decoding() { + let span = Span { + events: vec![Event::default(); 1 << 16], + ..Default::default() + }; + let request = Req::Traces(TracesData { + resource_spans: vec![ResourceSpans { + scope_spans: vec![ScopeSpans { + spans: vec![span], + ..Default::default() + }], + ..Default::default() + }], + }); + let body = web::Bytes::from(request.encode_pb()); + let estimate = leaf_decoded_size( + &request_span_bytes(&request), + crate::otel::decoded_size::Leaf::Span, + ); + let read = |max_record: usize| { + let mut rows = 0usize; + let mut chunker = Chunker::new(CHUNK_LIMITS, |chunk: Vec, _| { + rows += chunk.len(); + Ok::<_, JsonFlattenError>(()) + }); + let result = flatten_request( + &body, + Signal::Traces, + max_record, + &mut FlattenBudget::new(FlattenLimits::DEFAULT), + false, + &mut chunker, + ) + .and_then(|()| chunker.finish().map_err(StreamError::Consumer)); + drop(chunker); + (result, rows) + }; + let (refused, allocated) = crate::test_alloc::measure(|| read(estimate - 1)); + assert!(matches!(refused.0, Err(StreamError::RecordTooLarge { .. }))); + assert_eq!(refused.1, 0); + assert!(allocated.peak < 64 * 1024, "peak {} B", allocated.peak); + let (read, rows) = read(estimate); + assert!(read.is_ok()); + assert_eq!(rows, 1 << 16); + } + + fn request_span_bytes(request: &Req) -> Vec { + match request { + Req::Traces(data) => data.resource_spans[0].scope_spans[0].spans[0].encode_to_vec(), + _ => unreachable!(), + } + } + + // ----------------------------------------------------------------------- + // Partial success after chunks were staged, without the server + // ----------------------------------------------------------------------- + + const T0: u64 = 1_700_000_000_000_000_000; + + fn string_value(value: String) -> Option { + Some(AnyValue { + value: Some(any_value::Value::StringValue(value)), + }) + } + + /// One resource of `attributes` attributes over `records` log records + fn logs_request(records: usize, attributes: usize) -> Req { + Req::Logs(LogsData { + resource_logs: vec![ResourceLogs { + resource: Some(Resource { + attributes: (0..attributes) + .map(|i| KeyValue { + key: format!("resource.attribute.{i:02}"), + value: string_value(format!("value-of-attribute-{i:02}")), + ..Default::default() + }) + .collect(), + ..Default::default() + }), + scope_logs: vec![ScopeLogs { + log_records: (0..records) + .map(|i| LogRecord { + time_unix_nano: T0 + i as u64, + observed_time_unix_nano: T0 + i as u64, + severity_number: 9, + severity_text: format!("S{i:07}"), + body: string_value(format!("record {i}")), + ..Default::default() + }) + .collect(), + ..Default::default() + }], + ..Default::default() + }], + }) + } + + /// `metrics` sum metrics of `points` points each, under a resource without a + /// target identity (so no `target_info` row) + fn metrics_request(metrics: usize, points: usize) -> Req { + Req::Metrics(MetricsData { + resource_metrics: vec![ResourceMetrics { + scope_metrics: vec![ScopeMetrics { + metrics: (0..metrics) + .map(|m| Metric { + name: format!("metric{m:05}"), + data: Some(metric::Data::Sum(Sum { + data_points: (0..points) + .map(|p| NumberDataPoint { + time_unix_nano: T0 + p as u64, + start_time_unix_nano: T0, + value: Some(number_data_point::Value::AsInt(p as i64)), + ..Default::default() + }) + .collect(), + aggregation_temporality: 2, + is_monotonic: true, + })), + ..Default::default() + }) + .collect(), + ..Default::default() + }], + ..Default::default() + }], + }) + } + + /// Replaces the first byte of the only occurrence of `marker` in `body` with + /// 0xff, so the string it is in is not UTF-8 + fn damage_marker(body: &mut [u8], marker: &[u8]) { + let at: Vec = body + .windows(marker.len()) + .enumerate() + .filter(|(_, window)| *window == marker) + .map(|(at, _)| at) + .collect(); + assert_eq!(at.len(), 1); + body[at[0]] = 0xff; + } + + /// Where staging hands its chunks in these tests + #[derive(Default)] + struct Staged2 { + rows: Vec, + bytes: usize, + chunks: usize, + } + + fn collect(staged: &mut Staged2) -> impl FnMut(Vec) -> Result<(), PostError> + '_ { + |rows| { + staged.bytes += rows + .iter() + .map(|row| crate::otel::sink::row_bytes(row.as_object().unwrap())) + .sum::(); + staged.chunks += 1; + staged.rows.extend(rows); + Ok(()) + } + } + + fn target(source: &LogSource) -> OtelTarget<'_> { + static NO_FIELDS: std::sync::LazyLock> = + std::sync::LazyLock::new(HashMap::new); + OtelTarget { + stream_name: "test_stream", + log_source: source, + p_custom_fields: &NO_FIELDS, + telemetry_type: match source { + LogSource::OtelLogs => TelemetryType::Logs, + LogSource::OtelMetrics => TelemetryType::Metrics, + _ => TelemetryType::Traces, + }, + tenant_id: &None, + } + } + + fn limits(rows: usize, max_expanded: u64) -> StageLimits { + StageLimits { + chunk: ChunkLimits { + rows, + bytes: usize::MAX, + }, + max_expanded, + flatten: FlattenLimits::DEFAULT, + } + } + + /// Stages `request` in both encodings with `stage`, the JSON one decoded as + /// ingestion decodes it + fn stage_both( + request: &Req, + limits: StageLimits, + mut stage: impl FnMut(bool, Vec) -> Result<(), PostError>, + ) -> [(Result, Staged); 2] { + let source = request.source(); + let target = target(&source); + let protobuf = stage_otel_protobuf( + web::Bytes::from(request.encode_pb()), + &target, + PROTOBUF_OPTIONS, + limits, + |rows| stage(true, rows), + ); + let decoded = decode_as(request, false); + let json = stage_otel_resources(decoded.resources(), false, limits, |rows| { + stage(false, rows) + }); + [protobuf, json] + } + + /// The expansion cap is a running total: a request passing it after chunks + /// were staged is a partial success, the same in both encodings; one passing + /// it in its first chunk is refused, as before anything is staged + #[test] + fn otel_over_the_expansion_cap_stops_alike_in_both_encodings() { + let request = logs_request(2000, 40); + let mut all = Staged2::default(); + let (whole, _) = stage_otel_protobuf( + web::Bytes::from(request.encode_pb()), + &target(&request.source()), + PROTOBUF_OPTIONS, + limits(100, u64::MAX), + collect(&mut all), + ); + assert_eq!(whole.unwrap(), OtelIngested::Full); + assert_eq!(all.rows.len(), 2000); + + // About two fifths of the rows fit under the cap + let cap = all.bytes as u64 * 2 / 5; + let mut staged = [Staged2::default(), Staged2::default()]; + let [protobuf, json] = stage_both(&request, limits(100, cap), |protobuf, rows| { + collect(&mut staged[usize::from(protobuf)])(rows) + }); + for (outcome, counted) in [&protobuf, &json] { + assert!(counted.chunks > 0 && counted.records < 2000, "{counted:?}"); + let message = format!( + "Invalid Request: The rows of the request take more than the {cap} bytes allowed (4096 times the length of its body, at least 16777216 and at most 1024 times the payload limit). Split the batch into smaller requests, or send fewer resource, scope and span attributes per record" + ); + assert_eq!( + outcome.as_ref().unwrap(), + &OtelIngested::Partial { + rejected: 2000 - counted.records as i64, + message + } + ); + assert!(counted.rows as f64 * 1.0 <= 2000.0 * 0.4 + 100.0); + } + assert_eq!(protobuf.1, json.1); + assert_eq!( + serde_json::to_vec(&staged[0].rows).unwrap(), + serde_json::to_vec(&staged[1].rows).unwrap() + ); + println!( + "over the cap: {} of 2000 records staged in {} chunks, {} rejected", + protobuf.1.records, + protobuf.1.chunks, + 2000 - protobuf.1.records + ); + + // Passed in the first chunk: refused as before staging + let [protobuf, json] = stage_both(&request, limits(100, 1000), |_, _| Ok(())); + for (outcome, counted) in [protobuf, json] { + assert_eq!(counted.chunks, 0); + let error = outcome.unwrap_err(); + assert!(matches!(error, PostError::Invalid(_)), "{error:?}"); + assert!( + error + .to_string() + .contains("more than the 1000 bytes allowed") + ); + } + } + + /// A record that does not decode, met after chunks were staged, is a partial + /// success with prost's error; as the first record, a refusal with it + #[test] + fn otel_pb_record_damaged_late_is_a_partial_success() { + for (damaged, staged_records) in [(999, 900), (0, 0)] { + let mut request = logs_request(1000, 5); + if let Req::Logs(data) = &mut request { + data.resource_logs[0].scope_logs[0].log_records[damaged].severity_text = + "DAMAGEME".into(); + } + let mut body = request.encode_pb(); + damage_marker(&mut body, b"DAMAGEME"); + let prost_error = OtelProtobufRequest::decode(&body, &request.source()) + .unwrap_err() + .to_string(); + let mut staged_rows = Staged2::default(); + let (outcome, staged) = stage_otel_protobuf( + web::Bytes::from(body), + &target(&request.source()), + PROTOBUF_OPTIONS, + limits(100, u64::MAX), + collect(&mut staged_rows), + ); + let message = + format!("Invalid Request: Ingestion failed for stream test_stream: {prost_error}"); + assert_eq!(staged.records, staged_records); + if staged_records > 0 { + assert_eq!(staged.chunks, 9); + assert_eq!( + outcome.unwrap(), + OtelIngested::Partial { + rejected: 1000 - staged_records as i64, + message + } + ); + } else { + assert_eq!(outcome.unwrap_err().to_string(), message); + } + println!("damaged record {damaged}: {prost_error}"); + } + } + + /// A record over the decoded size cap, met after chunks were staged, is a + /// partial success; it is measured because it is long enough to reach the cap + #[test] + fn otel_pb_record_over_the_cap_late_is_a_partial_success() { + let mut request = logs_request(1000, 5); + if let Req::Logs(data) = &mut request { + data.resource_logs[0].scope_logs[0].log_records[999].body = + string_value("x".repeat(100_000)); + } + let options = ProtobufOptions { + max_payload: 4096, + flatten_exemplars: false, + }; + let max_record = crate::otel::protobuf_stream::max_record_bytes(options.max_payload); + assert!(crate::otel::decoded_size::needs_measuring( + 100_010, + Leaf::LogRecord, + max_record + )); + assert!(!crate::otel::decoded_size::needs_measuring( + 100, + Leaf::LogRecord, + max_record + )); + let (outcome, staged) = stage_otel_protobuf( + web::Bytes::from(request.encode_pb()), + &target(&request.source()), + options, + limits(100, u64::MAX), + |_| Ok(()), + ); + assert_eq!(staged.records, 900); + match outcome.unwrap() { + OtelIngested::Partial { rejected, message } => { + assert_eq!(rejected, 100); + assert!( + message + .contains("one LogRecord of the request would take more than 65536 bytes"), + "{message}" + ); + } + other => panic!("{other:?}"), + } + } + + /// A metrics request stopped after some chunks rejects exactly the data points + /// not staged: when staging refuses a chunk (both encodings), when a later + /// metric does not decode (its points read from the wire), and a server error + /// keeps its status + #[test] + fn otel_metrics_stopped_after_some_chunks_reject_the_points_not_staged() { + let request = metrics_request(10, 37); + let refusal = || PostError::Invalid(anyhow::anyhow!("schema conflict")); + let mut calls = [0, 0]; + let [protobuf, json] = stage_both(&request, limits(50, u64::MAX), |protobuf, _| { + let calls = &mut calls[usize::from(protobuf)]; + *calls += 1; + if *calls == 4 { Err(refusal()) } else { Ok(()) } + }); + for (outcome, staged) in [protobuf, json] { + assert_eq!(staged.points, 150); + assert_eq!(staged.records, 4); + assert_eq!( + outcome.unwrap(), + OtelIngested::Partial { + rejected: 370 - 150, + message: "Invalid Request: schema conflict".into() + } + ); + } + + // Metric 8 does not decode: metrics 0-7 (296 points) were flattened, 250 of + // them in full chunks; its 37 points are read from the wire + let mut damaged = request.clone(); + if let Req::Metrics(data) = &mut damaged { + data.resource_metrics[0].scope_metrics[0].metrics[8].name = "DAMAGEME".into(); + } + let mut body = damaged.encode_pb(); + damage_marker(&mut body, b"DAMAGEME"); + let body = web::Bytes::from(body); + assert_eq!(count_points(&body), 370); + let (outcome, staged) = stage_otel_protobuf( + body, + &target(&request.source()), + PROTOBUF_OPTIONS, + limits(50, u64::MAX), + |_| Ok(()), + ); + assert_eq!((staged.chunks, staged.points), (5, 250)); + match outcome.unwrap() { + OtelIngested::Partial { rejected, message } => { + assert_eq!(rejected, 370 - 250); + assert!(message.contains("invalid string value"), "{message}"); + } + other => panic!("{other:?}"), + } + + // A server error after chunks were staged keeps its status + let mut calls = 0; + let [protobuf, _] = stage_both(&request, limits(50, u64::MAX), |protobuf, _| { + calls += usize::from(protobuf); + if protobuf && calls == 2 { + Err(PostError::JsonFlattenError(JsonFlattenError::CannotFlatten)) + } else { + Ok(()) + } + }); + let error = protobuf.0.unwrap_err(); + assert!( + actix_web::ResponseError::status_code(&error).is_server_error(), + "{error:?}" + ); + assert_eq!(protobuf.1.chunks, 1); + } +} diff --git a/src/handlers/http/modal/utils/ingest_utils/otel_regression_tests.rs b/src/handlers/http/modal/utils/ingest_utils/otel_regression_tests.rs new file mode 100644 index 000000000..5ca50ede4 --- /dev/null +++ b/src/handlers/http/modal/utils/ingest_utils/otel_regression_tests.rs @@ -0,0 +1,322 @@ +/* + * Parseable Server (C) 2022 - 2025 Parseable, Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + */ + +//! Regression tests for what two reviews of chunked OTLP staging found, at the +//! level of one request. Each prints `REGRESSION : ...`. None touches +//! `PARSEABLE`, so they may be run with the filter `otel_regression_tests`; the +//! ones that need the server are in `otel_server_state_tests`. + +use super::*; +use crate::metadata::SchemaVersion; +use crate::otel::sink::RowSink; +use crate::utils::json::flatten::JsonFlattenError; +use arrow_schema::Field; +use opentelemetry_proto::tonic::common::v1::{AnyValue, KeyValue, any_value}; +use opentelemetry_proto::tonic::logs::v1::{LogRecord, ScopeLogs}; +use opentelemetry_proto::tonic::metrics::v1::{ + Gauge, Metric, NumberDataPoint, ScopeMetrics, metric, number_data_point, +}; +use opentelemetry_proto::tonic::resource::v1::Resource; +use serde_json::{Map, json}; +use std::collections::BTreeMap; +use std::sync::Arc; + +const MIB: usize = 1024 * 1024; + +/// `P_MAX_EVENT_PAYLOAD_SIZE` default +const PAYLOAD: usize = 10 * MIB; + +const OPTIONS: ProtobufOptions = ProtobufOptions { + max_payload: PAYLOAD, + flatten_exemplars: false, +}; + +fn kv(key: &str, value: impl Into) -> KeyValue { + KeyValue { + key: key.into(), + value: Some(AnyValue { + value: Some(any_value::Value::StringValue(value.into())), + }), + ..Default::default() + } +} + +fn target<'a>( + log_source: &'a LogSource, + p_custom_fields: &'a HashMap, +) -> OtelTarget<'a> { + OtelTarget { + stream_name: "otel_regression", + log_source, + p_custom_fields, + telemetry_type: TelemetryType::Logs, + tenant_id: &None, + } +} + +/// The staging limits ingestion uses for a body of `body_len` bytes +fn limits_for(body_len: usize) -> StageLimits { + StageLimits::for_body(body_len, PAYLOAD, FlattenLimits::DEFAULT) +} + +/// Review finding 8: the expansion cap was 1024 x `P_MAX_EVENT_PAYLOAD_SIZE` +/// (10 GiB) whatever the size of the body, so a body of a few KiB could stage +/// gigabytes of rows. It is now 4096 x the length of the body, with a floor, and +/// that 10 GiB (1024 x the payload limit) is kept as a ceiling, which decides for +/// bodies over a quarter of the limit: without it a body of the full limit could +/// stage 40 GiB of rows. +#[test] +fn expansion_cap_is_4096_times_the_body_with_a_floor_and_a_ceiling() { + use crate::otel::sink::{EXPANSION_CEILING_FACTOR, EXPANSION_FACTOR, MIN_EXPANDED_BYTES}; + assert_eq!(EXPANSION_FACTOR, 4096); + assert_eq!(EXPANSION_CEILING_FACTOR, 1024); + assert_eq!(max_expanded_bytes(0, PAYLOAD), MIN_EXPANDED_BYTES); + assert_eq!(max_expanded_bytes(1000, PAYLOAD), MIN_EXPANDED_BYTES); + assert_eq!(max_expanded_bytes(1 << 20, PAYLOAD), 4u64 << 30); + assert_eq!(max_expanded_bytes(PAYLOAD / 4, PAYLOAD), 10u64 << 30); + assert_eq!(max_expanded_bytes(PAYLOAD / 4 + 1, PAYLOAD), 10u64 << 30); + assert_eq!(max_expanded_bytes(PAYLOAD, PAYLOAD), 10u64 << 30); + // The ceiling follows the payload limit, and is never under the floor + assert_eq!(max_expanded_bytes(4 * PAYLOAD, 4 * PAYLOAD), 40u64 << 30); + assert_eq!(max_expanded_bytes(usize::MAX, usize::MAX), u64::MAX); + assert_eq!(max_expanded_bytes(1 << 20, 1024), MIN_EXPANDED_BYTES); + assert_eq!(max_expanded_bytes(1 << 20, 0), MIN_EXPANDED_BYTES); +} + +/// Review finding 8, as a request: a body of 47 KiB whose rows expand past 4096x +/// its length is cut off by the cap (it passed whole under the 10 GiB cap) +#[test] +fn a_small_body_expanding_past_4096_times_its_length_is_refused() { + // 100 resource attributes over records of two bytes each: their rows hold + // about 460 MB, past 4096 x the body's length but far under 10 GiB + let request = ExportLogsServiceRequest { + resource_logs: vec![ResourceLogs { + resource: Some(Resource { + attributes: (0..100) + .map(|i| kv(&format!("k8s.pod.label.{i:03}"), format!("{i:032}"))) + .collect(), + ..Default::default() + }), + scope_logs: vec![ScopeLogs { + log_records: vec![LogRecord::default(); 20_000], + ..Default::default() + }], + ..Default::default() + }], + }; + let body = web::Bytes::from(request.encode_to_vec()); + let limits = limits_for(body.len()); + let fields = HashMap::new(); + let mut staged_bytes = 0u64; + let (outcome, staged) = stage_otel_protobuf( + body.clone(), + &target(&LogSource::OtelLogs, &fields), + OPTIONS, + limits, + |rows| { + staged_bytes += rows + .iter() + .map(|row| crate::otel::sink::row_bytes(row.as_object().unwrap()) as u64) + .sum::(); + Ok(()) + }, + ); + println!( + "REGRESSION expansion cap: body {} B, cap {} B, staged {} of 20000 rows ({} B), outcome {:?}", + body.len(), + limits.max_expanded, + staged.rows, + staged_bytes, + outcome.as_ref().map_err(|e| e.to_string()) + ); + assert!( + matches!(&outcome, Ok(OtelIngested::Partial { rejected, .. }) if *rejected > 0), + "{outcome:?}" + ); + assert!(staged_bytes <= limits.max_expanded); +} + +/// Columns staged for `rows`, as one batch or in chunks of `chunk` rows, each +/// chunk typed against the schema the chunks before it committed, as a stream's +/// schema is +fn staged_columns(rows: &[Value], chunk: usize) -> Vec<(String, String, Vec)> { + use crate::event::format::{EventFormat as _, json as json_format}; + let mut storage: HashMap> = HashMap::new(); + let mut cells: BTreeMap)> = BTreeMap::new(); + for part in rows.chunks(chunk) { + let (rb, _) = json_format::Event { + json: Value::Array(part.to_vec()), + p_timestamp: chrono::Utc::now(), + } + .into_recordbatch( + &storage, + false, + None, + SchemaVersion::V1, + &HashMap::new(), + true, + ) + .unwrap(); + for (i, field) in rb.schema().fields().iter().enumerate() { + if field.name() == "p_timestamp" { + continue; + } + storage.insert(field.name().clone(), field.clone()); + let column = rb.column(i); + let entry = cells + .entry(field.name().clone()) + .or_insert_with(|| (format!("{:?}", field.data_type()), Vec::new())); + for row in 0..rb.num_rows() { + entry.1.push( + arrow::util::display::array_value_to_string(column, row).unwrap_or_default(), + ); + } + } + } + cells + .into_iter() + .map(|(name, (ty, values))| (name, ty, values)) + .collect() +} + +/// Review finding 3, kept as documented behaviour: each chunk of a request is +/// typed against the schema the chunk before it committed, so a value whose type +/// changes between the records of a request that is cut into chunks can land in +/// a differently named column than one batch would put it in, exactly as two +/// separate requests would. Requests that fit in one chunk are not affected. +#[test] +fn a_type_change_between_chunks_lands_where_a_second_request_would_put_it() { + let columns = |columns: &[(String, String, Vec)]| { + columns + .iter() + .map(|(name, ty, values)| format!("{name}:{ty}:{}", values.join("|"))) + .collect::>() + }; + let cases = [ + ( + vec![json!({"x": true, "n": 1}), json!({"x": "on", "n": 2})], + ["n:Float64:1.0|2.0", "x:Utf8:|on", "x_bool:Boolean:true|"], + ["n:Float64:1.0|2.0", "x:Boolean:true", "x_utf8:Utf8:on"], + ), + ( + vec![ + json!({"http_status_code": 200, "n": 1}), + json!({"http_status_code": "OK", "n": 2}), + ], + [ + "http_status_code:Utf8:|OK", + "http_status_code_int64:Float64:200.0|", + "n:Float64:1.0|2.0", + ], + [ + "http_status_code:Float64:200.0", + "http_status_code_utf8:Utf8:OK", + "n:Float64:1.0|2.0", + ], + ), + ]; + for (rows, one_batch, two_chunks) in cases { + let whole = columns(&staged_columns(&rows, rows.len())); + let chunked = columns(&staged_columns(&rows, 1)); + println!("REGRESSION type change: one batch {whole:?}, two chunks {chunked:?}"); + assert_eq!(whole, one_batch); + assert_eq!(chunked, two_chunks); + } +} + +/// Security review finding 2: the sizing pass charged the Prometheus `job` and +/// `instance` labels at 32 bytes, but they hold copies of `service.name` and +/// `service.instance.id`. There is no sizing pass any more: the running total is +/// the `row_bytes` of every staged row, labels included at their real size, so a +/// request whose labels are long is refused where its rows pass the cap. +#[test] +fn expansion_total_counts_the_prometheus_identity_labels_at_their_size() { + const LABEL: usize = 64 * 1024; + let label = LABEL; + let points = 13_000usize; + let resource_metrics = vec![ResourceMetrics { + resource: Some(Resource { + attributes: vec![kv("service.name", "n".repeat(label))], + ..Default::default() + }), + scope_metrics: vec![ScopeMetrics { + metrics: vec![Metric { + name: "m".into(), + data: Some(metric::Data::Gauge(Gauge { + data_points: (0..points) + .map(|i| NumberDataPoint { + time_unix_nano: 1_700_000_000_000_000_000 + i as u64, + start_time_unix_nano: 1_700_000_000_000_000_000, + value: Some(number_data_point::Value::AsDouble(1.0)), + ..Default::default() + }) + .collect(), + })), + ..Default::default() + }], + ..Default::default() + }], + ..Default::default() + }]; + + /// Keeps the `row_bytes` of the first row + #[derive(Default)] + struct First(Option); + impl RowSink for First { + type Error = JsonFlattenError; + fn row(&mut self, row: Map) -> Result<(), Self::Error> { + assert_eq!(row["job"], json!("n".repeat(LABEL))); + self.0.get_or_insert(crate::otel::sink::row_bytes(&row)); + Err(JsonFlattenError::CannotFlatten) + } + } + let mut first = First::default(); + let _ = flatten_metrics_into(&resource_metrics, false, &mut first); + let per_row = first.0.unwrap() as u64; + + let max_expanded = 1u64 << 30; + let limits = StageLimits { + chunk: CHUNK_LIMITS, + max_expanded, + flatten: FlattenLimits::DEFAULT, + }; + let mut staged_bytes = 0u64; + let (outcome, staged) = stage_otel_resources( + OtelResources::Metrics(&resource_metrics), + false, + limits, + |rows| { + staged_bytes += rows + .iter() + .map(|row| crate::otel::sink::row_bytes(row.as_object().unwrap()) as u64) + .sum::(); + Ok(()) + }, + ); + println!( + "REGRESSION identity labels: {per_row} row bytes per row ({label} B label twice), staged {} of {points} rows, {staged_bytes} B, cap {max_expanded} B, outcome {:?}", + staged.rows, + outcome.as_ref().map_err(|e| e.to_string()) + ); + // `service.name` and its copy in `job`, each at its real size + assert!(per_row > 2 * label as u64); + assert!(matches!(outcome, Ok(OtelIngested::Partial { .. }))); + assert!(staged_bytes <= max_expanded); + // Stopped by the cap, not before it: one more chunk would have passed it + assert!(staged_bytes + CHUNK_LIMITS.bytes as u64 + per_row > max_expanded); +} diff --git a/src/handlers/http/modal/utils/ingest_utils/otel_server_state_tests.rs b/src/handlers/http/modal/utils/ingest_utils/otel_server_state_tests.rs new file mode 100644 index 000000000..5baea4be9 --- /dev/null +++ b/src/handlers/http/modal/utils/ingest_utils/otel_server_state_tests.rs @@ -0,0 +1,163 @@ +/* + * Parseable Server (C) 2022 - 2025 Parseable, Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + */ + +//! Regression tests of OTLP ingestion that read the server state (`PARSEABLE`). +//! Each first sets up the global server state as the metastore contract tests do +//! (`CONTRACT_PARSEABLE_FACTORY`: default options, local storage in a temporary +//! directory under `target`), so the configuration is never parsed from the test +//! binary's command line and the tests may be run with a name filter. Each prints +//! `REGRESSION : ...`. + +use super::*; +use crate::metadata::{LogStreamMetadata, SchemaVersion}; +use actix_web::test::TestRequest; +use arrow_schema::{DataType, Field}; +use std::sync::Arc; + +/// Sets up `PARSEABLE` for tests, unless a test already did +fn initialize_server() { + fn factory() -> crate::parseable::Parseable { + use crate::storage::object_storage::ObjectStorageProvider; + let root = tempfile::tempdir_in(concat!(env!("CARGO_MANIFEST_DIR"), "/target")) + .unwrap() + .keep(); + let provider = Arc::new(crate::storage::FSConfig { root }); + let storage = provider.construct_client(); + let metastore = Arc::new( + crate::metastore::metastores::object_store_metastore::ObjectStoreMetastore { + storage: storage.clone(), + }, + ); + crate::parseable::Parseable::new( + crate::cli::Options::default(), + #[cfg(feature = "kafka")] + ::parse_from(["otel"]), + provider, + metastore, + storage, + ) + } + let _ = crate::parseable::CONTRACT_PARSEABLE_FACTORY.set(factory); + once_cell::sync::Lazy::force(&PARSEABLE); +} + +const SIGNALS: [(TelemetryType, LogSource); 3] = [ + (TelemetryType::Logs, LogSource::OtelLogs), + (TelemetryType::Metrics, LogSource::OtelMetrics), + (TelemetryType::Traces, LogSource::OtelTraces), +]; + +/// Review finding 7d: an empty request must be answered 200 without the stream, +/// in both encodings and for every signal. Collector setup scripts detect +/// protobuf support by posting an empty protobuf body to `/v1/metrics`. +#[tokio::test] +async fn empty_requests_are_answered_200_without_a_stream() { + initialize_server(); + for (telemetry_type, log_source) in SIGNALS { + for (content_type, body) in [ + ("application/x-protobuf", &b""[..]), + ("application/json", &b"{}"[..]), + ] { + let req = TestRequest::default() + .insert_header((CONTENT_TYPE, content_type)) + .to_http_request(); + let ingested = process_otel_content( + &req, + web::Bytes::from_static(body), + "otel_regression_no_such_stream", + &log_source, + telemetry_type, + ) + .await; + println!( + "REGRESSION empty request, {log_source}, {content_type}: {:?}", + ingested.as_ref().map_err(|e| e.to_string()) + ); + let ingested = ingested.expect("an empty request is accepted"); + assert_eq!(ingested, OtelIngested::Full); + let response = otel_response(&req, telemetry_type, &ingested); + assert_eq!(response.status(), actix_web::http::StatusCode::OK); + } + } +} + +/// Review finding 7a: for OTLP JSON the dataset field count is checked before +/// the body is decoded into a request, as at `b8c7d979`: a body that is not a +/// request, sent to a dataset over its field limit, is refused for the limit. +#[tokio::test] +async fn otlp_json_checks_the_field_count_before_decoding() { + initialize_server(); + let stream = "otel_regression_fields_limit"; + let limit = PARSEABLE.options.dataset_fields_allowed_limit; + let schema = (0..=limit) + .map(|i| { + let name = format!("f{i}"); + ( + name.clone(), + Arc::new(Field::new(name, DataType::Utf8, true)), + ) + }) + .collect(); + PARSEABLE.streams.get_or_create( + PARSEABLE.options.clone(), + stream.to_string(), + LogStreamMetadata { + schema, + schema_version: SchemaVersion::V1, + ..Default::default() + }, + None, + &None, + ); + for (telemetry_type, log_source, body) in [ + ( + TelemetryType::Logs, + LogSource::OtelLogs, + r#"{"resourceLogs":5}"#, + ), + ( + TelemetryType::Metrics, + LogSource::OtelMetrics, + r#"{"resourceMetrics":5}"#, + ), + ( + TelemetryType::Traces, + LogSource::OtelTraces, + r#"{"resourceSpans":5}"#, + ), + ] { + let req = TestRequest::default() + .insert_header((CONTENT_TYPE, "application/json")) + .to_http_request(); + let refused = process_otel_content( + &req, + web::Bytes::from_static(body.as_bytes()), + stream, + &log_source, + telemetry_type, + ) + .await + .expect_err("refused"); + println!("REGRESSION field count before decoding, {log_source}: {refused}"); + assert!( + matches!(refused, PostError::FieldsCountLimitExceeded(..)), + "{log_source}: {refused:?}" + ); + } + PARSEABLE.streams.delete(stream, &None); +} diff --git a/src/lib.rs b/src/lib.rs index 25d723809..5ec167060 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -134,6 +134,10 @@ pub static INTRA_CLUSTER_CLIENT: Lazy = Lazy::new(|| { .expect("Construction of client shouldn't fail") }); +// Counts what a test thread allocates, see `test_alloc::measure` +#[cfg(test)] +pub(crate) mod test_alloc; + // Keep the native build contract covered without network or frontend tooling. #[cfg(test)] #[path = "../build_support/native_ui.rs"] diff --git a/src/otel.rs b/src/otel.rs index 9accb4622..4f2855e95 100644 --- a/src/otel.rs +++ b/src/otel.rs @@ -16,11 +16,23 @@ * */ +pub mod decoded_size; pub mod logs; pub mod metrics; pub mod otel_utils; +pub mod protobuf_stream; +pub mod sink; pub mod traces; +#[cfg(test)] +mod corpus_tests; +#[cfg(test)] +mod memory_tests; +#[cfg(test)] +mod realistic_tests; +#[cfg(test)] +mod regression_tests; + /// Shared driver for the release-profile micro-benchmarks. Each benchmark is an /// `#[ignore]`d test that never touches the `PARSEABLE` global, so it can be run /// with a test-name filter: @@ -34,14 +46,24 @@ pub mod traces; /// the per-row wall time for `perf stat` to turn into instruction counts. #[cfg(test)] pub(crate) mod bench { + use crate::utils::json::flatten::JsonFlattenError; use std::time::Instant; /// Runs `body` `iters` times, requiring identical output every time, and /// prints the rows, their digest and the nanoseconds spent per row. + /// + /// `OTEL_BENCH_ITERS=` overrides `iters`. Running a benchmark at two + /// iteration counts under `perf stat` and dividing the difference in + /// instructions by the difference in rows flattened removes the fixed cost + /// of building the request and taking the digests. pub fn run(name: &str, iters: usize, mut body: F) where F: FnMut() -> Vec, { + let iters = std::env::var("OTEL_BENCH_ITERS") + .ok() + .and_then(|iters| iters.parse().ok()) + .unwrap_or(iters); // Serialising the rows costs more than flattening them, so the digest is // taken before and after the timed loop, never inside it. let first = body(); @@ -69,7 +91,7 @@ pub(crate) mod bench { ); println!( "{name}: rows={rows} iters={iters} ns_per_row={:.1} bytes={} digest={:016x}", - elapsed.as_secs_f64() * 1e9 / (rows * iters) as f64, + elapsed.as_secs_f64() * 1e9 / (rows * iters.max(1)) as f64, expected.0, expected.1 ); @@ -95,6 +117,31 @@ pub(crate) mod bench { ); } + /// The rows `flatten` hands to a `Chunker` with the default limits, each + /// chunk appended to the result as it is passed on + pub fn chunked( + flatten: impl FnOnce( + &mut super::sink::Chunker< + &mut dyn FnMut(Vec, usize) -> Result<(), JsonFlattenError>, + >, + ) -> Result<(), JsonFlattenError>, + ) -> Vec { + let mut rows = Vec::new(); + let mut stage = |chunk: Vec, _bytes: usize| { + rows.extend(chunk); + Ok(()) + }; + let mut chunker = super::sink::Chunker::new( + super::sink::CHUNK_LIMITS, + &mut stage + as &mut dyn FnMut(Vec, usize) -> Result<(), JsonFlattenError>, + ); + flatten(&mut chunker).expect("benchmark rows flatten"); + chunker.finish().expect("benchmark rows stage"); + drop(chunker); + rows + } + fn dump_dir() -> Option { std::env::var("OTEL_BENCH_DUMP").ok() } diff --git a/src/otel/corpus_tests.rs b/src/otel/corpus_tests.rs new file mode 100644 index 000000000..19bcbd935 --- /dev/null +++ b/src/otel/corpus_tests.rs @@ -0,0 +1,691 @@ +/* + * Parseable Server (C) 2022 - 2025 Parseable, Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + */ + +//! Seeded corpus of generated OTLP requests, pinning the rows the flatteners +//! make for every signal. A change to the flatteners that is meant to be a pure +//! speedup must leave every digest here unchanged: the rows, their values and +//! the order of the keys inside each row (which decides column order). +//! +//! The generator aims at what the benchmark requests do not reach: attribute +//! keys that collide with fixed row fields and with each other across resource, +//! scope, record, event, link and data point; repeated keys inside one list; +//! attributes without a value; every `AnyValue` kind, nested; empty and missing +//! scopes and resources; log bodies of every kind including JSON text; every +//! metric type with exemplars and metadata; spans with many events and links. +//! Every timestamp is set, so rows do not depend on the clock. +//! +//! Conventions follow the DST harness: SplitMix64, `DST_SEED` and `DST_ITERS` +//! override the seed and the request count (the pinned digests are checked +//! only for the defaults), and the seed is printed. None of these tests touches +//! `PARSEABLE`, so they may be run with the filter `otel::corpus_tests`. + +use opentelemetry_proto::tonic::common::v1::{ + AnyValue, ArrayValue, InstrumentationScope, KeyValue, KeyValueList, any_value, +}; +use opentelemetry_proto::tonic::logs::v1::{LogRecord, ResourceLogs, ScopeLogs}; +use opentelemetry_proto::tonic::metrics::v1::{ + Exemplar, ExponentialHistogram, ExponentialHistogramDataPoint, Gauge, Histogram, + HistogramDataPoint, Metric, NumberDataPoint, ResourceMetrics, ScopeMetrics, Sum, Summary, + SummaryDataPoint, exemplar, exponential_histogram_data_point, metric, number_data_point, + summary_data_point, +}; +use opentelemetry_proto::tonic::resource::v1::Resource; +use opentelemetry_proto::tonic::trace::v1::span::{Event, Link}; +use opentelemetry_proto::tonic::trace::v1::{ResourceSpans, ScopeSpans, Span, Status}; +use serde_json::Value; + +use crate::utils::json::flatten::{FlattenBudget, FlattenLimits}; + +const DEFAULT_SEED: u64 = 0x0071_9c0d_5eed_2026; +const DEFAULT_ITERS: usize = 3000; + +/// SplitMix64, as the DST harness uses +struct Rng(u64); + +impl Rng { + fn next(&mut self) -> u64 { + self.0 = self.0.wrapping_add(0x9e37_79b9_7f4a_7c15); + let mut z = self.0; + z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9); + z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb); + z ^ (z >> 31) + } + + /// A number in `0..n` + fn below(&mut self, n: usize) -> usize { + (self.next() % n as u64) as usize + } + + /// True with probability `percent` in 100 + fn chance(&mut self, percent: usize) -> bool { + self.below(100) < percent + } + + fn pick<'a, T>(&mut self, items: &'a [T]) -> &'a T { + &items[self.below(items.len())] + } + + /// A nonzero timestamp, so the flatteners never read the clock + fn timestamp(&mut self) -> u64 { + match self.below(4) { + 0 => 1, + 1 => 1_700_000_000_000_000_000 + self.below(1_000_000_000) as u64, + 2 => u64::MAX - self.below(1000) as u64, + _ => 1 + self.next() % (i64::MAX as u64), + } + } + + fn id(&mut self) -> Vec { + let len = *self.pick(&[0usize, 8, 16, 3]); + (0..len).map(|_| self.next() as u8).collect() + } +} + +/// Keys every signal can collide with: its own fixed row fields, generic keys +/// shared across levels, and keys a flattened JSON body or key-value list makes +fn key_pool() -> Vec<&'static str> { + let mut keys: Vec<&'static str> = vec![ + "k", + "a", + "a.b", + "service.name", + "host.name", + "body", + "body_a", + "body_k", + "p_timestamp", + "p_log_category", + "", + "ключ", + "le", + "quantile", + ]; + keys.extend(super::logs::OTEL_LOG_KNOWN_FIELD_LIST); + keys.extend(super::traces::OTEL_TRACES_KNOWN_FIELD_LIST); + keys.extend(super::metrics::OTEL_METRICS_KNOWN_FIELD_LIST); + keys +} + +const TEXTS: [&str; 14] = [ + "", + "v", + "INFO", + "warn", + "Error", + "UNSPECIFIED", + "fatal: disk full", + "ünïcödé ✓", + "{\"a\":1,\"b\":{\"c\":[1,2,{\"d\":null}]},\"k\":\"x\"}", + "{\"severity_text\":\"x\",\"body\":true,\"nested\":{\"deep\":{\"deeper\":[[1],[2]]}}}", + "{}", + "[1,2,3]", + "{\"a\":", + "null", +]; + +const DOUBLES: [f64; 12] = [ + 0.0, + -0.0, + 1.5, + -2.25, + 1e20, + 1e21, + 1e-7, + 123456789.125, + f64::MAX, + f64::MIN_POSITIVE, + f64::NAN, + f64::INFINITY, +]; + +struct Gen { + rng: Rng, + keys: Vec<&'static str>, +} + +impl Gen { + fn key(&mut self) -> String { + // A small pool for most keys, so lists repeat keys and levels collide + if self.rng.chance(85) { + let index = self.rng.below(self.keys.len().min(24)); + self.keys[index].to_string() + } else { + self.rng.pick(&self.keys).to_string() + } + } + + fn text(&mut self) -> String { + if self.rng.chance(80) { + self.rng.pick(&TEXTS).to_string() + } else { + format!("s{}", self.rng.next() % 1000) + } + } + + fn any_value(&mut self, depth: usize) -> AnyValue { + AnyValue { + value: self.value(depth), + } + } + + fn value(&mut self, depth: usize) -> Option { + let kinds = if depth == 0 { 6 } else { 8 }; + Some(match self.rng.below(kinds + 1) { + 0 => return None, + 1 => any_value::Value::StringValue(self.text()), + 2 => any_value::Value::BoolValue(self.rng.chance(50)), + 3 => { + let random = self.rng.next() as i64; + any_value::Value::IntValue(*self.rng.pick(&[0, -1, 42, i64::MIN, i64::MAX, random])) + } + 4 => any_value::Value::DoubleValue(*self.rng.pick(&DOUBLES)), + 5 => { + let len = self.rng.below(6); + let mut bytes: Vec = (0..len).map(|_| self.rng.next() as u8).collect(); + if self.rng.chance(30) { + bytes.extend_from_slice(b"ok"); + } + any_value::Value::BytesValue(bytes) + } + 6 => any_value::Value::StringValue(self.rng.pick(&TEXTS[8..]).to_string()), + 7 => any_value::Value::ArrayValue(ArrayValue { + values: (0..self.rng.below(5)) + .map(|_| self.any_value(depth - 1)) + .collect(), + }), + _ => any_value::Value::KvlistValue(KeyValueList { + values: self.attributes_up_to(4, depth - 1), + }), + }) + } + + fn attribute(&mut self, depth: usize) -> KeyValue { + KeyValue { + key: self.key(), + value: if self.rng.chance(10) { + None + } else { + Some(self.any_value(depth)) + }, + ..Default::default() + } + } + + fn attributes_up_to(&mut self, max: usize, depth: usize) -> Vec { + let len = self.rng.below(max + 1); + let mut attributes: Vec = (0..len).map(|_| self.attribute(depth)).collect(); + // Sometimes one key many times over + if self.rng.chance(5) { + let key = self.key(); + for _ in 0..self.rng.below(40) { + let mut attribute = self.attribute(depth); + attribute.key = key.clone(); + attributes.push(attribute); + } + } + attributes + } + + fn attributes(&mut self) -> Vec { + self.attributes_up_to(8, 3) + } + + fn resource(&mut self) -> Option { + match self.rng.below(5) { + 0 => None, + 1 => Some(Resource::default()), + _ => Some(Resource { + attributes: self.attributes(), + dropped_attributes_count: self.rng.below(3) as u32, + ..Default::default() + }), + } + } + + fn scope(&mut self) -> Option { + match self.rng.below(5) { + 0 => None, + 1 => Some(InstrumentationScope::default()), + _ => Some(InstrumentationScope { + name: self.text(), + version: self.text(), + attributes: self.attributes(), + dropped_attributes_count: self.rng.below(3) as u32, + }), + } + } + + fn schema_url(&mut self) -> String { + if self.rng.chance(50) { + String::new() + } else { + "https://opentelemetry.io/schemas/1.21.0".into() + } + } + + fn count(&mut self, max: usize) -> usize { + self.rng.below(max + 1) + } + + fn log_record(&mut self) -> LogRecord { + LogRecord { + time_unix_nano: self.rng.timestamp(), + observed_time_unix_nano: self.rng.timestamp(), + severity_number: self.rng.below(28) as i32 - 1, + severity_text: self.text(), + body: match self.rng.below(6) { + 0 => None, + 1 => Some(AnyValue { + value: Some(any_value::Value::StringValue( + self.rng.pick(&TEXTS[8..]).to_string(), + )), + }), + _ => Some(self.any_value(3)), + }, + attributes: self.attributes(), + dropped_attributes_count: self.rng.below(3) as u32, + flags: *self.rng.pick(&[0u32, 1, 255, 256, 7]), + trace_id: self.rng.id(), + span_id: self.rng.id(), + event_name: self.text(), + } + } + + fn logs(&mut self) -> Vec { + (0..self.count(3)) + .map(|_| ResourceLogs { + resource: self.resource(), + scope_logs: (0..self.count(3)) + .map(|_| ScopeLogs { + scope: self.scope(), + log_records: (0..self.count(4)).map(|_| self.log_record()).collect(), + schema_url: self.schema_url(), + }) + .collect(), + schema_url: self.schema_url(), + }) + .collect() + } + + fn event(&mut self) -> Event { + Event { + time_unix_nano: self.rng.timestamp(), + name: self.text(), + attributes: self.attributes_up_to(4, 2), + dropped_attributes_count: self.rng.below(3) as u32, + } + } + + fn link(&mut self) -> Link { + Link { + trace_id: self.rng.id(), + span_id: self.rng.id(), + trace_state: self.text(), + attributes: self.attributes_up_to(4, 2), + dropped_attributes_count: self.rng.below(3) as u32, + flags: *self.rng.pick(&[0u32, 1, 256, 512, 769]), + } + } + + fn span(&mut self) -> Span { + // Most spans have a few events and links; some have many + let (events, links) = if self.rng.chance(5) { + (20 + self.count(60), 10 + self.count(30)) + } else { + (self.count(3), self.count(2)) + }; + Span { + trace_id: self.rng.id(), + span_id: self.rng.id(), + trace_state: self.text(), + parent_span_id: self.rng.id(), + flags: *self.rng.pick(&[0u32, 255, 256, 512, 1, 769]), + name: self.text(), + kind: self.rng.below(8) as i32 - 1, + start_time_unix_nano: self.rng.timestamp(), + end_time_unix_nano: self.rng.timestamp(), + attributes: self.attributes(), + dropped_attributes_count: self.rng.below(3) as u32, + events: (0..events).map(|_| self.event()).collect(), + dropped_events_count: self.rng.below(3) as u32, + links: (0..links).map(|_| self.link()).collect(), + dropped_links_count: self.rng.below(3) as u32, + status: if self.rng.chance(30) { + None + } else { + Some(Status { + message: self.text(), + code: self.rng.below(5) as i32 - 1, + }) + }, + } + } + + fn traces(&mut self) -> Vec { + (0..self.count(3)) + .map(|_| ResourceSpans { + resource: self.resource(), + scope_spans: (0..self.count(3)) + .map(|_| ScopeSpans { + scope: self.scope(), + spans: (0..self.count(3)).map(|_| self.span()).collect(), + schema_url: self.schema_url(), + }) + .collect(), + schema_url: self.schema_url(), + }) + .collect() + } + + fn double(&mut self) -> f64 { + *self.rng.pick(&DOUBLES) + } + + fn option_double(&mut self) -> Option { + self.rng.chance(70).then(|| self.double()) + } + + fn exemplars(&mut self) -> Vec { + (0..self.count(3)) + .map(|_| Exemplar { + filtered_attributes: self.attributes_up_to(4, 2), + time_unix_nano: self.rng.timestamp(), + span_id: self.rng.id(), + trace_id: self.rng.id(), + value: match self.rng.below(3) { + 0 => None, + 1 => Some(exemplar::Value::AsInt(self.rng.next() as i64)), + _ => Some(exemplar::Value::AsDouble(self.double())), + }, + }) + .collect() + } + + fn number_points(&mut self) -> Vec { + (0..self.count(4)) + .map(|_| NumberDataPoint { + attributes: self.attributes(), + start_time_unix_nano: self.rng.timestamp(), + time_unix_nano: self.rng.timestamp(), + exemplars: self.exemplars(), + flags: self.rng.below(3) as u32, + value: match self.rng.below(3) { + 0 => None, + 1 => Some(number_data_point::Value::AsInt(self.rng.next() as i64)), + _ => Some(number_data_point::Value::AsDouble(self.double())), + }, + }) + .collect() + } + + fn counts(&mut self) -> Vec { + (0..self.count(5)) + .map(|_| self.rng.below(100) as u64) + .collect() + } + + fn metric(&mut self) -> Metric { + let temporality = self.rng.below(4) as i32; + let data = match self.rng.below(7) { + 0 => None, + 1 => Some(metric::Data::Gauge(Gauge { + data_points: self.number_points(), + })), + 2 => Some(metric::Data::Sum(Sum { + data_points: self.number_points(), + aggregation_temporality: temporality, + is_monotonic: self.rng.chance(50), + })), + 3 => Some(metric::Data::Histogram(Histogram { + data_points: (0..self.count(3)) + .map(|_| HistogramDataPoint { + attributes: self.attributes(), + start_time_unix_nano: self.rng.timestamp(), + time_unix_nano: self.rng.timestamp(), + count: self.rng.below(1000) as u64, + sum: self.option_double(), + bucket_counts: self.counts(), + explicit_bounds: (0..self.count(4)).map(|_| self.double()).collect(), + exemplars: self.exemplars(), + flags: self.rng.below(3) as u32, + min: self.option_double(), + max: self.option_double(), + }) + .collect(), + aggregation_temporality: temporality, + })), + 4 => Some(metric::Data::ExponentialHistogram(ExponentialHistogram { + data_points: (0..self.count(3)) + .map(|_| ExponentialHistogramDataPoint { + attributes: self.attributes(), + start_time_unix_nano: self.rng.timestamp(), + time_unix_nano: self.rng.timestamp(), + count: self.rng.below(1000) as u64, + sum: self.option_double(), + scale: self.rng.below(20) as i32 - 10, + zero_count: self.rng.below(10) as u64, + positive: self.rng.chance(70).then(|| { + exponential_histogram_data_point::Buckets { + offset: self.rng.below(10) as i32 - 5, + bucket_counts: self.counts(), + } + }), + negative: self.rng.chance(50).then(|| { + exponential_histogram_data_point::Buckets { + offset: self.rng.below(10) as i32 - 5, + bucket_counts: self.counts(), + } + }), + flags: self.rng.below(3) as u32, + exemplars: self.exemplars(), + min: self.option_double(), + max: self.option_double(), + zero_threshold: self.double(), + }) + .collect(), + aggregation_temporality: temporality, + })), + 5 => Some(metric::Data::Summary(Summary { + data_points: (0..self.count(3)) + .map(|_| SummaryDataPoint { + attributes: self.attributes(), + start_time_unix_nano: self.rng.timestamp(), + time_unix_nano: self.rng.timestamp(), + count: self.rng.below(1000) as u64, + sum: self.double(), + quantile_values: (0..self.count(4)) + .map(|_| summary_data_point::ValueAtQuantile { + quantile: self.double(), + value: self.double(), + }) + .collect(), + flags: self.rng.below(3) as u32, + }) + .collect(), + })), + // Data with no data points + _ => Some(metric::Data::Gauge(Gauge { + data_points: Vec::new(), + })), + }; + Metric { + name: self.text(), + description: self.text(), + unit: self.text(), + metadata: self.attributes_up_to(4, 2), + data, + } + } + + fn metrics(&mut self) -> Vec { + (0..self.count(3)) + .map(|_| ResourceMetrics { + resource: self.resource(), + scope_metrics: (0..self.count(3)) + .map(|_| ScopeMetrics { + scope: self.scope(), + metrics: (0..self.count(4)).map(|_| self.metric()).collect(), + schema_url: self.schema_url(), + }) + .collect(), + schema_url: self.schema_url(), + }) + .collect() + } +} + +/// FNV-1a over everything written, independent of any crate's hasher +struct Digest { + hash: u64, + rows: usize, + bytes: usize, +} + +impl Digest { + fn new() -> Self { + Self { + hash: 0xcbf2_9ce4_8422_2325, + rows: 0, + bytes: 0, + } + } + + fn write(&mut self, bytes: &[u8]) { + for byte in bytes { + self.hash ^= u64::from(*byte); + self.hash = self.hash.wrapping_mul(0x0000_0100_0000_01b3); + } + self.bytes += bytes.len(); + } + + /// The rows of one request in order, each with its keys in order, or the + /// error that stopped it + fn request(&mut self, rows: &[Value], result: Result<(), E>) { + for row in rows { + self.write(&serde_json::to_vec(row).unwrap()); + self.write(b"\n"); + self.rows += 1; + } + if let Err(error) = result { + self.write(format!("error: {error}\n").as_bytes()); + } + self.write(b"--\n"); + } +} + +fn settings() -> (u64, usize, bool) { + let seed = std::env::var("DST_SEED").ok().map(|seed| { + let seed = seed.trim(); + seed.strip_prefix("0x") + .map_or_else(|| seed.parse(), |hex| u64::from_str_radix(hex, 16)) + .expect("DST_SEED is a number") + }); + let iters = std::env::var("DST_ITERS") + .ok() + .map(|iters| iters.parse().expect("DST_ITERS is a number")); + let pinned = seed.is_none_or(|seed| seed == DEFAULT_SEED) + && iters.is_none_or(|iters| iters == DEFAULT_ITERS); + ( + seed.unwrap_or(DEFAULT_SEED), + iters.unwrap_or(DEFAULT_ITERS), + pinned, + ) +} + +/// Runs `signal` over the corpus and checks its digest against `expected` (rows, +/// bytes, digest) when the default seed and count are used +fn check( + signal: &str, + salt: u64, + expected: (usize, usize, u64), + mut run: impl FnMut(&mut Gen, &mut Digest), +) { + let (seed, iters, pinned) = settings(); + let mut generator = Gen { + rng: Rng(seed ^ salt), + keys: key_pool(), + }; + let mut digest = Digest::new(); + for _ in 0..iters { + run(&mut generator, &mut digest); + } + println!( + "CORPUS {signal}: seed {seed:#x}, {iters} requests, {} rows, {} bytes, digest {:016x}", + digest.rows, digest.bytes, digest.hash + ); + if pinned { + assert_eq!( + (digest.rows, digest.bytes, digest.hash), + expected, + "rows of the {signal} corpus changed (seed {seed:#x})" + ); + } +} + +#[test] +fn seeded_corpus_log_rows_are_stable() { + check( + "logs", + 1, + (13_819, 8_786_447, 0x5247_f2af_863c_6427), + |generator, digest| { + let request = generator.logs(); + let mut rows = Vec::new(); + let result = super::logs::flatten_logs_into( + &request, + &mut FlattenBudget::new(FlattenLimits::DEFAULT), + &mut rows, + ); + digest.request(&rows, result); + }, + ); +} + +#[test] +fn seeded_corpus_metric_rows_are_stable() { + check( + "metrics", + 2, + (42_718, 40_623_570, 0xb299_fcc3_bdad_0047), + |generator, digest| { + let request = generator.metrics(); + // Both exemplar modes over the same request + for flatten_exemplars in [false, true] { + let mut rows = Vec::new(); + let result = + super::metrics::flatten_metrics_into(&request, flatten_exemplars, &mut rows); + digest.request(&rows, result); + } + }, + ); +} + +#[test] +fn seeded_corpus_trace_rows_are_stable() { + check( + "traces", + 3, + (65_400, 83_307_143, 0x2f81_3bb5_32c5_11a5), + |generator, digest| { + let request = generator.traces(); + let mut rows = Vec::new(); + let result = super::traces::flatten_traces_into(&request, &mut rows); + digest.request(&rows, result); + }, + ); +} diff --git a/src/otel/decoded_size.rs b/src/otel/decoded_size.rs new file mode 100644 index 000000000..ab3685307 --- /dev/null +++ b/src/otel/decoded_size.rs @@ -0,0 +1,809 @@ +/* + * Parseable Server (C) 2022 - 2025 Parseable, Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + */ + +//! The memory an OTLP export request takes once decoded, estimated before it is decoded. +//! +//! Decoding allocates far more than the body holds for small messages: an empty span is +//! two bytes of protobuf and a `Span` of a few hundred bytes, an empty attribute two bytes +//! and a `KeyValue` of 64. A body inside the payload limit could ask for gigabytes. The +//! estimate walks the body against the OTLP schema without allocating, adding up the heap +//! memory the decoded request holds: every `Vec` of messages or numbers, at the capacity +//! that pushing its elements one by one grows it to, as prost does, and every string and +//! bytes field, which prost allocates at its length but at least 8 bytes (a message field +//! held inline, not in a `Vec`, is part of its parent's struct). For a body as prost +//! encodes it, that is exactly what decoding retains, allocator overhead aside; while +//! decoding, a `Vec` that grows holds its old and new buffers at once for a moment. +//! +//! The same walk runs over the `Value` tree of an OTLP JSON body before it is mapped to +//! the typed messages, so both encodings of a request are refused alike. A JSON body has +//! already been parsed by then; the walk bounds the typed copy made from it. It counts +//! the text of a hex or base64 field, more than the bytes it decodes to. + +use std::mem::size_of; +use std::sync::LazyLock; + +use opentelemetry_proto::tonic::common::v1::{AnyValue, EntityRef, KeyValue}; +use opentelemetry_proto::tonic::logs::v1::{LogRecord, ResourceLogs, ScopeLogs}; +use opentelemetry_proto::tonic::metrics::v1::{ + Exemplar, ExponentialHistogramDataPoint, HistogramDataPoint, Metric, NumberDataPoint, + ResourceMetrics, ScopeMetrics, SummaryDataPoint, summary_data_point::ValueAtQuantile, +}; +use opentelemetry_proto::tonic::trace::v1::{ + ResourceSpans, ScopeSpans, Span, + span::{Event, Link}, +}; + +/// The leaf records the request is decoded one at a time in (see `protobuf_stream`) +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Leaf { + LogRecord, + Span, + Metric, +} + +/// Estimated bytes one leaf record takes once prost decodes `body` (its encoding, +/// without a length prefix) on its own: its struct and everything its fields allocate. +/// For a record prost encoded this equals what decoding retains; a record that repeats +/// a singular message field can retain up to twice its estimate (prost merges the +/// occurrences into one `Vec` that grows past the sum of their capacities). A record +/// whose framing breaks is counted up to the break, where decoding it fails too. +pub fn leaf_decoded_size(body: &[u8], leaf: Leaf) -> usize { + let msg = match leaf { + Leaf::LogRecord => Msg::LogRecord, + Leaf::Span => Msg::Span, + Leaf::Metric => Msg::Metric, + }; + let mut size = leaf_struct_size(leaf); + // A leaf is three messages deep in its request + let _ = scan(body, msg, 3, &mut size); + size +} + +/// Most estimated bytes ([`leaf_decoded_size`]) one wire byte of a `leaf` record adds +/// beyond the record's own struct: `leaf_decoded_size(body, leaf) <= size_of the leaf +/// + bytes_per_wire_byte(leaf) * body.len()` for every `body`, valid or not. +/// +/// The bound is `B = max(8, 2 * S)`, where `S` is the largest element of a repeated +/// field reachable from the leaf. By induction over the messages of a body, each +/// message adds at most `B` times its own encoded length: +/// - a nested message adds what its fields add (its own struct is counted by the +/// `Vec` that holds it, or is part of its parent's struct); +/// - a string or bytes field of `L > 0` bytes adds `max(8, L) <= 8 * L`, and is +/// `L` bytes of content plus at least 2 of key and length; +/// - a repeated field of `n` elements adds a `Vec` of at most `max(4, n.next_power_of_two()) +/// <= 2 * n + 2` elements of `S` bytes, while each element takes at least 2 wire +/// bytes besides its content (a key and a length, or a key and a 1-byte varint; +/// a packed run of `n` numbers takes `n + 2`): `(2n + 2) * S <= 2 * S * 2n`. +/// +/// So a record can come close to `S` bytes per wire byte (many empty elements of the +/// largest kind, 2 bytes each) and reach `2 * S` (one empty element alone in its +/// `Vec`, which holds 4); `bound_holds_for_crafted_and_random_records` checks it. +pub fn bytes_per_wire_byte(leaf: Leaf) -> usize { + static BOUNDS: LazyLock<[usize; 3]> = LazyLock::new(|| { + [ + reachable_bound(Msg::LogRecord), + reachable_bound(Msg::Span), + reachable_bound(Msg::Metric), + ] + }); + BOUNDS[leaf as usize] +} + +/// Bytes of the struct of a `leaf` record +pub fn leaf_struct_size(leaf: Leaf) -> usize { + match leaf { + Leaf::LogRecord => size_of::(), + Leaf::Span => size_of::(), + Leaf::Metric => size_of::(), + } +} + +/// Whether a `leaf` record of `len` wire bytes can take more than `limit` bytes once +/// decoded ([`leaf_decoded_size`]); one that can not needs no measuring +#[inline] +pub fn needs_measuring(len: usize, leaf: Leaf, limit: usize) -> bool { + leaf_struct_size(leaf).saturating_add(bytes_per_wire_byte(leaf).saturating_mul(len)) > limit +} + +/// Field numbers of the OTLP schema are all below this +const MAX_FIELD_NUMBER: u64 = 32; + +/// `max(8, 2 * S)` over the repeated fields of the messages reachable from `root`, +/// see [`bytes_per_wire_byte`] +fn reachable_bound(root: Msg) -> usize { + let mut bound = 8; + let mut seen = vec![root]; + let mut stack = vec![root]; + while let Some(msg) = stack.pop() { + for number in 1..MAX_FIELD_NUMBER { + let Some(Field { kind, slot }) = msg.field(number) else { + continue; + }; + if slot.is_some() { + bound = bound.max(2 * kind.element_size()); + } + if let Kind::Message(child) = kind + && !seen.contains(&child) + { + seen.push(child); + stack.push(child); + } + } + } + bound +} + +/// Data points the metric `body` (its encoding, without a length prefix) decodes to: +/// the elements of the `data_points` field of its `data`, which prost merges when the +/// same kind of data occurs again and replaces when another kind follows. Read from +/// the wire, without decoding the metric. A metric whose framing breaks is counted up +/// to the break. +pub fn metric_points(mut body: &[u8]) -> u64 { + let (mut kind, mut points) = (0, 0); + while !body.is_empty() { + let Ok((number, wire)) = key(&mut body) else { + break; + }; + // `gauge`, `sum`, `histogram`, `exponential_histogram`, `summary` + if matches!(number, 5 | 7 | 9 | 10 | 11) && wire == LEN { + let Ok(data) = varint(&mut body).and_then(|len| take(&mut body, len)) else { + break; + }; + let found = data_points(data); + if number == kind { + points += found; + } else { + (kind, points) = (number, found); + } + } else if skip(&mut body, wire, number, 0).is_err() { + break; + } + } + points +} + +/// Elements of field 1 (`data_points`) of the `data` of a metric, up to a break +fn data_points(mut body: &[u8]) -> u64 { + let mut points = 0; + while !body.is_empty() { + let Ok((number, wire)) = key(&mut body) else { + break; + }; + if skip(&mut body, wire, number, 0).is_err() { + break; + } + if number == 1 && wire == LEN { + points += 1; + } + } + points +} + +/// Messages of the OTLP schema whose fields allocate when decoded. Leaf records are +/// sized on their own (`leaf_decoded_size`); the levels above them are walked by +/// prost in `protobuf_stream`, so their variants are only reached from each other. +#[allow(dead_code)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Msg { + LogsRequest, + ResourceLogs, + ScopeLogs, + LogRecord, + TracesRequest, + ResourceSpans, + ScopeSpans, + Span, + Event, + Link, + Status, + MetricsRequest, + ResourceMetrics, + ScopeMetrics, + Metric, + /// `Gauge`, `Sum`: their data points + NumberPoints, + Histogram, + ExponentialHistogram, + Summary, + NumberDataPoint, + HistogramDataPoint, + ExponentialHistogramDataPoint, + Buckets, + SummaryDataPoint, + ValueAtQuantile, + Exemplar, + Resource, + EntityRef, + Scope, + KeyValue, + AnyValue, + /// `ArrayValue`, `KeyValueList`: their values + ArrayValue, + KeyValueList, +} + +/// What a field allocates when decoded +#[derive(Debug, Clone, Copy)] +enum Kind { + /// A message: its struct if it is held in a `Vec`, and what its fields allocate + Message(Msg), + /// A string or bytes: its bytes, and a `String` if it is held in a `Vec` + Bytes, + /// A repeated 8-byte number, a `u64` or `f64` slot each + Numbers(Encoding), +} + +/// Wire encoding of the elements of a repeated number field +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Encoding { + Varint, + Fixed64, +} + +#[derive(Debug, Clone, Copy)] +struct Field { + kind: Kind, + /// For a repeated field, which of the `SLOTS` counters of its message counts its + /// elements; every repeated field of a message has its own + slot: Option, +} + +/// Repeated fields a message has at most (`HistogramDataPoint` has 4) +const SLOTS: usize = 4; + +const fn one(kind: Kind) -> Option { + Some(Field { kind, slot: None }) +} + +const fn many(slot: usize, kind: Kind) -> Option { + Some(Field { + kind, + slot: Some(slot), + }) +} + +impl Kind { + /// Bytes of one element of a `Vec` of this kind + fn element_size(self) -> usize { + match self { + Self::Message(msg) => msg.size(), + Self::Bytes => size_of::(), + Self::Numbers(_) => size_of::(), + } + } +} + +/// Bytes a `Vec` of `len` elements of `element_size` bytes holds once they were pushed one +/// by one: the standard library starts at 4 elements (8 for 1-byte elements, 1 for +/// elements over 1 KiB) and doubles +fn vec_capacity_bytes(len: usize, element_size: usize) -> usize { + if len == 0 || element_size == 0 { + return 0; + } + let first = match element_size { + 1 => 8, + 2..=1024 => 4, + _ => 1, + }; + len.checked_next_power_of_two() + .unwrap_or(usize::MAX) + .max(first) + .saturating_mul(element_size) +} + +/// Bytes prost allocates for a string or bytes field of `len` bytes +fn bytes_capacity(len: usize) -> usize { + // `vec_capacity_bytes(len.min(1), 1).max(len)`: 8 bytes at least, once there is one + if len == 0 { 0 } else { len.max(8) } +} + +/// Counts the elements of the repeated fields of one message, and adds the `Vec`s that +/// hold them once the message is done +#[derive(Default)] +struct Vecs { + lens: [usize; SLOTS], + element_sizes: [usize; SLOTS], + /// Whether any slot was pushed to; most messages have no repeated field + used: bool, +} + +impl Vecs { + fn push(&mut self, slot: usize, kind: Kind, elements: usize) { + self.lens[slot] = self.lens[slot].saturating_add(elements); + self.element_sizes[slot] = kind.element_size(); + self.used = true; + } + + fn add_to(&self, size: &mut usize) { + if !self.used { + return; + } + for (&len, &element_size) in self.lens.iter().zip(&self.element_sizes) { + add(size, vec_capacity_bytes(len, element_size)); + } + } +} + +use Kind::{Bytes, Message as M, Numbers}; + +impl Msg { + /// Bytes of the struct a message held in a `Vec` adds + fn size(self) -> usize { + match self { + Self::LogsRequest | Self::TracesRequest | Self::MetricsRequest => 0, + Self::ResourceLogs => size_of::(), + Self::ScopeLogs => size_of::(), + Self::LogRecord => size_of::(), + Self::ResourceSpans => size_of::(), + Self::ScopeSpans => size_of::(), + Self::Span => size_of::(), + Self::Event => size_of::(), + Self::Link => size_of::(), + Self::ResourceMetrics => size_of::(), + Self::ScopeMetrics => size_of::(), + Self::Metric => size_of::(), + Self::NumberDataPoint => size_of::(), + Self::HistogramDataPoint => size_of::(), + Self::ExponentialHistogramDataPoint => size_of::(), + Self::SummaryDataPoint => size_of::(), + Self::ValueAtQuantile => size_of::(), + Self::Exemplar => size_of::(), + Self::EntityRef => size_of::(), + Self::KeyValue => size_of::(), + Self::AnyValue => size_of::(), + // Only ever held inline in their parent + Self::Status + | Self::NumberPoints + | Self::Histogram + | Self::ExponentialHistogram + | Self::Summary + | Self::Buckets + | Self::Resource + | Self::Scope + | Self::ArrayValue + | Self::KeyValueList => 0, + } + } + + /// The field with protobuf field number `number`, `None` for a field that allocates + /// nothing (a number, a bool, an enum) or that the schema does not have + fn field(self, number: u64) -> Option { + match (self, number) { + (Self::LogsRequest, 1) => many(0, M(Self::ResourceLogs)), + (Self::ResourceLogs, 1) => one(M(Self::Resource)), + (Self::ResourceLogs, 2) => many(0, M(Self::ScopeLogs)), + (Self::ScopeLogs, 1) => one(M(Self::Scope)), + (Self::ScopeLogs, 2) => many(0, M(Self::LogRecord)), + (Self::LogRecord, 3 | 9 | 10 | 12) => one(Bytes), + (Self::LogRecord, 5) => one(M(Self::AnyValue)), + (Self::LogRecord, 6) => many(0, M(Self::KeyValue)), + + (Self::TracesRequest, 1) => many(0, M(Self::ResourceSpans)), + (Self::ResourceSpans, 1) => one(M(Self::Resource)), + (Self::ResourceSpans, 2) => many(0, M(Self::ScopeSpans)), + (Self::ScopeSpans, 1) => one(M(Self::Scope)), + (Self::ScopeSpans, 2) => many(0, M(Self::Span)), + (Self::Span, 1..=5) => one(Bytes), + (Self::Span, 9) => many(0, M(Self::KeyValue)), + (Self::Span, 11) => many(1, M(Self::Event)), + (Self::Span, 13) => many(2, M(Self::Link)), + (Self::Span, 15) => one(M(Self::Status)), + (Self::Event, 2) => one(Bytes), + (Self::Event, 3) => many(0, M(Self::KeyValue)), + (Self::Link, 1..=3) => one(Bytes), + (Self::Link, 4) => many(0, M(Self::KeyValue)), + (Self::Status, 2) => one(Bytes), + + (Self::MetricsRequest, 1) => many(0, M(Self::ResourceMetrics)), + (Self::ResourceMetrics, 1) => one(M(Self::Resource)), + (Self::ResourceMetrics, 2) => many(0, M(Self::ScopeMetrics)), + (Self::ScopeMetrics, 1) => one(M(Self::Scope)), + (Self::ScopeMetrics, 2) => many(0, M(Self::Metric)), + (Self::Metric, 1..=3) => one(Bytes), + (Self::Metric, 5 | 7) => one(M(Self::NumberPoints)), + (Self::Metric, 9) => one(M(Self::Histogram)), + (Self::Metric, 10) => one(M(Self::ExponentialHistogram)), + (Self::Metric, 11) => one(M(Self::Summary)), + (Self::Metric, 12) => many(0, M(Self::KeyValue)), + (Self::NumberPoints, 1) => many(0, M(Self::NumberDataPoint)), + (Self::Histogram, 1) => many(0, M(Self::HistogramDataPoint)), + (Self::ExponentialHistogram, 1) => many(0, M(Self::ExponentialHistogramDataPoint)), + (Self::Summary, 1) => many(0, M(Self::SummaryDataPoint)), + (Self::NumberDataPoint, 7) => many(0, M(Self::KeyValue)), + (Self::NumberDataPoint, 5) => many(1, M(Self::Exemplar)), + (Self::HistogramDataPoint, 9) => many(0, M(Self::KeyValue)), + (Self::HistogramDataPoint, 6) => many(1, Numbers(Encoding::Fixed64)), + (Self::HistogramDataPoint, 7) => many(2, Numbers(Encoding::Fixed64)), + (Self::HistogramDataPoint, 8) => many(3, M(Self::Exemplar)), + (Self::ExponentialHistogramDataPoint, 1) => many(0, M(Self::KeyValue)), + (Self::ExponentialHistogramDataPoint, 8 | 9) => one(M(Self::Buckets)), + (Self::ExponentialHistogramDataPoint, 11) => many(1, M(Self::Exemplar)), + (Self::Buckets, 2) => many(0, Numbers(Encoding::Varint)), + (Self::SummaryDataPoint, 7) => many(0, M(Self::KeyValue)), + (Self::SummaryDataPoint, 6) => many(1, M(Self::ValueAtQuantile)), + (Self::Exemplar, 7) => many(0, M(Self::KeyValue)), + (Self::Exemplar, 4 | 5) => one(Bytes), + + ( + Self::ResourceLogs + | Self::ScopeLogs + | Self::ResourceSpans + | Self::ScopeSpans + | Self::ResourceMetrics + | Self::ScopeMetrics, + 3, + ) => one(Bytes), + (Self::Resource, 1) => many(0, M(Self::KeyValue)), + (Self::Resource, 3) => many(1, M(Self::EntityRef)), + (Self::EntityRef, 1 | 2) => one(Bytes), + (Self::EntityRef, 3) => many(0, Bytes), + (Self::EntityRef, 4) => many(1, Bytes), + (Self::Scope, 1 | 2) => one(Bytes), + (Self::Scope, 3) => many(0, M(Self::KeyValue)), + (Self::KeyValue, 1) => one(Bytes), + (Self::KeyValue, 2) => one(M(Self::AnyValue)), + (Self::AnyValue, 1 | 7) => one(Bytes), + (Self::AnyValue, 5) => one(M(Self::ArrayValue)), + (Self::AnyValue, 6) => one(M(Self::KeyValueList)), + (Self::ArrayValue, 1) => many(0, M(Self::AnyValue)), + (Self::KeyValueList, 1) => many(0, M(Self::KeyValue)), + _ => None, + } + } +} + +/// Deeper than prost decodes: a body nested this deep fails to decode before reaching it +const MAX_DEPTH: u32 = 128; + +/// The framing of the body is broken, or nested deeper than decoding allows +struct Malformed; + +fn varint(buf: &mut &[u8]) -> Result { + // Keys, lengths and small numbers take one byte + if let Some((&byte, rest)) = buf.split_first() + && byte < 0x80 + { + *buf = rest; + return Ok(u64::from(byte)); + } + let mut value = 0u64; + for (index, &byte) in buf.iter().enumerate().take(10) { + value |= u64::from(byte & 0x7f) << (7 * index); + if byte < 0x80 { + *buf = &buf[index + 1..]; + return Ok(value); + } + } + Err(Malformed) +} + +fn take<'a>(buf: &mut &'a [u8], len: u64) -> Result<&'a [u8], Malformed> { + let len = usize::try_from(len).map_err(|_| Malformed)?; + if len > buf.len() { + return Err(Malformed); + } + let (taken, rest) = buf.split_at(len); + *buf = rest; + Ok(taken) +} + +const VARINT: u64 = 0; +const FIXED64: u64 = 1; +const LEN: u64 = 2; +const START_GROUP: u64 = 3; +const END_GROUP: u64 = 4; +const FIXED32: u64 = 5; + +/// Skips a field of wire type `wire`, the way decoding skips a field it does not know +fn skip(buf: &mut &[u8], wire: u64, number: u64, depth: u32) -> Result<(), Malformed> { + match wire { + VARINT => varint(buf).map(drop), + FIXED64 => take(buf, 8).map(drop), + LEN => { + let len = varint(buf)?; + take(buf, len).map(drop) + } + FIXED32 => take(buf, 4).map(drop), + START_GROUP => { + if depth >= MAX_DEPTH { + return Err(Malformed); + } + loop { + let (inner, inner_wire) = key(buf)?; + if inner_wire == END_GROUP { + return if inner == number { + Ok(()) + } else { + Err(Malformed) + }; + } + skip(buf, inner_wire, inner, depth + 1)?; + } + } + _ => Err(Malformed), + } +} + +fn key(buf: &mut &[u8]) -> Result<(u64, u64), Malformed> { + let key = varint(buf)?; + if key > u64::from(u32::MAX) || key >> 3 == 0 { + return Err(Malformed); + } + Ok((key >> 3, key & 7)) +} + +fn add(size: &mut usize, bytes: usize) { + *size = size.saturating_add(bytes); +} + +/// Adds what decoding `buf` as a `msg` allocates to `size`, up to where its framing breaks +fn scan(mut buf: &[u8], msg: Msg, depth: u32, size: &mut usize) -> Result<(), Malformed> { + let mut vecs = Vecs::default(); + // The `Vec`s of a message cut short count too: decoding allocated them before failing + let result = scan_fields(&mut buf, msg, depth, size, &mut vecs); + vecs.add_to(size); + result +} + +fn scan_fields( + buf: &mut &[u8], + msg: Msg, + depth: u32, + size: &mut usize, + vecs: &mut Vecs, +) -> Result<(), Malformed> { + while !buf.is_empty() { + let (number, wire) = key(buf)?; + match (msg.field(number), wire) { + (Some(Field { kind, slot }), LEN) => { + let len = varint(buf)?; + let body = take(buf, len)?; + let elements = match kind { + Kind::Message(child) => { + if depth >= MAX_DEPTH { + return Err(Malformed); + } + scan(body, child, depth + 1, size)?; + 1 + } + Kind::Bytes => { + add(size, bytes_capacity(body.len())); + 1 + } + // Packed + Kind::Numbers(Encoding::Varint) => { + body.iter().filter(|&&byte| byte < 0x80).count() + } + Kind::Numbers(Encoding::Fixed64) => body.len() / size_of::(), + }; + if let Some(slot) = slot { + vecs.push(slot, kind, elements); + } + } + // One unpacked element + ( + Some(Field { + kind: kind @ Kind::Numbers(encoding), + slot: Some(slot), + }), + VARINT | FIXED64, + ) => { + skip(buf, wire, number, depth)?; + if (encoding == Encoding::Varint) == (wire == VARINT) { + vecs.push(slot, kind, 1); + } + } + // A field that allocates nothing, a field the schema does not have, or a field + // of the wrong wire type, which fails decoding + _ => skip(buf, wire, number, depth)?, + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use opentelemetry_proto::tonic::metrics::v1::{Gauge, Sum, metric}; + use prost::Message as _; + + fn put_varint(out: &mut Vec, mut value: u64) { + while value >= 0x80 { + out.push(value as u8 | 0x80); + value >>= 7; + } + out.push(value as u8); + } + + fn put_key(out: &mut Vec, number: u64, wire: u64) { + put_varint(out, (number << 3) | wire); + } + + fn len_field(number: u64, body: &[u8]) -> Vec { + let mut out = Vec::new(); + put_key(&mut out, number, LEN); + put_varint(&mut out, body.len() as u64); + out.extend_from_slice(body); + out + } + + /// The shortest path of field numbers from `root` to every message reachable from it + fn paths(root: Msg) -> Vec<(Msg, Vec)> { + let mut found = vec![(root, vec![])]; + let mut next = 0; + while next < found.len() { + let (msg, path) = found[next].clone(); + next += 1; + for number in 1..MAX_FIELD_NUMBER { + if let Some(Field { + kind: Kind::Message(child), + .. + }) = msg.field(number) + && !found.iter().any(|(seen, _)| *seen == child) + { + let mut path = path.clone(); + path.push(number); + found.push((child, path)); + } + } + } + found + } + + /// Records of `root` built to come close to the bound: for every repeated field + /// of every message reachable from it, `n` elements of the fewest wire bytes, + /// packed and unpacked, inside the shortest path to that message + fn crafted(root: Msg) -> Vec> { + let mut records = Vec::new(); + for (msg, path) in paths(root) { + for number in 1..MAX_FIELD_NUMBER { + let Some(Field { + kind, + slot: Some(_), + }) = msg.field(number) + else { + continue; + }; + for n in [1, 2, 3, 5, 9, 17, 33, 1025, 4097] { + let mut bodies = vec![Vec::new()]; + match kind { + Kind::Message(_) | Kind::Bytes => { + for _ in 0..n { + put_key(&mut bodies[0], number, LEN); + bodies[0].push(0); + } + } + Kind::Numbers(encoding) => { + let (wire, width) = match encoding { + Encoding::Varint => (VARINT, 1), + Encoding::Fixed64 => (FIXED64, 8), + }; + for _ in 0..n { + put_key(&mut bodies[0], number, wire); + bodies[0].extend(std::iter::repeat_n(0, width)); + } + bodies.push(len_field(number, &vec![0; n * width])); + } + } + for mut body in bodies { + for &field in path.iter().rev() { + body = len_field(field, &body); + } + records.push(body); + } + } + } + } + records + } + + #[test] + fn bound_holds_for_crafted_and_random_records() { + println!( + "STRUCTS KeyValue {} AnyValue {} Event {} Link {} NumberDataPoint {} HistogramDataPoint {} ExponentialHistogramDataPoint {} SummaryDataPoint {} ValueAtQuantile {} Exemplar {}", + size_of::(), + size_of::(), + size_of::(), + size_of::(), + size_of::(), + size_of::(), + size_of::(), + size_of::(), + size_of::(), + size_of::(), + ); + let cap = crate::otel::protobuf_stream::max_record_bytes(10 * 1024 * 1024); + for (leaf, root) in [ + (Leaf::LogRecord, Msg::LogRecord), + (Leaf::Span, Msg::Span), + (Leaf::Metric, Msg::Metric), + ] { + let bound = bytes_per_wire_byte(leaf); + let own = leaf_struct_size(leaf); + let mut worst: f64 = 0.0; + let records = crafted(root); + for record in &records { + let size = leaf_decoded_size(record, leaf); + assert!( + size <= own + bound * record.len(), + "{leaf:?}: {size} B from {} wire bytes", + record.len() + ); + worst = worst.max((size - own) as f64 / record.len() as f64); + } + let threshold = (0..).find(|&len| needs_measuring(len, leaf, cap)).unwrap(); + println!( + "BOUND {leaf:?}: {bound} decoded bytes per wire byte, struct {own} B, {} crafted records reach {worst:.1}; at the default cap ({cap} B) records from {threshold} wire bytes are measured", + records.len() + ); + // Close to tight: a record reaches at least half of it + assert!(worst >= bound as f64 / 2.0, "{leaf:?}: {worst} of {bound}"); + assert_eq!(threshold, (cap - own) / bound + 1); + } + } + + fn metric_with(data: metric::Data) -> Vec { + Metric { + name: "m".into(), + data: Some(data), + ..Default::default() + } + .encode_to_vec() + } + + fn gauge(points: usize) -> Vec { + metric_with(metric::Data::Gauge(Gauge { + data_points: vec![NumberDataPoint::default(); points], + })) + } + + fn sum(points: usize) -> Vec { + metric_with(metric::Data::Sum(Sum { + data_points: vec![NumberDataPoint::default(); points], + ..Default::default() + })) + } + + /// Concatenated encodings decode as one merged metric: the same kind of data + /// merges, another kind replaces it + #[test] + fn data_points_read_from_the_wire_match_decoding() { + let cases: Vec> = vec![ + gauge(3), + [gauge(3), gauge(4)].concat(), + [gauge(3), sum(2)].concat(), + [gauge(3), sum(2), gauge(4)].concat(), + [sum(5), sum(0), sum(1)].concat(), + [gauge(2), Metric::default().encode_to_vec()].concat(), + Metric::default().encode_to_vec(), + ]; + for body in cases { + let decoded = Metric::decode(body.as_slice()).unwrap(); + let points = match decoded.data { + Some(metric::Data::Gauge(g)) => g.data_points.len(), + Some(metric::Data::Sum(s)) => s.data_points.len(), + None => 0, + _ => unreachable!(), + }; + assert_eq!(metric_points(&body), points as u64); + } + // Cut short: counted up to the break + let body = gauge(5); + assert!(metric_points(&body[..body.len() - 1]) < 5); + } +} diff --git a/src/otel/logs.rs b/src/otel/logs.rs index ca3a98eb7..f001f3845 100644 --- a/src/otel/logs.rs +++ b/src/otel/logs.rs @@ -18,17 +18,20 @@ use super::otel_utils::attribute_capacity; use super::otel_utils::collect_json_from_values; use super::otel_utils::convert_epoch_nano_to_timestamp; -use super::otel_utils::insert_attributes; +use super::otel_utils::insert_attributes_fitted; +use super::sink::{CHUNK_LIMITS, RowSink, VALUE_BYTES, heap_bytes}; use crate::metrics::increment_logs_collected_by_date; use crate::utils::json::flatten::{ FlattenBudget, FlattenCost, JsonFlattenError, expand_generic_flattening, flatten_pipeline_cost, string_json_len, }; use opentelemetry_proto::tonic::collector::logs::v1::ExportLogsServiceRequest; +use opentelemetry_proto::tonic::common::v1::InstrumentationScope; use opentelemetry_proto::tonic::logs::v1::LogRecord; use opentelemetry_proto::tonic::logs::v1::LogsData; -use opentelemetry_proto::tonic::logs::v1::ScopeLogs; +use opentelemetry_proto::tonic::logs::v1::ResourceLogs; use opentelemetry_proto::tonic::logs::v1::SeverityNumber; +use opentelemetry_proto::tonic::resource::v1::Resource; use serde_json::Map; use serde_json::Value; @@ -115,20 +118,6 @@ fn severity_number_from_text(severity_text: &str) -> Option { } } -/// Add the normalized severity fields to the flattened JSON. -fn flatten_severity(severity_number: i32, severity_text: &str) -> Map { - let mut severity_json: Map = Map::new(); - severity_json.insert( - "severity_number".to_string(), - Value::Number(severity_number.into()), - ); - severity_json.insert( - "severity_text".to_string(), - Value::String(severity_text.to_string()), - ); - severity_json -} - /// Maps OTel severity_number (0–24) to a log category. /// See https://opentelemetry.io/docs/specs/otel/logs/data-model/#severity-fields fn category_from_severity(severity_number: i32) -> Option<&'static str> { @@ -171,6 +160,215 @@ fn category_from_body(body_str: &str) -> &'static str { .map_or("UNSPECIFIED", |(_, label)| *label) } +/// Most memory the JSON text bodies of one log record may be parsed into: one +/// chunk of rows. JSON text of typical logs parses into about 8 bytes per byte, +/// so a body of a MiB or two of such text is parsed. A body that would take more +/// is kept as its text, like text that is not JSON. +pub const MAX_PARSED_BODY_BYTES: usize = CHUNK_LIMITS.bytes; + +/// Most bytes one byte of JSON text parses into, at the peak of parsing it: each +/// level of arrays nested in arrays (`[` and `]`, two bytes) is a `Vec` of four +/// 72 byte `Value`s, which is the most any two bytes of text make (see +/// `json_object_text_bytes`) +const PARSED_BYTES_PER_TEXT_BYTE: usize = 2 * VALUE_BYTES; + +/// Parses every body that is the JSON text of an object, as the fields of the +/// record are extracted from those only. Bodies are measured before they are +/// parsed: a body whose text could parse into more than what is left of +/// `MAX_PARSED_BODY_BYTES` is first scanned without allocating, which finds its +/// type and the memory parsing it takes. A body that would take more than is left +/// is not parsed, and neither is text that is not an object: those are kept as +/// their text. +fn parse_json_object_bodies(body_json: &Map) -> Vec> { + let mut held = 0usize; + let mut parsed = Vec::with_capacity(body_json.len()); + for value in body_json.values() { + let Value::String(text) = value else { + parsed.push(None); + continue; + }; + let most = text.len().saturating_mul(PARSED_BYTES_PER_TEXT_BYTE); + if held.saturating_add(most) > MAX_PARSED_BODY_BYTES { + match json_object_text_bytes(text) { + Some(bytes) if held.saturating_add(bytes) <= MAX_PARSED_BODY_BYTES => { + held += bytes; + } + // Not the JSON text of an object, or too large to parse: kept as text + _ => { + parsed.push(None); + continue; + } + } + } else { + held += most; + } + parsed.push( + serde_json::from_str::(text) + .ok() + .filter(Value::is_object), + ); + } + parsed +} + +/// Size of one `serde_json::Map` entry (an `IndexMap` bucket): the hash, the key +/// and the value +const MAP_ENTRY_BYTES: usize = + std::mem::size_of::() + std::mem::size_of::() + VALUE_BYTES; + +/// Most memory `serde_json::from_str::(text)` holds at once while parsing +/// `text`, when it is the JSON text of an object, found without allocating; `None` +/// for any other text. +/// +/// Containers are counted at the capacity they grow to while their elements are +/// pushed one at a time: a `Vec` to at least 4 elements and then by doubling, a +/// map's hash table by doubling its buckets (3, 7, 14, 28... entries fit) and its +/// entries to what the table fits. The old block of the last growth is counted as +/// well, as a reallocation holds both. So is the scratch buffer strings with escapes +/// are unescaped into, at three times the longest string. Repeated keys are counted +/// as distinct ones. The most any two bytes of text make is one more level of +/// arrays nested in arrays: a `Vec` of four `Value`s, `2 * VALUE_BYTES` per byte, +/// which `PARSED_BYTES_PER_TEXT_BYTE` is. +fn json_object_text_bytes(text: &str) -> Option { + use serde::de::{Deserialize, Deserializer, MapAccess, SeqAccess, Visitor}; + + /// Heap bytes of one parsed value, whether it is an object, and the longest + /// string in it + struct Parsed { + bytes: usize, + object: bool, + longest: usize, + } + + impl Parsed { + fn scalar() -> Self { + Self { + bytes: 0, + object: false, + longest: 0, + } + } + } + + /// Bytes of a `Vec` of `len` values pushed one at a time, at the peak of its + /// last growth + fn vec_bytes(len: usize) -> usize { + if len == 0 { + return 0; + } + let capacity = len.next_power_of_two().max(4); + let previous = if len > 4 { capacity / 2 } else { 0 }; + heap_bytes(capacity.saturating_mul(VALUE_BYTES)) + .saturating_add(heap_bytes(previous.saturating_mul(VALUE_BYTES))) + } + + /// Bytes of a map of `len` entries inserted one at a time, at the peak of its + /// last growth: the hash table of `usize` indices (8 bytes and a control byte + /// per bucket, and one group of control bytes), and the entries, which grow to + /// what the table fits + fn map_bytes(len: usize) -> usize { + if len == 0 { + return 0; + } + let fits = |buckets: usize| { + if buckets < 8 { + buckets - 1 + } else { + buckets / 8 * 7 + } + }; + let mut buckets = 4usize; + while fits(buckets) < len { + buckets = buckets.saturating_mul(2); + } + let table = heap_bytes(buckets.saturating_mul(9).saturating_add(16)); + let entries = heap_bytes(fits(buckets).saturating_mul(MAP_ENTRY_BYTES)); + let previous = if buckets > 4 { + heap_bytes(fits(buckets / 2).saturating_mul(MAP_ENTRY_BYTES)) + } else { + 0 + }; + table.saturating_add(entries).saturating_add(previous) + } + + impl<'de> Deserialize<'de> for Parsed { + fn deserialize>(deserializer: D) -> Result { + deserializer.deserialize_any(ParsedVisitor) + } + } + + struct ParsedVisitor; + + impl<'de> Visitor<'de> for ParsedVisitor { + type Value = Parsed; + + fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { + formatter.write_str("any JSON value") + } + fn visit_bool(self, _: bool) -> Result { + Ok(Parsed::scalar()) + } + fn visit_i64(self, _: i64) -> Result { + Ok(Parsed::scalar()) + } + fn visit_u64(self, _: u64) -> Result { + Ok(Parsed::scalar()) + } + fn visit_f64(self, _: f64) -> Result { + Ok(Parsed::scalar()) + } + fn visit_unit(self) -> Result { + Ok(Parsed::scalar()) + } + fn visit_str(self, s: &str) -> Result { + Ok(Parsed { + bytes: heap_bytes(s.len()), + object: false, + longest: s.len(), + }) + } + fn visit_seq>(self, mut seq: A) -> Result { + let mut len = 0usize; + let mut bytes = 0usize; + let mut longest = 0usize; + while let Some(element) = seq.next_element::()? { + len += 1; + bytes = bytes.saturating_add(element.bytes); + longest = longest.max(element.longest); + } + Ok(Parsed { + bytes: bytes.saturating_add(vec_bytes(len)), + object: false, + longest, + }) + } + fn visit_map>(self, mut map: A) -> Result { + let mut len = 0usize; + let mut bytes = 0usize; + let mut longest = 0usize; + while let Some(key) = map.next_key::()? { + let value = map.next_value::()?; + len += 1; + bytes = bytes.saturating_add(key.bytes).saturating_add(value.bytes); + longest = longest.max(key.longest).max(value.longest); + } + Ok(Parsed { + bytes: bytes.saturating_add(map_bytes(len)), + object: true, + longest, + }) + } + } + + let mut deserializer = serde_json::Deserializer::from_str(text); + let parsed = Parsed::deserialize(&mut deserializer).ok()?; + deserializer.end().ok()?; + let scratch = heap_bytes(parsed.longest.saturating_mul(3)); + parsed + .object + .then_some(parsed.bytes.saturating_add(scratch)) +} + /// this function flattens the `LogRecord` object /// and returns a `Map` of the flattened json /// this function is called recursively for each log record object in the otel logs @@ -181,8 +379,23 @@ pub fn flatten_log_record( ) -> Result, JsonFlattenError> { // Fixed fields plus the record attributes; body fields can add more, but // one growth is cheaper than the four an empty map needs for these - let mut log_record_json: Map = - Map::with_capacity(16 + attribute_capacity(&log_record.attributes)); + let capacity = 16 + attribute_capacity(&log_record.attributes); + let mut log_record_json: Map = Map::with_capacity(capacity); + flatten_log_record_into(log_record, budget, &mut log_record_json, capacity)?; + Ok(log_record_json) +} + +/// The fields of `flatten_log_record`, inserted into `log_record_json` (which is +/// a finished row when the record is one of a scope). `capacity` is the room the +/// map was created with, `attribute_capacity` of the record's attributes included: +/// what repeated attribute keys did not use is given back, because the map is +/// kept as the row. +fn flatten_log_record_into( + log_record: &LogRecord, + budget: &mut FlattenBudget, + log_record_json: &mut Map, + capacity: usize, +) -> Result<(), JsonFlattenError> { log_record_json.insert( "time_unix_nano".to_string(), Value::String(convert_epoch_nano_to_timestamp( @@ -198,7 +411,11 @@ pub fn flatten_log_record( let (severity_number, severity_text) = normalize_severity(log_record.severity_number, &log_record.severity_text); - log_record_json.extend(flatten_severity(severity_number, &severity_text)); + log_record_json.insert( + "severity_number".to_string(), + Value::Number(severity_number.into()), + ); + log_record_json.insert("severity_text".to_string(), Value::String(severity_text)); // Primary: derive category from the normalized severity_number let mut log_category = category_from_severity(severity_number); @@ -207,15 +424,7 @@ pub fn flatten_log_record( let body = &log_record.body; let body_json = collect_json_from_values(body, "body"); // Values that are strings which can be parsed as JSON objects get their fields extracted - let parsed_bodies: Vec> = body_json - .values() - .map(|value| match value { - Value::String(s) => serde_json::from_str::(s) - .ok() - .filter(Value::is_object), - _ => None, - }) - .collect(); + let parsed_bodies = parse_json_object_bodies(&body_json); // The rows of every parsed body are merged into this record, but they are all built // first, so charge all of them before building any let limits = budget.limits(); @@ -283,7 +492,7 @@ pub fn flatten_log_record( } } - insert_attributes(&mut log_record_json, &log_record.attributes); + insert_attributes_fitted(log_record_json, &log_record.attributes, capacity); // Insert after attributes so a client-sent "p_log_category" cannot override log_record_json.insert( @@ -308,29 +517,23 @@ pub fn flatten_log_record( Value::String(hex::encode(&log_record.trace_id)), ); - Ok(log_record_json) + Ok(()) } -/// this function flattens the `ScopeLogs` object -/// and returns a `Vec` of `Map` of the flattened json -fn flatten_scope_log( - scope_log: &ScopeLogs, - budget: &mut FlattenBudget, -) -> Result>, JsonFlattenError> { - let mut vec_scope_log_json = Vec::with_capacity(scope_log.log_records.len()); - let mut scope_log_json = Map::with_capacity( - 5 + scope_log - .scope - .as_ref() - .map_or(0, |scope| attribute_capacity(&scope.attributes)), - ); - if let Some(scope) = &scope_log.scope { +/// Fields every row of one `ScopeLogs` gets, before the record's own fields +pub fn scope_log_fields( + scope: Option<&InstrumentationScope>, + schema_url: &str, +) -> Map { + let capacity = 5 + scope.map_or(0, |scope| attribute_capacity(&scope.attributes)); + let mut scope_log_json = Map::with_capacity(capacity); + if let Some(scope) = scope { scope_log_json.insert("scope_name".to_string(), Value::String(scope.name.clone())); scope_log_json.insert( "scope_version".to_string(), Value::String(scope.version.clone()), ); - insert_attributes(&mut scope_log_json, &scope.attributes); + insert_attributes_fitted(&mut scope_log_json, &scope.attributes, capacity); scope_log_json.insert( "scope_dropped_attributes_count".to_string(), Value::Number(scope.dropped_attributes_count.into()), @@ -338,78 +541,91 @@ fn flatten_scope_log( } scope_log_json.insert( "scope_log_schema_url".to_string(), - Value::String(scope_log.schema_url.clone()), + Value::String(schema_url.to_string()), ); + scope_log_json +} - for log_record in &scope_log.log_records { - let log_record_json = flatten_log_record(log_record, budget)?; - let mut combined_json = scope_log_json.clone(); - combined_json.extend(log_record_json); - vec_scope_log_json.push(combined_json); +/// Fields every row of one `ResourceLogs` gets, after the record's own fields +pub fn resource_log_fields(resource: Option<&Resource>, schema_url: &str) -> Map { + let capacity = 4 + resource.map_or(0, |resource| attribute_capacity(&resource.attributes)); + let mut resource_log_json = Map::with_capacity(capacity); + if let Some(resource) = resource { + insert_attributes_fitted(&mut resource_log_json, &resource.attributes, capacity); + resource_log_json.insert( + "resource_dropped_attributes_count".to_string(), + Value::Number(resource.dropped_attributes_count.into()), + ); } - - Ok(vec_scope_log_json) + resource_log_json.insert( + "schema_url".to_string(), + Value::String(schema_url.to_string()), + ); + resource_log_json } -/// Common function to process resource logs and merge resource-level fields -fn process_resource_logs( - resource_logs: &[T], - get_resource: fn(&T) -> Option<&opentelemetry_proto::tonic::resource::v1::Resource>, - get_scope_logs: fn(&T) -> &[ScopeLogs], - get_schema_url: fn(&T) -> &str, - tenant_id: &str, +/// The row of one log record: the scope fields, the record's own fields over them, +/// then the resource fields over both +pub fn log_record_row( + log_record: &LogRecord, + scope_fields: &Map, + resource_fields: &Map, budget: &mut FlattenBudget, -) -> Result, JsonFlattenError> -where - T: std::fmt::Debug, -{ - let mut vec_otel_json = Vec::new(); - let mut logs_collected: u64 = 0; +) -> Result, JsonFlattenError> { + // Sized so that the record inserts and the resource merge below never have to + // grow the map: a growth rehashes every entry of the row. The record's own + // fields go straight into the row instead of a scratch map that is hashed a + // second time when it is merged. + let capacity = scope_fields.len() + + resource_fields.len() + + 16 + + attribute_capacity(&log_record.attributes); + let mut row = Map::with_capacity(capacity); + row.extend(scope_fields.iter().map(|(k, v)| (k.clone(), v.clone()))); + flatten_log_record_into(log_record, budget, &mut row, capacity)?; + row.extend(resource_fields.iter().map(|(k, v)| (k.clone(), v.clone()))); + Ok(row) +} +/// Hands the row of every log record of `resource_logs` to `sink`, one at a time. +/// The JSON bodies of every record are charged to `budget`, which all records of the +/// request share, before their rows are built. +pub fn flatten_logs_into( + resource_logs: &[ResourceLogs], + budget: &mut FlattenBudget, + sink: &mut S, +) -> Result<(), S::Error> { for resource_log in resource_logs { - let resource = get_resource(resource_log); - let mut resource_log_json = Map::with_capacity( - 4 + resource.map_or(0, |resource| attribute_capacity(&resource.attributes)), - ); - - // Process resource attributes if present - if let Some(resource) = resource { - insert_attributes(&mut resource_log_json, &resource.attributes); - resource_log_json.insert( - "resource_dropped_attributes_count".to_string(), - Value::Number(resource.dropped_attributes_count.into()), - ); - } - - let scope_logs = get_scope_logs(resource_log); - let mut vec_resource_logs_json = Vec::with_capacity( - scope_logs - .iter() - .map(|scope_log| scope_log.log_records.len()) - .sum(), - ); - - for scope_log in scope_logs { - vec_resource_logs_json.extend(flatten_scope_log(scope_log, budget)?); - logs_collected += scope_log.log_records.len() as u64; - } - - resource_log_json.insert( - "schema_url".to_string(), - Value::String(get_schema_url(resource_log).to_string()), - ); - - for mut resource_logs_json in vec_resource_logs_json { - resource_logs_json.extend(resource_log_json.clone()); - vec_otel_json.push(Value::Object(resource_logs_json)); + let resource_fields = + resource_log_fields(resource_log.resource.as_ref(), &resource_log.schema_url); + for scope_log in &resource_log.scope_logs { + let scope_fields = scope_log_fields(scope_log.scope.as_ref(), &scope_log.schema_url); + for log_record in &scope_log.log_records { + sink.row(log_record_row( + log_record, + &scope_fields, + &resource_fields, + budget, + )?)?; + sink.record_end(); + } } } + Ok(()) +} - // Only count the logs of a request that was converted in full +/// All rows of `resource_logs` at once. Counts the records for `tenant_id` once +/// every one was converted. Ingestion streams the rows instead, see `flatten_logs_into`. +fn collect_resource_logs( + resource_logs: &[ResourceLogs], + tenant_id: &str, + budget: &mut FlattenBudget, +) -> Result, JsonFlattenError> { + let mut rows = Vec::new(); + flatten_logs_into(resource_logs, budget, &mut rows)?; let date = chrono::Utc::now().date_naive().to_string(); - increment_logs_collected_by_date(logs_collected, &date, tenant_id); - - Ok(vec_otel_json) + increment_logs_collected_by_date(rows.len() as u64, &date, tenant_id); + Ok(rows) } /// Same as `flatten_otel_logs`, for the protobuf request @@ -418,14 +634,7 @@ pub fn flatten_otel_protobuf( tenant_id: &str, budget: &mut FlattenBudget, ) -> Result, JsonFlattenError> { - process_resource_logs( - &message.resource_logs, - |record| record.resource.as_ref(), - |record| &record.scope_logs, - |record| &record.schema_url, - tenant_id, - budget, - ) + collect_resource_logs(&message.resource_logs, tenant_id, budget) } /// this function performs the custom flattening of the otel logs @@ -438,14 +647,7 @@ pub fn flatten_otel_logs( tenant_id: &str, budget: &mut FlattenBudget, ) -> Result, JsonFlattenError> { - process_resource_logs( - &message.resource_logs, - |record| record.resource.as_ref(), - |record| &record.scope_logs, - |record| &record.schema_url, - tenant_id, - budget, - ) + collect_resource_logs(&message.resource_logs, tenant_id, budget) } #[cfg(test)] @@ -946,8 +1148,18 @@ mod tests { .map(|(field, value)| (format!("{key}_{field}"), value.clone())) .collect(), ); - crate::utils::json::flatten::flatten(&mut prefixed, "_", None, None, None, false) - .unwrap(); + crate::utils::json::flatten::flatten( + &mut prefixed, + "_", + None, + None, + None, + false, + &mut crate::utils::json::flatten::FlattenBudget::new( + crate::utils::json::flatten::GENEROUS_LIMITS, + ), + ) + .unwrap(); serde_json::to_vec(&prefixed).unwrap().len() }) .sum() @@ -990,12 +1202,146 @@ mod tests { ); } + const MIB: usize = 1024 * 1024; + + /// A JSON object of `fields` fields `"f0000000":0`, the reviewer's shape + fn many_fields(fields: usize) -> String { + let mut text = String::from("{"); + for i in 0..fields { + if i > 0 { + text.push(','); + } + text.push_str(&format!("\"f{i:07}\":0")); + } + text.push('}'); + text + } + + fn timed_record(body: String) -> LogRecord { + LogRecord { + time_unix_nano: 1_700_000_000_000_000_000, + observed_time_unix_nano: 1_700_000_000_000_000_000, + body: string_body(&body), + ..Default::default() + } + } + + /// Review findings 2 and 6: a JSON text body was parsed when its parse was + /// estimated under 64 MiB (a 3 MiB body of 241,980 fields was accepted and + /// peaked at 180 MiB), and a body estimated over it refused its record with + /// `LogBodyTooLarge` (450,000 fields, 5.6 MiB, which `b8c7d979` accepted). Now + /// at most one chunk's worth (16 MiB) of parsed memory is allowed, and a body + /// over it is kept as its text, as text that is not JSON is: never refused. + #[test] + fn json_text_body_over_one_chunk_of_parsed_memory_is_kept_as_text() { + let mut measured = Vec::new(); + for fields in [241_980usize, 400_000, 450_000] { + let text = many_fields(fields); + let record = timed_record(text.clone()); + let mut budget = FlattenBudget::new(FlattenLimits::DEFAULT); + let (flattened, allocated) = + crate::test_alloc::measure(|| flatten_log_record(&record, &mut budget)); + println!( + "REGRESSION JSON text body of {fields} fields: text {:.2} MiB, {}, peak {:.1} MiB", + text.len() as f64 / MIB as f64, + match &flattened { + Ok(row) => format!("{} fields", row.len()), + Err(e) => format!("refused: {e}"), + }, + allocated.peak as f64 / MIB as f64, + ); + measured.push((fields, text, flattened, allocated.peak)); + } + for (fields, text, flattened, peak) in measured { + let row = flattened.expect("the record is not refused"); + assert_eq!(row["body"], json!(text)); + assert!( + !row.keys().any(|key| key.starts_with("body_")), + "{fields} fields: the body was parsed" + ); + // Copies of the text: the body field, its copy in the row, and the + // text the category is looked for in (severity is unset) + assert!(peak < 5 * text.len() + MIB, "{fields} fields"); + } + // A body whose parse fits in one chunk is still parsed + let text = many_fields(40_000); + let row = flatten_log_record( + &timed_record(text), + &mut FlattenBudget::new(FlattenLimits::DEFAULT), + ) + .unwrap(); + assert_eq!(row["body_f0039999"], json!(0)); + } + + /// Review finding 6: the scan before parsing estimated under 64 MiB for an + /// object of 400,000 fields whose parse held 74.5 MiB. The estimate counts the + /// table and entries an `IndexMap` grows to, a `Vec` the capacity it doubles + /// to, and the old block of the last growth, which a reallocation holds too. + #[test] + fn parsed_body_estimate_covers_what_parsing_holds() { + let mut shapes: Vec<(String, String)> = + [1usize, 3, 4, 7, 8, 15, 100, 1000, 100_000, 400_000] + .into_iter() + .map(|n| (format!("object of {n} fields"), many_fields(n))) + .collect(); + for n in [1usize, 4, 5, 1000, 262_145] { + let numbers = vec!["0"; n].join(","); + shapes.push((format!("{n} numbers"), format!(r#"{{"a":[{numbers}]}}"#))); + let singles = vec!["[0]"; n].join(","); + shapes.push(( + format!("{n} one-number arrays"), + format!(r#"{{"a":[{singles}]}}"#), + )); + let objects = vec![r#"{"k":"v","n":1}"#; n].join(","); + shapes.push(( + format!("{n} small objects"), + format!(r#"{{"a":[{objects}]}}"#), + )); + } + for n in [1000usize, 1_000_000] { + // Escapes are unescaped into a scratch buffer while parsing + shapes.push(( + format!("escaped string of {n} bytes"), + format!(r#"{{"m":"{}"}}"#, "\\n".repeat(n)), + )); + } + shapes.push(( + "nested objects".into(), + format!("{}0{}", r#"{"a":"#.repeat(100), "}".repeat(100)), + )); + let mut under = Vec::new(); + for (name, text) in shapes { + let estimate = super::json_object_text_bytes(&text).expect("an object"); + let (parsed, allocated) = + crate::test_alloc::measure(|| serde_json::from_str::(&text)); + assert!(parsed.is_ok()); + drop(parsed); + let ratio = estimate as f64 / allocated.peak.max(1) as f64; + println!( + "REGRESSION parsed body estimate, {name}: text {} B, estimate {estimate} B, parse peak {} B, estimate/peak {ratio:.2}", + text.len(), + allocated.peak + ); + if estimate < allocated.peak { + under.push(name.clone()); + } + assert!( + (text.len() * super::PARSED_BYTES_PER_TEXT_BYTE) >= allocated.peak, + "{name}: over the quick bound per text byte" + ); + assert!( + (text.len() * super::PARSED_BYTES_PER_TEXT_BYTE) >= estimate, + "{name}: estimate over the quick bound per text byte" + ); + } + assert!(under.is_empty(), "estimated under the parse: {under:?}"); + } + // Release-profile micro-benchmarks. Run with a filter, for example: // cargo test --release --lib -- --ignored --exact otel::logs::tests::bench_flatten_otel_protobuf_logs --nocapture // They never touch the PARSEABLE global: every timestamp is set, so the rows // are deterministic, and the flatten budget is built from FlattenLimits::DEFAULT. mod benches { - use super::super::flatten_otel_protobuf; use crate::otel::bench; use crate::utils::json::flatten::{FlattenBudget, FlattenLimits}; use opentelemetry_proto::tonic::collector::logs::v1::ExportLogsServiceRequest; @@ -1142,10 +1488,13 @@ mod tests { ExportLogsServiceRequest { resource_logs } } + /// What ingestion does with a decoded request: its rows handed over in + /// chunks (collected here) fn flatten(request: &ExportLogsServiceRequest) -> Vec { let mut budget = FlattenBudget::new(FlattenLimits::DEFAULT); - flatten_otel_protobuf(request, "perfbench", &mut budget) - .expect("benchmark rows flatten") + bench::chunked(|chunker| { + super::super::flatten_logs_into(&request.resource_logs, &mut budget, chunker) + }) } #[test] diff --git a/src/otel/memory_tests.rs b/src/otel/memory_tests.rs new file mode 100644 index 000000000..f5dc92b73 --- /dev/null +++ b/src/otel/memory_tests.rs @@ -0,0 +1,676 @@ +/* + * Parseable Server (C) 2022 - 2025 Parseable, Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + */ + +//! Memory one OTLP request makes the server hold while its rows are built and +//! handed to staging, measured with the test allocator (`test_alloc`, layout +//! bytes on the calling thread). The decoded request is built before the +//! measurement starts. Each test prints `MEMORY : ...` with its numbers. +//! None of them touches `PARSEABLE`, so they may be run with a name filter. + +use crate::otel::sink::{CHUNK_LIMITS, Chunker, row_bytes}; +use crate::test_alloc::{Allocated, measure}; +use crate::utils::json::flatten::{FlattenBudget, FlattenLimits, JsonFlattenError}; +use opentelemetry_proto::tonic::collector::logs::v1::ExportLogsServiceRequest; +use opentelemetry_proto::tonic::collector::metrics::v1::ExportMetricsServiceRequest; +use opentelemetry_proto::tonic::collector::trace::v1::ExportTraceServiceRequest; +use opentelemetry_proto::tonic::common::v1::{AnyValue, KeyValue, any_value}; +use opentelemetry_proto::tonic::logs::v1::{LogRecord, ResourceLogs, ScopeLogs}; +use opentelemetry_proto::tonic::metrics::v1::{ + Exemplar, Gauge, Metric, NumberDataPoint, ResourceMetrics, ScopeMetrics, metric, +}; +use opentelemetry_proto::tonic::resource::v1::Resource; +use opentelemetry_proto::tonic::trace::v1::span::{Event, Link}; +use opentelemetry_proto::tonic::trace::v1::{ResourceSpans, ScopeSpans, Span}; +use serde_json::Value; + +const MIB: usize = 1024 * 1024; + +/// What a request may make the server hold while its rows are built and staged: +/// one chunk of rows (whose real size stays within 2x of its estimate), the row +/// that filled it and the chunk's `Vec`. It does not grow with the rows of the +/// request. +const PEAK_BOUND: usize = 2 * CHUNK_LIMITS.bytes + 8 * MIB; + +fn mb(bytes: impl TryInto) -> f64 { + bytes.try_into().ok().unwrap() as f64 / MIB as f64 +} + +fn kv(key: impl Into, value: any_value::Value) -> KeyValue { + KeyValue { + key: key.into(), + value: Some(AnyValue { value: Some(value) }), + ..Default::default() + } +} + +/// Takes a chunk of rows, as staging does +type Stage<'a> = dyn FnMut(Vec, usize) -> Result<(), JsonFlattenError> + 'a; + +/// Rows handed over, and the most rows a chunk held +#[derive(Debug, Default)] +struct Handed { + rows: usize, + largest_chunk: usize, +} + +/// Hands the rows of a request to a consumer that drops every chunk once it is +/// full, as staging does, and reports what that allocated +fn hand_over( + name: &str, + flatten: impl FnOnce(&mut Stage) -> Result<(), E>, +) -> (Result, Allocated) { + let (result, allocated) = measure(|| { + let mut handed = Handed::default(); + let mut stage = |rows: Vec, _bytes: usize| { + handed.rows += rows.len(); + handed.largest_chunk = handed.largest_chunk.max(rows.len()); + Ok(()) + }; + flatten(&mut stage).map_err(|e| format!("{e:?}"))?; + Ok(handed) + }); + println!( + "MEMORY {name}: {:?}, peak {:.1} MiB, bound {:.0} MiB", + result, + mb(allocated.peak), + mb(PEAK_BOUND) + ); + (result, allocated) +} + +fn traces( + request: &ExportTraceServiceRequest, +) -> impl FnOnce(&mut Stage) -> Result<(), JsonFlattenError> + '_ { + move |stage| { + let mut chunker = Chunker::new(CHUNK_LIMITS, stage); + crate::otel::traces::flatten_traces_into(&request.resource_spans, &mut chunker)?; + chunker.finish() + } +} + +fn metrics( + request: &ExportMetricsServiceRequest, +) -> impl FnOnce(&mut Stage) -> Result<(), JsonFlattenError> + '_ { + move |stage| { + let mut chunker = Chunker::new(CHUNK_LIMITS, stage); + crate::otel::metrics::flatten_metrics_into(&request.resource_metrics, false, &mut chunker)?; + chunker.finish() + } +} + +fn logs<'a>( + request: &'a ExportLogsServiceRequest, + budget: &'a mut FlattenBudget, +) -> impl FnOnce(&mut Stage) -> Result<(), JsonFlattenError> + 'a { + move |stage| { + let mut chunker = Chunker::new(CHUNK_LIMITS, stage); + crate::otel::logs::flatten_logs_into(&request.resource_logs, budget, &mut chunker)?; + chunker.finish() + } +} + +fn one_span(span: Span) -> ExportTraceServiceRequest { + ExportTraceServiceRequest { + resource_spans: vec![ResourceSpans { + scope_spans: vec![ScopeSpans { + spans: vec![span], + ..Default::default() + }], + ..Default::default() + }], + } +} + +fn one_metric(metric: Metric) -> ExportMetricsServiceRequest { + ExportMetricsServiceRequest { + resource_metrics: vec![ResourceMetrics { + scope_metrics: vec![ScopeMetrics { + metrics: vec![metric], + ..Default::default() + }], + ..Default::default() + }], + } +} + +/// Review finding 1: every event row of a span was built before the first was +/// handed over. 131,072 empty events (256 KiB of protobuf) held about 600 MiB. +#[test] +fn events_of_one_span_are_handed_over_in_bounded_memory() { + let n = 1 << 17; + let request = one_span(Span { + start_time_unix_nano: 1, + end_time_unix_nano: 2, + events: vec![ + Event { + time_unix_nano: 1, + ..Default::default() + }; + n + ], + ..Default::default() + }); + let (result, allocated) = hand_over("events of one span", traces(&request)); + let handed = result.unwrap(); + assert_eq!(handed.rows, n); + assert!(handed.largest_chunk < n); + assert!(allocated.peak < PEAK_BOUND, "peak {} B", allocated.peak); +} + +/// Same for the links of one span +#[test] +fn links_of_one_span_are_handed_over_in_bounded_memory() { + let n = 1 << 16; + let request = one_span(Span { + start_time_unix_nano: 1, + end_time_unix_nano: 2, + links: vec![Link::default(); n], + ..Default::default() + }); + let (result, allocated) = hand_over("links of one span", traces(&request)); + assert_eq!(result.unwrap().rows, n); + assert!(allocated.peak < PEAK_BOUND, "peak {} B", allocated.peak); +} + +/// Same for the data points of one gauge +#[test] +fn data_points_of_one_metric_are_handed_over_in_bounded_memory() { + let n = 1 << 17; + let request = one_metric(Metric { + name: "g".into(), + data: Some(metric::Data::Gauge(Gauge { + data_points: vec![ + NumberDataPoint { + time_unix_nano: 1, + start_time_unix_nano: 1, + ..Default::default() + }; + n + ], + })), + ..Default::default() + }); + let (result, allocated) = hand_over("points of one gauge", metrics(&request)); + assert_eq!(result.unwrap().rows, n); + assert!(allocated.peak < PEAK_BOUND, "peak {} B", allocated.peak); +} + +/// 1000 tiny resource attributes copied into every row of 2000 records: a 13 KB +/// body whose rows held about 400 MiB at once (review finding 3) +#[test] +fn tiny_copied_fields_are_handed_over_in_bounded_memory() { + let attributes: Vec = (0..1000) + .map(|i| kv(format!("k{i:03}"), any_value::Value::IntValue(0))) + .collect(); + let rows = 2000; + let request = ExportLogsServiceRequest { + resource_logs: vec![ResourceLogs { + resource: Some(Resource { + attributes, + ..Default::default() + }), + scope_logs: vec![ScopeLogs { + log_records: (0..rows) + .map(|i| LogRecord { + time_unix_nano: 1_700_000_000_000_000_000 + i as u64, + observed_time_unix_nano: 1_700_000_000_000_000_000, + ..Default::default() + }) + .collect(), + ..Default::default() + }], + ..Default::default() + }], + }; + let mut budget = FlattenBudget::new(FlattenLimits::DEFAULT); + let (result, allocated) = hand_over("tiny copied fields", logs(&request, &mut budget)); + assert_eq!(result.unwrap().rows, rows); + assert!(allocated.peak < PEAK_BOUND, "peak {} B", allocated.peak); +} + +/// Review finding 7: a log body that is JSON text was parsed before anything was +/// charged. A 10 MiB body `{"a":[0,0,...]}` peaked at 586 MiB. It would parse into +/// more than one chunk's worth of memory, so it is kept as its text. +#[test] +fn json_text_log_body_is_not_parsed_into_unbounded_memory() { + let mut text = String::with_capacity(10 * MIB); + text.push_str(r#"{"a":["#); + while text.len() < 10 * MIB - 4096 { + text.push_str("0,"); + } + text.push_str("0]}"); + let body_len = text.len(); + let request = ExportLogsServiceRequest { + resource_logs: vec![ResourceLogs { + scope_logs: vec![ScopeLogs { + log_records: vec![LogRecord { + time_unix_nano: 1_700_000_000_000_000_000, + observed_time_unix_nano: 1_700_000_000_000_000_000, + body: Some(AnyValue { + value: Some(any_value::Value::StringValue(text)), + }), + ..Default::default() + }], + ..Default::default() + }], + ..Default::default() + }], + }; + let mut budget = FlattenBudget::new(FlattenLimits::DEFAULT); + let (result, allocated) = hand_over("10 MiB JSON text body", logs(&request, &mut budget)); + assert_eq!( + result.unwrap().rows, + 1, + "the record is kept, its body as text" + ); + // The row holds copies of the body text, nothing parsed from it + assert!( + allocated.peak < PEAK_BOUND + 3 * body_len, + "peak {} B", + allocated.peak + ); +} + +/// Review finding 4: an array of objects with distinct keys becomes a column per +/// key with a cell for every object: 3,600 exemplars held 890 MiB once their row +/// was structurally flattened +#[test] +fn exemplar_column_tables_are_bounded() { + let exemplars: Vec = (0..3_600) + .map(|i| Exemplar { + filtered_attributes: vec![kv(format!("k{i}"), any_value::Value::IntValue(1))], + time_unix_nano: 1, + ..Default::default() + }) + .collect(); + let request = one_metric(Metric { + name: "g".into(), + data: Some(metric::Data::Gauge(Gauge { + data_points: vec![NumberDataPoint { + time_unix_nano: 1, + start_time_unix_nano: 1, + exemplars, + ..Default::default() + }], + })), + ..Default::default() + }); + let mut rows = Vec::new(); + crate::otel::metrics::flatten_metrics_into(&request.resource_metrics, false, &mut rows) + .unwrap(); + let mut row = rows.pop().unwrap(); + let estimate = row_bytes(row.as_object().unwrap()); + let mut budget = FlattenBudget::new(FlattenLimits::DEFAULT); + let (result, allocated) = measure(|| { + crate::utils::json::flatten::flatten(&mut row, "_", None, None, None, false, &mut budget) + }); + println!( + "MEMORY exemplar table: {:?}, estimate {:.1} MiB, peak {:.1} MiB", + result.as_ref().map_err(ToString::to_string), + mb(estimate), + mb(allocated.peak) + ); + // The chunk estimate counts the table, so such a row fills a chunk on its own + assert!(estimate > 3_600 * 3_600 * 72); + assert!(result.is_err()); + assert!(allocated.peak < PEAK_BOUND, "peak {} B", allocated.peak); +} + +/// `count` attributes without a value: two bytes each on the wire, skipped when rows +/// are built +fn valueless(count: usize) -> Vec { + vec![KeyValue::default(); count] +} + +const VALUELESS: usize = 50_000; + +/// Maps sized by the raw attribute count of the request held room for every +/// attribute without a value: 50,000 of them (100 KB of protobuf) made a row map +/// reserve about 5.5 MB +#[test] +fn valueless_attributes_do_not_size_row_maps() { + let point = NumberDataPoint { + attributes: valueless(VALUELESS), + time_unix_nano: 1, + start_time_unix_nano: 1, + exemplars: vec![Exemplar { + filtered_attributes: valueless(VALUELESS), + time_unix_nano: 1, + ..Default::default() + }], + ..Default::default() + }; + let metric = |data| Metric { + name: "m".into(), + metadata: valueless(VALUELESS), + data: Some(data), + ..Default::default() + }; + for (name, metric) in [ + ( + "gauge point", + metric(metric::Data::Gauge(Gauge { + data_points: vec![point.clone()], + })), + ), + ( + "metric without points", + metric(metric::Data::Gauge(Gauge::default())), + ), + ] { + let (rows, allocated) = + measure(|| crate::otel::metrics::flatten_metrics_record(&metric, false)); + println!( + "MEMORY valueless attributes, {name}: {} rows, retained {} B, peak {} B", + rows.len(), + allocated.retained, + allocated.peak + ); + assert_eq!(rows.len(), 1); + assert!( + allocated.peak < 256 * 1024, + "{name}: peak {} B", + allocated.peak + ); + } +} + +/// Same for the maps built while a row is: event and link attributes, and the +/// entries of key-value lists and arrays +#[test] +fn valueless_attributes_do_not_size_temporary_maps() { + let list = |values: Vec| { + vec![kv( + "list", + any_value::Value::KvlistValue(opentelemetry_proto::tonic::common::v1::KeyValueList { + values, + }), + )] + }; + let array = vec![kv( + "array", + any_value::Value::ArrayValue(opentelemetry_proto::tonic::common::v1::ArrayValue { + values: vec![AnyValue::default(); VALUELESS], + }), + )]; + let span = Span { + start_time_unix_nano: 1, + end_time_unix_nano: 2, + attributes: [list(valueless(VALUELESS)), array].concat(), + events: vec![Event { + time_unix_nano: 1, + attributes: valueless(VALUELESS), + ..Default::default() + }], + links: vec![Link { + attributes: valueless(VALUELESS), + ..Default::default() + }], + ..Default::default() + }; + let request = one_span(span); + let (rows, allocated) = measure(|| { + let mut rows = Vec::new(); + crate::otel::traces::flatten_traces_into(&request.resource_spans, &mut rows).unwrap(); + rows + }); + println!( + "MEMORY valueless attributes, span: {} rows, peak {} B", + rows.len(), + allocated.peak + ); + assert_eq!(rows.len(), 2); + // Converting an attribute clones its decoded value first: the 50,000 entries of + // the list and of the array, as decoded, are held once more + let clones = VALUELESS * (std::mem::size_of::() + std::mem::size_of::()); + assert!( + allocated.peak < clones + 256 * 1024, + "peak {} B, clones {clones} B", + allocated.peak + ); +} + +/// The chunk limit is an estimate of the memory rows hold (`row_bytes`); it must +/// track what they really allocate, for realistic rows and for rows of many tiny +/// fields alike (review finding 3: JSON length was 18.5x off) +#[test] +fn row_estimate_tracks_allocated_memory() { + use opentelemetry_proto::tonic::common::v1::InstrumentationScope; + + let realistic: Vec = [ + ("service.name", "checkout"), + ("service.namespace", "shop"), + ("service.instance.id", "checkout-7d9f8b6c4-x2x9q"), + ("k8s.namespace.name", "production"), + ("k8s.pod.name", "checkout-7d9f8b6c4-x2x9q"), + ("k8s.pod.uid", "6b1a3c1e-2f0e-4d5a-9a43-77b8c2d1e0f1"), + ("k8s.deployment.name", "checkout"), + ("k8s.node.name", "ip-10-0-12-34.ec2.internal"), + ("k8s.cluster.name", "prod-eu-west-1"), + ("host.name", "ip-10-0-12-34.ec2.internal"), + ("cloud.provider", "aws"), + ("cloud.region", "eu-west-1"), + ("container.name", "checkout"), + ("container.image.name", "registry.example.com/shop/checkout"), + ("container.image.tag", "1.42.3"), + ("telemetry.sdk.name", "opentelemetry"), + ("telemetry.sdk.language", "java"), + ("telemetry.sdk.version", "1.38.0"), + ] + .into_iter() + .map(|(k, v)| kv(k, any_value::Value::StringValue(v.into()))) + .collect(); + let tiny: Vec = (0..1000) + .map(|i| kv(format!("k{i:03}"), any_value::Value::IntValue(0))) + .collect(); + for (name, resource, record_attributes) in + [("realistic", realistic, 6), ("tiny fields", tiny, 0)] + { + let request = ExportLogsServiceRequest { + resource_logs: vec![ResourceLogs { + resource: Some(Resource { + attributes: resource, + ..Default::default() + }), + scope_logs: vec![ScopeLogs { + scope: Some(InstrumentationScope { + name: "io.opentelemetry.logback".into(), + version: "2.6.0".into(), + ..Default::default() + }), + log_records: (0..500u64) + .map(|i| LogRecord { + time_unix_nano: 1_700_000_000_000_000_000 + i, + observed_time_unix_nano: 1_700_000_000_000_000_000 + i, + severity_number: 9, + severity_text: "INFO".into(), + body: Some(AnyValue { + value: Some(any_value::Value::StringValue(format!( + "GET /api/v1/orders/{i} 200 in 12ms" + ))), + }), + attributes: (0..record_attributes) + .map(|a| { + kv(format!("attr.{a}"), any_value::Value::IntValue(i as i64)) + }) + .collect(), + trace_id: vec![7; 16], + span_id: vec![3; 8], + ..Default::default() + }) + .collect(), + ..Default::default() + }], + ..Default::default() + }], + }; + let (rows, allocated) = measure(|| { + let mut rows = Vec::new(); + crate::otel::logs::flatten_logs_into( + &request.resource_logs, + &mut FlattenBudget::new(FlattenLimits::DEFAULT), + &mut rows, + ) + .unwrap(); + rows + }); + let estimate: usize = rows + .iter() + .map(|row| row_bytes(row.as_object().unwrap())) + .sum(); + let ratio = allocated.retained as f64 / estimate as f64; + println!( + "MEMORY row estimate, {name}: {} rows, allocated {} B, estimated {} B, allocated/estimated {:.2}", + rows.len(), + allocated.retained, + estimate, + ratio, + ); + assert!((0.5..=2.0).contains(&ratio), "{name}: {ratio:.2}"); + } +} + +/// Resident and peak resident memory of this process in bytes, from +/// `/proc/self/statm` and `VmHWM` +#[cfg(target_os = "linux")] +fn resident() -> (usize, usize) { + let statm = std::fs::read_to_string("/proc/self/statm").unwrap(); + let pages: usize = statm.split_whitespace().nth(1).unwrap().parse().unwrap(); + let status = std::fs::read_to_string("/proc/self/status").unwrap(); + let hwm: usize = status + .lines() + .find_map(|line| line.strip_prefix("VmHWM:")) + .and_then(|kb| kb.trim().trim_end_matches(" kB").trim().parse().ok()) + .unwrap(); + (pages * 4096, hwm * 1024) +} + +/// Resident memory of decoding a request and handing its rows over in chunks. +/// Release build, run alone: +/// `cargo test --release --lib -- --ignored --exact otel::memory_tests::resident_memory_of_requests --nocapture` +#[test] +#[cfg(target_os = "linux")] +#[ignore = "measures the resident memory of the process; run it alone"] +fn resident_memory_of_requests() { + use prost::Message; + + fn measure_case(name: &str, signal: &str, body: &[u8]) { + // VmHWM is reset to the current resident size + std::fs::write("/proc/self/clear_refs", "5").unwrap(); + let (before, _) = resident(); + let mut rows = 0usize; + let mut stage = |chunk: Vec, _bytes: usize| { + rows += chunk.len(); + Ok::<_, JsonFlattenError>(()) + }; + let mut chunker = Chunker::new(CHUNK_LIMITS, &mut stage); + let (decoded, after_decode) = match signal { + "logs" => { + let request = ExportLogsServiceRequest::decode(body).unwrap(); + let decoded = resident().0; + crate::otel::logs::flatten_logs_into( + &request.resource_logs, + &mut FlattenBudget::new(FlattenLimits::DEFAULT), + &mut chunker, + ) + .unwrap(); + (decoded, resident().0) + } + "traces" => { + let request = ExportTraceServiceRequest::decode(body).unwrap(); + let decoded = resident().0; + crate::otel::traces::flatten_traces_into(&request.resource_spans, &mut chunker) + .unwrap(); + (decoded, resident().0) + } + _ => { + let request = ExportMetricsServiceRequest::decode(body).unwrap(); + let decoded = resident().0; + crate::otel::metrics::flatten_metrics_into( + &request.resource_metrics, + false, + &mut chunker, + ) + .unwrap(); + (decoded, resident().0) + } + }; + chunker.finish().unwrap(); + drop(chunker); + let (_, hwm) = resident(); + println!( + "RESIDENT {name}: body {:.1} MiB, {rows} rows, decoded +{:.0} MiB, peak +{:.0} MiB over the {:.0} MiB before (decode included), {:.0} MiB at the end", + mb(body.len()), + mb(decoded.saturating_sub(before)), + mb(hwm.saturating_sub(before)), + mb(before), + mb(after_decode) + ); + } + + // One case per process, so that memory freed by an earlier case does not hide + // what a later one takes: `RESIDENT_CASE` is `events`, `tiny`, or + // `:` (see `dump_realistic_bodies`) + let case = std::env::var("RESIDENT_CASE").expect("RESIDENT_CASE"); + match case.split_once(':') { + // The two worst cases of the review: 2,097,152 empty events of one span + // (4 MiB), and 1000 tiny resource attributes copied into 5000 rows + None if case == "events" => { + let body = one_span(Span { + events: vec![Event::default(); 1 << 21], + ..Default::default() + }) + .encode_to_vec(); + measure_case("2,097,152 empty events of one span", "traces", &body); + } + None if case == "tiny" => { + let body = ExportLogsServiceRequest { + resource_logs: vec![ResourceLogs { + resource: Some(Resource { + attributes: (0..1000) + .map(|i| kv(format!("k{i:03}"), any_value::Value::IntValue(0))) + .collect(), + ..Default::default() + }), + scope_logs: vec![ScopeLogs { + log_records: (0..5000u64) + .map(|i| LogRecord { + time_unix_nano: 1_700_000_000_000_000_000 + i, + observed_time_unix_nano: 1_700_000_000_000_000_000, + ..Default::default() + }) + .collect(), + ..Default::default() + }], + ..Default::default() + }], + } + .encode_to_vec(); + measure_case( + "1000 tiny resource attributes x 5000 records", + "logs", + &body, + ); + } + Some((signal, path)) => { + let body = std::fs::read(path).unwrap(); + measure_case(path, signal, &body); + } + None => panic!("unknown RESIDENT_CASE {case}"), + } +} diff --git a/src/otel/metrics.rs b/src/otel/metrics.rs index b71a5d76f..416363938 100644 --- a/src/otel/metrics.rs +++ b/src/otel/metrics.rs @@ -17,16 +17,17 @@ */ use once_cell::sync::Lazy; use opentelemetry_proto::tonic::collector::metrics::v1::ExportMetricsServiceRequest; +use opentelemetry_proto::tonic::common::v1::InstrumentationScope; use opentelemetry_proto::tonic::metrics::v1::number_data_point::Value as NumberDataPointValue; use opentelemetry_proto::tonic::metrics::v1::{ - Exemplar, ExponentialHistogram, Gauge, Histogram, Metric, MetricsData, NumberDataPoint, Sum, - Summary, exemplar::Value as ExemplarValue, exponential_histogram_data_point::Buckets, metric, + Exemplar, ExponentialHistogram, ExponentialHistogramDataPoint, Histogram, HistogramDataPoint, + Metric, MetricsData, NumberDataPoint, ResourceMetrics, Sum, SummaryDataPoint, + exemplar::Value as ExemplarValue, exponential_histogram_data_point::Buckets, metric, }; +use opentelemetry_proto::tonic::resource::v1::Resource; use serde_json::{Map, Value}; -use rustc_hash::FxHasher; -use std::borrow::Cow; -use std::collections::HashSet; +use rustc_hash::{FxHashSet, FxHasher}; use std::hash::Hasher; use tracing::info_span; @@ -34,8 +35,10 @@ use crate::metrics::increment_metrics_collected_by_date; use crate::parseable::PARSEABLE; use super::otel_utils::{ - convert_epoch_nano_to_timestamp, insert_attributes, insert_number_if_some, + attribute_capacity, convert_epoch_nano_to_timestamp, insert_attributes, + insert_attributes_fitted, insert_number_if_some, }; +use super::sink::RowSink; pub const SERIES_HASH_COLUMN: &str = "__series_hash_u64"; @@ -91,7 +94,7 @@ pub const OTEL_METRICS_KNOWN_FIELD_LIST: [&str; 39] = [ SERIES_HASH_COLUMN, ]; -static OTEL_METRICS_KNOWN_FIELDS: Lazy> = +static OTEL_METRICS_KNOWN_FIELDS: Lazy> = Lazy::new(|| OTEL_METRICS_KNOWN_FIELD_LIST.iter().copied().collect()); const SERVICE_NAME_ATTRIBUTE: &str = "service.name"; @@ -173,33 +176,52 @@ fn target_info_record( /// non-cryptographic) and feeds keys in sorted order so the hash /// doesn't depend on JSON Map iteration order. pub fn compute_series_hash(dp: &Map) -> u64 { - let mut label_pairs: Vec<(&str, Cow<'_, str>)> = Vec::with_capacity(dp.len()); + // Only references are collected: a non-string label is hashed as the text + // `Value` would print, not formatted into a string first (that allocated + // one string per non-string label of every data point). + let mut label_pairs: Vec<(&str, &Value)> = Vec::with_capacity(dp.len()); + let mut metric_name: Option<&str> = None; for (key, value) in dp { + if key == "metric_name" + && let Value::String(name) = value + { + metric_name = Some(name.as_str()); + } if OTEL_METRICS_KNOWN_FIELDS.contains(key.as_str()) { continue; } if key.starts_with("exemplars_") { continue; } - let value = match value { - Value::String(s) => Cow::Borrowed(s.as_str()), - other => Cow::Owned(other.to_string()), - }; label_pairs.push((key.as_str(), value)); } - label_pairs.sort_by(|a, b| a.0.cmp(b.0)); + // Keys are unique, so an unstable sort leaves the same order + label_pairs.sort_unstable_by(|a, b| a.0.cmp(b.0)); let mut hasher = FxHasher::default(); // Include metric_name in the identity. Without it, two different // metrics with identical label sets would collide into one series. - if let Some(Value::String(name)) = dp.get("metric_name") { + if let Some(name) = metric_name { hasher.write(name.as_bytes()); hasher.write(b"\0"); } + let mut number = String::new(); for (k, v) in &label_pairs { hasher.write(k.as_bytes()); hasher.write(b"="); - hasher.write(v.as_bytes()); + match v { + Value::String(s) => hasher.write(s.as_bytes()), + Value::Bool(b) => hasher.write(if *b { b"true" } else { b"false" }), + Value::Null => hasher.write(b"null"), + Value::Number(n) => { + // `Value` prints a number as this `Display` does + number.clear(); + std::fmt::Write::write_fmt(&mut number, format_args!("{n}")).unwrap(); + hasher.write(number.as_bytes()); + } + // An array or object, as `Value` prints it + other => hasher.write(other.to_string().as_bytes()), + } hasher.write(b"\0"); } hasher.finish() @@ -229,7 +251,8 @@ fn exemplar_value_to_json(value: &ExemplarValue) -> Value { /// names match the legacy flat columns, so switching representations via the /// flag changes only the shape, not the field names. fn exemplar_to_json(exemplar: &Exemplar) -> Value { - let mut exemplar_json = Map::with_capacity(exemplar.filtered_attributes.len() + 4); + let mut exemplar_json = + Map::with_capacity(attribute_capacity(&exemplar.filtered_attributes) + 4); insert_attributes(&mut exemplar_json, &exemplar.filtered_attributes); exemplar_json.insert( "exemplar_time_unix_nano".to_string(), @@ -293,148 +316,134 @@ fn insert_exemplars(map: &mut Map, exemplars: &[Exemplar], flatte } } -/// otel metrics event has json array for number data points -/// this function flatten the number data points json array -/// and returns a `Vec` of `Map` of the flattened json -/// this function is reused in all json objects that have number data points -fn flatten_number_data_points( - data_points: &[NumberDataPoint], +/// The own fields of the row of one number data point (gauge or sum); `extra` is +/// the capacity the metric and envelope fields merged over it will take +fn number_data_point_row( + data_point: &NumberDataPoint, flatten_exemplars: bool, -) -> Vec> { - data_points - .iter() - .map(|data_point| { - let mut data_point_json = Map::with_capacity(data_point.attributes.len() + 8); - insert_attributes(&mut data_point_json, &data_point.attributes); - data_point_json.insert( - "start_time_unix_nano".to_string(), - Value::String(convert_epoch_nano_to_timestamp( - data_point.start_time_unix_nano as i64, - )), - ); - data_point_json.insert( - "time_unix_nano".to_string(), - Value::String(convert_epoch_nano_to_timestamp( - data_point.time_unix_nano as i64, - )), - ); + extra: usize, +) -> Map { + let capacity = attribute_capacity(&data_point.attributes) + 8 + extra; + let mut data_point_json = Map::with_capacity(capacity); + insert_attributes_fitted(&mut data_point_json, &data_point.attributes, capacity); + data_point_json.insert( + "start_time_unix_nano".to_string(), + Value::String(convert_epoch_nano_to_timestamp( + data_point.start_time_unix_nano as i64, + )), + ); + data_point_json.insert( + "time_unix_nano".to_string(), + Value::String(convert_epoch_nano_to_timestamp( + data_point.time_unix_nano as i64, + )), + ); - insert_exemplars( - &mut data_point_json, - &data_point.exemplars, - flatten_exemplars, - ); + insert_exemplars( + &mut data_point_json, + &data_point.exemplars, + flatten_exemplars, + ); - insert_data_point_flags(&mut data_point_json, data_point.flags); - if let Some(value) = &data_point.value { - match value { - NumberDataPointValue::AsDouble(double_val) => { - data_point_json.insert( - "data_point_value".to_string(), - serde_json::Number::from_f64(*double_val) - .map(Value::Number) - .unwrap_or(Value::Null), - ); - } - NumberDataPointValue::AsInt(int_val) => { - data_point_json.insert( - "data_point_value".to_string(), - Value::Number(serde_json::Number::from(*int_val)), - ); - } - } + insert_data_point_flags(&mut data_point_json, data_point.flags); + if let Some(value) = &data_point.value { + match value { + NumberDataPointValue::AsDouble(double_val) => { + data_point_json.insert( + "data_point_value".to_string(), + serde_json::Number::from_f64(*double_val) + .map(Value::Number) + .unwrap_or(Value::Null), + ); } - data_point_json - }) - .collect() -} - -/// otel metrics event has json object for gauge -/// each gauge object has json array for data points -/// this function flatten the gauge json object -/// and returns a `Vec` of `Map` for each data point -fn flatten_gauge(gauge: &Gauge, flatten_exemplars: bool) -> Vec> { - flatten_number_data_points(&gauge.data_points, flatten_exemplars) + NumberDataPointValue::AsInt(int_val) => { + data_point_json.insert( + "data_point_value".to_string(), + Value::Number(serde_json::Number::from(*int_val)), + ); + } + } + } + data_point_json } -/// otel metrics event has json object for sum -/// each sum object has json array for data points -/// this function flatten the sum json object -/// and returns a `Vec` of `Map` for each data point -fn flatten_sum(sum: &Sum, flatten_exemplars: bool) -> Vec> { - let mut data_points = flatten_number_data_points(&sum.data_points, flatten_exemplars); - for dp in &mut data_points { - insert_aggregation_temporality(dp, sum.aggregation_temporality); - dp.insert("is_monotonic".to_string(), Value::Bool(sum.is_monotonic)); - } - data_points +/// The own fields of the row of one sum data point +fn sum_data_point_row( + sum: &Sum, + data_point: &NumberDataPoint, + flatten_exemplars: bool, + extra: usize, +) -> Map { + let mut dp = number_data_point_row(data_point, flatten_exemplars, extra); + insert_aggregation_temporality(&mut dp, sum.aggregation_temporality); + dp.insert("is_monotonic".to_string(), Value::Bool(sum.is_monotonic)); + dp } -/// otel metrics event has json object for histogram -/// each histogram object has json array for data points -/// this function flatten the histogram json object -/// and returns a `Vec` of `Map` for each data point -fn flatten_histogram(histogram: &Histogram, flatten_exemplars: bool) -> Vec> { - let mut data_points_json = Vec::with_capacity(histogram.data_points.len()); - for data_point in &histogram.data_points { - let mut data_point_json = Map::with_capacity(data_point.attributes.len() + 10); - insert_attributes(&mut data_point_json, &data_point.attributes); - data_point_json.insert( - "start_time_unix_nano".to_string(), - Value::String(convert_epoch_nano_to_timestamp( - data_point.start_time_unix_nano as i64, - )), - ); - data_point_json.insert( - "time_unix_nano".to_string(), - Value::String(convert_epoch_nano_to_timestamp( - data_point.time_unix_nano as i64, - )), - ); - data_point_json.insert( - "data_point_count".to_string(), - Value::Number(data_point.count.into()), - ); - insert_number_if_some(&mut data_point_json, "data_point_sum", &data_point.sum); - let data_point_bucket_counts = Value::Array( - data_point - .bucket_counts - .iter() - .map(|&count| Value::Number(count.into())) - .collect(), - ); - data_point_json.insert( - "data_point_bucket_counts".to_string(), - data_point_bucket_counts, - ); - let data_point_explicit_bounds = Value::Array( - data_point - .explicit_bounds - .iter() - .map(|bound| { - serde_json::Number::from_f64(*bound) - .map(Value::Number) - .unwrap_or(Value::Null) - }) - .collect(), - ); - data_point_json.insert( - "data_point_explicit_bounds".to_string(), - data_point_explicit_bounds, - ); - insert_exemplars( - &mut data_point_json, - &data_point.exemplars, - flatten_exemplars, - ); +/// The own fields of the row of one histogram data point +fn histogram_data_point_row( + histogram: &Histogram, + data_point: &HistogramDataPoint, + flatten_exemplars: bool, + extra: usize, +) -> Map { + let capacity = attribute_capacity(&data_point.attributes) + 10 + extra; + let mut data_point_json = Map::with_capacity(capacity); + insert_attributes_fitted(&mut data_point_json, &data_point.attributes, capacity); + data_point_json.insert( + "start_time_unix_nano".to_string(), + Value::String(convert_epoch_nano_to_timestamp( + data_point.start_time_unix_nano as i64, + )), + ); + data_point_json.insert( + "time_unix_nano".to_string(), + Value::String(convert_epoch_nano_to_timestamp( + data_point.time_unix_nano as i64, + )), + ); + data_point_json.insert( + "data_point_count".to_string(), + Value::Number(data_point.count.into()), + ); + insert_number_if_some(&mut data_point_json, "data_point_sum", &data_point.sum); + let data_point_bucket_counts = Value::Array( + data_point + .bucket_counts + .iter() + .map(|&count| Value::Number(count.into())) + .collect(), + ); + data_point_json.insert( + "data_point_bucket_counts".to_string(), + data_point_bucket_counts, + ); + let data_point_explicit_bounds = Value::Array( + data_point + .explicit_bounds + .iter() + .map(|bound| { + serde_json::Number::from_f64(*bound) + .map(Value::Number) + .unwrap_or(Value::Null) + }) + .collect(), + ); + data_point_json.insert( + "data_point_explicit_bounds".to_string(), + data_point_explicit_bounds, + ); + insert_exemplars( + &mut data_point_json, + &data_point.exemplars, + flatten_exemplars, + ); - insert_data_point_flags(&mut data_point_json, data_point.flags); - insert_number_if_some(&mut data_point_json, "data_point_min", &data_point.min); - insert_number_if_some(&mut data_point_json, "data_point_max", &data_point.max); - insert_aggregation_temporality(&mut data_point_json, histogram.aggregation_temporality); - data_points_json.push(data_point_json); - } - data_points_json + insert_data_point_flags(&mut data_point_json, data_point.flags); + insert_number_if_some(&mut data_point_json, "data_point_min", &data_point.min); + insert_number_if_some(&mut data_point_json, "data_point_max", &data_point.max); + insert_aggregation_temporality(&mut data_point_json, histogram.aggregation_temporality); + data_point_json } /// otel metrics event has json object for buckets @@ -456,239 +465,298 @@ fn flatten_buckets(bucket: &Buckets) -> Map { bucket_json } -/// otel metrics event has json object for exponential histogram -/// each exponential histogram object has json array for data points -/// this function flatten the exponential histogram json object -/// and returns a `Vec` of `Map` for each data point -fn flatten_exp_histogram( +/// The own fields of the row of one exponential histogram data point +fn exp_histogram_data_point_row( exp_histogram: &ExponentialHistogram, + data_point: &ExponentialHistogramDataPoint, flatten_exemplars: bool, -) -> Vec> { - let mut data_points_json = Vec::with_capacity(exp_histogram.data_points.len()); - for data_point in &exp_histogram.data_points { - let mut data_point_json = Map::with_capacity(data_point.attributes.len() + 12); - insert_attributes(&mut data_point_json, &data_point.attributes); - data_point_json.insert( - "start_time_unix_nano".to_string(), - Value::String(convert_epoch_nano_to_timestamp( - data_point.start_time_unix_nano as i64, - )), - ); - data_point_json.insert( - "time_unix_nano".to_string(), - Value::String(convert_epoch_nano_to_timestamp( - data_point.time_unix_nano as i64, - )), - ); - data_point_json.insert( - "data_point_count".to_string(), - Value::Number(data_point.count.into()), - ); - insert_number_if_some(&mut data_point_json, "data_point_sum", &data_point.sum); - data_point_json.insert( - "data_point_scale".to_string(), - Value::Number(data_point.scale.into()), - ); - data_point_json.insert( - "data_point_zero_count".to_string(), - Value::Number(data_point.zero_count.into()), - ); - if let Some(positive) = &data_point.positive { - let positive_json = flatten_buckets(positive); - for (key, value) in positive_json { - data_point_json.insert(format!("positive_{key}"), value); - } + extra: usize, +) -> Map { + let capacity = attribute_capacity(&data_point.attributes) + 12 + extra; + let mut data_point_json = Map::with_capacity(capacity); + insert_attributes_fitted(&mut data_point_json, &data_point.attributes, capacity); + data_point_json.insert( + "start_time_unix_nano".to_string(), + Value::String(convert_epoch_nano_to_timestamp( + data_point.start_time_unix_nano as i64, + )), + ); + data_point_json.insert( + "time_unix_nano".to_string(), + Value::String(convert_epoch_nano_to_timestamp( + data_point.time_unix_nano as i64, + )), + ); + data_point_json.insert( + "data_point_count".to_string(), + Value::Number(data_point.count.into()), + ); + insert_number_if_some(&mut data_point_json, "data_point_sum", &data_point.sum); + data_point_json.insert( + "data_point_scale".to_string(), + Value::Number(data_point.scale.into()), + ); + data_point_json.insert( + "data_point_zero_count".to_string(), + Value::Number(data_point.zero_count.into()), + ); + if let Some(positive) = &data_point.positive { + let positive_json = flatten_buckets(positive); + for (key, value) in positive_json { + data_point_json.insert(format!("positive_{key}"), value); } - if let Some(negative) = &data_point.negative { - let negative_json = flatten_buckets(negative); - for (key, value) in negative_json { - data_point_json.insert(format!("negative_{key}"), value); - } + } + if let Some(negative) = &data_point.negative { + let negative_json = flatten_buckets(negative); + for (key, value) in negative_json { + data_point_json.insert(format!("negative_{key}"), value); } - insert_exemplars( - &mut data_point_json, - &data_point.exemplars, - flatten_exemplars, - ); - - insert_aggregation_temporality(&mut data_point_json, exp_histogram.aggregation_temporality); - data_points_json.push(data_point_json); } - data_points_json + insert_exemplars( + &mut data_point_json, + &data_point.exemplars, + flatten_exemplars, + ); + + insert_aggregation_temporality(&mut data_point_json, exp_histogram.aggregation_temporality); + data_point_json } -/// otel metrics event has json object for summary -/// each summary object has json array for data points -/// this function flatten the summary json object -/// and returns a `Vec` of `Map` for each data point -fn flatten_summary(summary: &Summary) -> Vec> { - let mut data_points_json = Vec::with_capacity(summary.data_points.len()); - for data_point in &summary.data_points { - let mut data_point_json = Map::with_capacity(data_point.attributes.len() + 6); - insert_attributes(&mut data_point_json, &data_point.attributes); - data_point_json.insert( - "start_time_unix_nano".to_string(), - Value::String(convert_epoch_nano_to_timestamp( - data_point.start_time_unix_nano as i64, - )), - ); - data_point_json.insert( - "time_unix_nano".to_string(), - Value::String(convert_epoch_nano_to_timestamp( - data_point.time_unix_nano as i64, - )), - ); - data_point_json.insert( - "data_point_count".to_string(), - Value::Number(data_point.count.into()), - ); - data_point_json.insert( - "data_point_sum".to_string(), - serde_json::Number::from_f64(data_point.sum) - .map(Value::Number) - .unwrap_or(Value::Null), - ); - data_point_json.insert( - "data_point_quantile_values".to_string(), - Value::Array( - data_point - .quantile_values - .iter() - .map(|quantile_value| { - let mut quantile_map = Map::with_capacity(2); - quantile_map.insert( - "quantile".to_string(), - serde_json::Number::from_f64(quantile_value.quantile) - .map(Value::Number) - .unwrap_or(Value::Null), - ); - quantile_map.insert( - "value".to_string(), - serde_json::Number::from_f64(quantile_value.value) - .map(Value::Number) - .unwrap_or(Value::Null), - ); - Value::Object(quantile_map) - }) - .collect(), - ), - ); +/// The own fields of the row of one summary data point +fn summary_data_point_row(data_point: &SummaryDataPoint, extra: usize) -> Map { + let capacity = attribute_capacity(&data_point.attributes) + 6 + extra; + let mut data_point_json = Map::with_capacity(capacity); + insert_attributes_fitted(&mut data_point_json, &data_point.attributes, capacity); + data_point_json.insert( + "start_time_unix_nano".to_string(), + Value::String(convert_epoch_nano_to_timestamp( + data_point.start_time_unix_nano as i64, + )), + ); + data_point_json.insert( + "time_unix_nano".to_string(), + Value::String(convert_epoch_nano_to_timestamp( + data_point.time_unix_nano as i64, + )), + ); + data_point_json.insert( + "data_point_count".to_string(), + Value::Number(data_point.count.into()), + ); + data_point_json.insert( + "data_point_sum".to_string(), + serde_json::Number::from_f64(data_point.sum) + .map(Value::Number) + .unwrap_or(Value::Null), + ); + data_point_json.insert( + "data_point_quantile_values".to_string(), + Value::Array( + data_point + .quantile_values + .iter() + .map(|quantile_value| { + let mut quantile_map = Map::with_capacity(2); + quantile_map.insert( + "quantile".to_string(), + serde_json::Number::from_f64(quantile_value.quantile) + .map(Value::Number) + .unwrap_or(Value::Null), + ); + quantile_map.insert( + "value".to_string(), + serde_json::Number::from_f64(quantile_value.value) + .map(Value::Number) + .unwrap_or(Value::Null), + ); + Value::Object(quantile_map) + }) + .collect(), + ), + ); + data_point_json +} + +/// One row of a metric, handed to the caller of `metric_rows` +pub enum MetricRow { + /// The row of one data point + Point(Map), + /// The one row of a metric that has data but no data points + NoPoints(Map), +} + +/// Fields every row of one metric gets, merged over the data point's own fields +struct MetricFields { + name: Value, + description: Value, + unit: Value, + metric_type: Value, + metadata: Map, +} - data_points_json.push(data_point_json); +impl MetricFields { + fn apply(&self, mut dp: Map) -> Map { + dp.insert("metric_name".to_string(), self.name.clone()); + dp.insert("metric_description".to_string(), self.description.clone()); + dp.insert("metric_unit".to_string(), self.unit.clone()); + dp.insert("metric_type".to_string(), self.metric_type.clone()); + for (k, v) in &self.metadata { + dp.insert(k.clone(), v.clone()); + } + dp } - data_points_json } -/// this function flattens the `Metric` object -/// each metric object has json object for gauge, sum, histogram, exponential histogram, summary -/// this function flatten the metric json object -/// and returns a `Vec` of `Map` of the flattened json -/// this function is called recursively for each metric record object in the otel metrics event -pub fn flatten_metrics_record( +/// Hands the rows of one metric to `emit` one at a time: one per data point, each +/// built once the one before it was handed over, or one for a metric that has data +/// but no data points. A metric without data has no rows. `merged` is the number of +/// fields the caller merges over every row after this (a scope's envelope); rows +/// are sized for them so that merging never has to grow a row map. +pub fn metric_rows( metrics_record: &Metric, flatten_exemplars: bool, -) -> Vec> { - let (mut data_points, metric_type) = match &metrics_record.data { - Some(metric::Data::Gauge(gauge)) => (flatten_gauge(gauge, flatten_exemplars), "gauge"), - Some(metric::Data::Sum(sum)) => (flatten_sum(sum, flatten_exemplars), "sum"), - Some(metric::Data::Histogram(histogram)) => { - (flatten_histogram(histogram, flatten_exemplars), "histogram") - } - Some(metric::Data::ExponentialHistogram(exp_histogram)) => ( - flatten_exp_histogram(exp_histogram, flatten_exemplars), - "exponential_histogram", - ), - Some(metric::Data::Summary(summary)) => (flatten_summary(summary), "summary"), - None => return Vec::new(), + merged: usize, + mut emit: impl FnMut(MetricRow) -> Result<(), E>, +) -> Result<(), E> { + let Some(data) = &metrics_record.data else { + return Ok(()); + }; + let metric_type = match data { + metric::Data::Gauge(_) => "gauge", + metric::Data::Sum(_) => "sum", + metric::Data::Histogram(_) => "histogram", + metric::Data::ExponentialHistogram(_) => "exponential_histogram", + metric::Data::Summary(_) => "summary", }; // Build metric-level fields once - let metric_name = Value::String(metrics_record.name.clone()); - let metric_desc = Value::String(metrics_record.description.clone()); - let metric_unit = Value::String(metrics_record.unit.clone()); - let metric_type_val = Value::String(metric_type.to_string()); - let mut metadata = Map::with_capacity(metrics_record.metadata.len()); - insert_attributes(&mut metadata, &metrics_record.metadata); - - if data_points.is_empty() { - let mut single = Map::with_capacity(metadata.len() + 8); - single.insert("metric_name".to_string(), metric_name); - single.insert("metric_description".to_string(), metric_desc); - single.insert("metric_unit".to_string(), metric_unit); - single.insert("metric_type".to_string(), metric_type_val); - match &metrics_record.data { - Some(metric::Data::Sum(sum)) => { + let capacity = attribute_capacity(&metrics_record.metadata); + let mut metadata = Map::with_capacity(capacity); + insert_attributes_fitted(&mut metadata, &metrics_record.metadata, capacity); + let fields = MetricFields { + name: Value::String(metrics_record.name.clone()), + description: Value::String(metrics_record.description.clone()), + unit: Value::String(metrics_record.unit.clone()), + metric_type: Value::String(metric_type.to_string()), + metadata, + }; + let extra = 4 + fields.metadata.len() + merged; + + let points = match data { + metric::Data::Gauge(gauge) => { + for dp in &gauge.data_points { + emit(MetricRow::Point(fields.apply(number_data_point_row( + dp, + flatten_exemplars, + extra, + ))))?; + } + gauge.data_points.len() + } + metric::Data::Sum(sum) => { + for dp in &sum.data_points { + emit(MetricRow::Point(fields.apply(sum_data_point_row( + sum, + dp, + flatten_exemplars, + extra, + ))))?; + } + sum.data_points.len() + } + metric::Data::Histogram(histogram) => { + for dp in &histogram.data_points { + emit(MetricRow::Point(fields.apply(histogram_data_point_row( + histogram, + dp, + flatten_exemplars, + extra, + ))))?; + } + histogram.data_points.len() + } + metric::Data::ExponentialHistogram(exp_histogram) => { + for dp in &exp_histogram.data_points { + emit(MetricRow::Point(fields.apply( + exp_histogram_data_point_row(exp_histogram, dp, flatten_exemplars, extra), + )))?; + } + exp_histogram.data_points.len() + } + metric::Data::Summary(summary) => { + for dp in &summary.data_points { + emit(MetricRow::Point( + fields.apply(summary_data_point_row(dp, extra)), + ))?; + } + summary.data_points.len() + } + }; + + if points == 0 { + let MetricFields { + name, + description, + unit, + metric_type, + metadata, + } = fields; + let mut single = Map::with_capacity(metadata.len() + 8 + merged); + single.insert("metric_name".to_string(), name); + single.insert("metric_description".to_string(), description); + single.insert("metric_unit".to_string(), unit); + single.insert("metric_type".to_string(), metric_type); + match data { + metric::Data::Sum(sum) => { insert_aggregation_temporality(&mut single, sum.aggregation_temporality); single.insert("is_monotonic".to_string(), Value::Bool(sum.is_monotonic)); } - Some(metric::Data::Histogram(histogram)) => { + metric::Data::Histogram(histogram) => { insert_aggregation_temporality(&mut single, histogram.aggregation_temporality); } - Some(metric::Data::ExponentialHistogram(exp_histogram)) => { + metric::Data::ExponentialHistogram(exp_histogram) => { insert_aggregation_temporality(&mut single, exp_histogram.aggregation_temporality); } _ => {} } single.extend(metadata); - return vec![single]; - } - - // Insert metric-level fields directly into each data point - for dp in &mut data_points { - dp.insert("metric_name".to_string(), metric_name.clone()); - dp.insert("metric_description".to_string(), metric_desc.clone()); - dp.insert("metric_unit".to_string(), metric_unit.clone()); - dp.insert("metric_type".to_string(), metric_type_val.clone()); - for (k, v) in &metadata { - dp.insert(k.clone(), v.clone()); - } + emit(MetricRow::NoPoints(single))?; } - - data_points + Ok(()) } -fn metric_data_point_count(metric: &Metric) -> usize { - match &metric.data { - Some(metric::Data::Gauge(gauge)) => gauge.data_points.len(), - Some(metric::Data::Sum(sum)) => sum.data_points.len(), - Some(metric::Data::Histogram(histogram)) => histogram.data_points.len(), - Some(metric::Data::ExponentialHistogram(exp_histogram)) => exp_histogram.data_points.len(), - Some(metric::Data::Summary(summary)) => summary.data_points.len(), - None => 0, - } +/// this function flattens the `Metric` object +/// each metric object has json object for gauge, sum, histogram, exponential histogram, summary +/// this function flatten the metric json object +/// and returns a `Vec` of `Map` of the flattened json +pub fn flatten_metrics_record( + metrics_record: &Metric, + flatten_exemplars: bool, +) -> Vec> { + let mut rows = Vec::new(); + let Ok(()) = + metric_rows::(metrics_record, flatten_exemplars, 0, |row| { + rows.push(match row { + MetricRow::Point(row) | MetricRow::NoPoints(row) => row, + }); + Ok(()) + }); + rows } -/// Common function to process resource metrics and merge resource-level fields -#[allow(clippy::too_many_arguments)] -fn process_resource_metrics( - resource_metrics: &[T], - get_resource: fn(&T) -> Option<&opentelemetry_proto::tonic::resource::v1::Resource>, - get_scope_metrics: fn(&T) -> &[S], - get_schema_url: fn(&T) -> &str, - get_scope: fn(&S) -> Option<&opentelemetry_proto::tonic::common::v1::InstrumentationScope>, - get_scope_schema_url: fn(&S) -> &str, - get_metrics: fn(&S) -> &[M], - get_metric: fn(&M) -> &Metric, - tenant_id: &str, - flatten_exemplars: bool, -) -> Vec { - let _span = info_span!( - "process_resource_metrics", - resource_count = resource_metrics.len(), - ) - .entered(); - let mut vec_otel_json = Vec::new(); +/// Fields every row of one `ResourceMetrics` gets, and its Prometheus target identity +pub struct ResourceMetricFields { + fields: Map, + target_identity: Option<(String, String)>, +} - for resource_metric in resource_metrics { +impl ResourceMetricFields { + pub fn new(resource: Option<&Resource>, schema_url: &str) -> Self { // Build resource-level fields once per resource - let mut resource_fields = Map::with_capacity( - get_resource(resource_metric) - .map(|resource| resource.attributes.len()) - .unwrap_or_default() - + 2, - ); - if let Some(resource) = get_resource(resource_metric) { - insert_attributes(&mut resource_fields, &resource.attributes); + let capacity = resource.map_or(0, |resource| attribute_capacity(&resource.attributes)) + 2; + let mut resource_fields = Map::with_capacity(capacity); + if let Some(resource) = resource { + insert_attributes_fitted(&mut resource_fields, &resource.attributes, capacity); resource_fields.insert( "resource_dropped_attributes_count".to_string(), Value::Number(resource.dropped_attributes_count.into()), @@ -696,7 +764,7 @@ fn process_resource_metrics( } resource_fields.insert( "resource_schema_url".to_string(), - Value::String(get_schema_url(resource_metric).to_string()), + Value::String(schema_url.to_string()), ); // Prometheus uses these labels as the foreign key between every @@ -705,86 +773,160 @@ fn process_resource_metrics( if let Some(identity) = &target_identity { insert_prometheus_target_identity(&mut resource_fields, identity); } - let mut target_timestamp: Option = None; + Self { + fields: resource_fields, + target_identity, + } + } - for scope_metric in get_scope_metrics(resource_metric) { - // Build envelope = resource + scope fields (once per scope) - let mut envelope = resource_fields.clone(); + /// Envelope = resource + scope fields, merged over every row of the scope + pub fn scope_envelope( + &self, + scope: Option<&InstrumentationScope>, + scope_schema_url: &str, + ) -> Map { + let mut envelope = self.fields.clone(); - if let Some(scope) = get_scope(scope_metric) { - envelope.insert("scope_name".to_string(), Value::String(scope.name.clone())); - envelope.insert( - "scope_version".to_string(), - Value::String(scope.version.clone()), - ); - insert_attributes(&mut envelope, &scope.attributes); - envelope.insert( - "scope_dropped_attributes_count".to_string(), - Value::Number(scope.dropped_attributes_count.into()), - ); - } + if let Some(scope) = scope { + envelope.insert("scope_name".to_string(), Value::String(scope.name.clone())); envelope.insert( - "scope_schema_url".to_string(), - Value::String(get_scope_schema_url(scope_metric).to_string()), + "scope_version".to_string(), + Value::String(scope.version.clone()), ); - // Scope attributes are merged after resource attributes. Reapply - // the derived identity so they cannot shadow job or instance. - if let Some(identity) = &target_identity { - insert_prometheus_target_identity(&mut envelope, identity); - } - - let metrics = get_metrics(scope_metric); - vec_otel_json.reserve( - metrics - .iter() - .map(|metric| metric_data_point_count(get_metric(metric)).max(1)) - .sum::(), + insert_attributes(&mut envelope, &scope.attributes); + envelope.insert( + "scope_dropped_attributes_count".to_string(), + Value::Number(scope.dropped_attributes_count.into()), ); - let date = chrono::Utc::now().date_naive().to_string(); - increment_metrics_collected_by_date(metrics.len() as u64, &date, tenant_id); - - // Flatten each metric's data points and merge envelope in one pass - for metric in metrics { - let data_points = flatten_metrics_record(get_metric(metric), flatten_exemplars); - for mut dp in data_points { - if let Some(Value::String(timestamp)) = dp.get("time_unix_nano") - && target_timestamp - .as_ref() - .is_none_or(|latest| timestamp > latest) - { - target_timestamp = Some(timestamp.clone()); - } - for (k, v) in &envelope { - dp.insert(k.clone(), v.clone()); - } - // Compute the physical-series hash AFTER envelope merge - // so resource/scope attributes participate in series - // identity (they're labels from the query layer's - // perspective). Computed once per data point — O(label - // count) per sample, ~200 ns at typical attribute counts. - let series_hash = compute_series_hash(&dp); - dp.insert( - SERIES_HASH_COLUMN.to_string(), - Value::Number(series_hash.into()), - ); - vec_otel_json.push(Value::Object(dp)); - } - } } + envelope.insert( + "scope_schema_url".to_string(), + Value::String(scope_schema_url.to_string()), + ); + // Scope attributes are merged after resource attributes. Reapply + // the derived identity so they cannot shadow job or instance. + if let Some(identity) = &self.target_identity { + insert_prometheus_target_identity(&mut envelope, identity); + } + envelope + } + + /// Whether the rows of this resource get Prometheus `job` and `instance` + /// labels, and the resource a `target_info` row + pub fn has_target_identity(&self) -> bool { + self.target_identity.is_some() + } + /// The `target_info` row of this resource, at the latest data point + /// timestamp of its rows, if it has a Prometheus target identity + pub fn target_info(&self, latest: Option) -> Option> { // Emit one target_info sample per OTel resource, using its latest data // point timestamp so current metadata joins remain available. - if target_identity.is_some() - && let Some(timestamp) = target_timestamp + if self.target_identity.is_some() + && let Some(timestamp) = latest + { + Some(target_info_record(&self.fields, timestamp)) + } else { + None + } + } +} + +/// Hands the rows of every metric of one scope to `sink`, tracking in `latest` the +/// latest `time_unix_nano` of the rows for the resource's `target_info` row +pub fn metric_rows_into( + metric: &Metric, + envelope: &Map, + flatten_exemplars: bool, + latest: &mut Option, + sink: &mut S, +) -> Result<(), S::Error> { + metric_rows(metric, flatten_exemplars, envelope.len(), |row| { + let (mut dp, point) = match row { + MetricRow::Point(dp) => (dp, true), + MetricRow::NoPoints(dp) => (dp, false), + }; + if let Some(Value::String(timestamp)) = dp.get("time_unix_nano") + && latest.as_ref().is_none_or(|latest| timestamp > latest) { - vec_otel_json.push(Value::Object(target_info_record( - &resource_fields, - timestamp, - ))); + *latest = Some(timestamp.clone()); + } + for (k, v) in envelope { + dp.insert(k.clone(), v.clone()); + } + // Compute the physical-series hash AFTER envelope merge + // so resource/scope attributes participate in series + // identity (they're labels from the query layer's + // perspective). Computed once per data point — O(label + // count) per sample, ~200 ns at typical attribute counts. + let series_hash = compute_series_hash(&dp); + dp.insert( + SERIES_HASH_COLUMN.to_string(), + Value::Number(series_hash.into()), + ); + if point { sink.point(dp) } else { sink.row(dp) } + })?; + sink.record_end(); + Ok(()) +} + +/// Hands the rows of every metric of `resource_metrics` to `sink`, one at a time, +/// with one `target_info` row after the rows of each resource that has a +/// Prometheus target identity +pub fn flatten_metrics_into( + resource_metrics: &[ResourceMetrics], + flatten_exemplars: bool, + sink: &mut S, +) -> Result<(), S::Error> { + for resource_metric in resource_metrics { + let resource = ResourceMetricFields::new( + resource_metric.resource.as_ref(), + &resource_metric.schema_url, + ); + let mut target_timestamp: Option = None; + for scope_metric in &resource_metric.scope_metrics { + let envelope = + resource.scope_envelope(scope_metric.scope.as_ref(), &scope_metric.schema_url); + for metric in &scope_metric.metrics { + metric_rows_into( + metric, + &envelope, + flatten_exemplars, + &mut target_timestamp, + sink, + )?; + } + } + if let Some(target) = resource.target_info(target_timestamp) { + sink.row(target)?; } } + Ok(()) +} - vec_otel_json +/// All rows of `resource_metrics` at once, counting the metrics for `tenant_id`. +/// Ingestion streams the rows instead, see `flatten_metrics_into`. +fn process_resource_metrics( + resource_metrics: &[ResourceMetrics], + tenant_id: &str, + flatten_exemplars: bool, +) -> Vec { + let _span = info_span!( + "process_resource_metrics", + resource_count = resource_metrics.len(), + ) + .entered(); + let mut rows = Vec::new(); + flatten_metrics_into(resource_metrics, flatten_exemplars, &mut rows) + .expect("metric rows are never refused"); + let metrics: usize = resource_metrics + .iter() + .flat_map(|resource_metric| &resource_metric.scope_metrics) + .map(|scope_metric| scope_metric.metrics.len()) + .sum(); + let date = chrono::Utc::now().date_naive().to_string(); + increment_metrics_collected_by_date(metrics as u64, &date, tenant_id); + rows } /// this function performs the custom flattening of the otel metrics @@ -800,18 +942,7 @@ pub fn flatten_otel_metrics_with_options( tenant_id: &str, flatten_exemplars: bool, ) -> Vec { - process_resource_metrics( - &message.resource_metrics, - |record| record.resource.as_ref(), - |record| &record.scope_metrics, - |record| &record.schema_url, - |scope_metric| scope_metric.scope.as_ref(), - |scope_metric| &scope_metric.schema_url, - |scope_metric| &scope_metric.metrics, - |metric| metric, - tenant_id, - flatten_exemplars, - ) + process_resource_metrics(&message.resource_metrics, tenant_id, flatten_exemplars) } /// Flattens OpenTelemetry metrics from protobuf format @@ -839,18 +970,7 @@ pub fn flatten_otel_metrics_protobuf_with_options( ); let _guard = span.enter(); - let result = process_resource_metrics( - &message.resource_metrics, - |record| record.resource.as_ref(), - |record| &record.scope_metrics, - |record| &record.schema_url, - |scope_metric| scope_metric.scope.as_ref(), - |scope_metric| &scope_metric.schema_url, - |scope_metric| &scope_metric.metrics, - |metric| metric, - tenant_id, - flatten_exemplars, - ); + let result = process_resource_metrics(&message.resource_metrics, tenant_id, flatten_exemplars); span.record("output_count", result.len()); result @@ -892,6 +1012,7 @@ mod tests { use opentelemetry_proto::tonic::common::v1::{ AnyValue, InstrumentationScope, KeyValue, any_value, }; + use opentelemetry_proto::tonic::metrics::v1::Gauge; use opentelemetry_proto::tonic::metrics::v1::{ResourceMetrics, ScopeMetrics}; use opentelemetry_proto::tonic::resource::v1::Resource; @@ -921,18 +1042,7 @@ mod tests { } fn flatten_for_test(message: &MetricsData) -> Vec { - process_resource_metrics( - &message.resource_metrics, - |record| record.resource.as_ref(), - |record| &record.scope_metrics, - |record| &record.schema_url, - |scope_metric| scope_metric.scope.as_ref(), - |scope_metric| &scope_metric.schema_url, - |scope_metric| &scope_metric.metrics, - |metric| metric, - "test-tenant", - false, - ) + process_resource_metrics(&message.resource_metrics, "test-tenant", false) } #[test] @@ -1500,7 +1610,7 @@ mod tests { }; use opentelemetry_proto::tonic::resource::v1::Resource; - use super::super::{compute_series_hash, process_resource_metrics}; + use super::super::compute_series_hash; const DATA_POINTS_PER_METRIC: usize = 10; const METRICS_PER_SCOPE: usize = 50; @@ -1633,19 +1743,12 @@ mod tests { ExportMetricsServiceRequest { resource_metrics } } + /// What ingestion does with a decoded request: its rows handed over in + /// chunks (collected here) fn flatten(request: &ExportMetricsServiceRequest) -> Vec { - process_resource_metrics( - &request.resource_metrics, - |record| record.resource.as_ref(), - |record| &record.scope_metrics, - |record| &record.schema_url, - |scope_metric| scope_metric.scope.as_ref(), - |scope_metric| &scope_metric.schema_url, - |scope_metric| &scope_metric.metrics, - |metric| metric, - "perfbench", - false, - ) + bench::chunked(|chunker| { + super::super::flatten_metrics_into(&request.resource_metrics, false, chunker) + }) } #[test] diff --git a/src/otel/otel_utils.rs b/src/otel/otel_utils.rs index 5b6ed5616..2f9dede0f 100644 --- a/src/otel/otel_utils.rs +++ b/src/otel/otel_utils.rs @@ -86,6 +86,62 @@ pub fn collect_json_from_value(key: &str, value: OtelValue) -> Map, key: &str, value: &OtelValue) { + match value { + OtelValue::StringValue(str_val) => { + map.insert(key.to_string(), Value::String(str_val.clone())); + } + OtelValue::BoolValue(bool_val) => { + map.insert(key.to_string(), Value::Bool(*bool_val)); + } + OtelValue::IntValue(int_val) => { + map.insert(key.to_string(), Value::String(int_val.to_string())); + } + OtelValue::DoubleValue(double_val) => insert_json_double(map, key, *double_val), + OtelValue::ArrayValue(array_val) => insert_json_array(map, key, array_val), + OtelValue::KvlistValue(kv_list_val) => { + // Create a JSON object to store the key-value list + let kv_object = collect_json_from_key_value_list(kv_list_val); + map.extend(kv_object); + } + OtelValue::BytesValue(bytes_val) => { + map.insert( + key.to_string(), + Value::String(String::from_utf8_lossy(bytes_val).to_string()), + ); + } + OtelValue::StringValueStrindex(str_index) => { + tracing::warn!( + "StringValueStrindex is not supported in key-value lists, index: {str_index}" + ); + } + } +} + +fn insert_json_double(map: &mut Map, key: &str, double_val: f64) { + if let Some(number) = serde_json::Number::from_f64(double_val) { + map.insert(key.to_string(), Value::Number(number)); + } +} + +fn insert_json_array(map: &mut Map, key: &str, array_val: &ArrayValue) { + let json_array_value = collect_json_from_array_value(array_val); + // Convert the array to a JSON string + let json_array_string = match serde_json::to_string(&json_array_value) { + Ok(s) => s, + Err(e) => { + tracing::warn!("failed to serialise array value: {e}"); + String::default() + } + }; + // Insert the array into the result map + map.insert(key.to_string(), Value::String(json_array_string)); +} + fn insert_json_from_value(map: &mut Map, key: &str, value: OtelValue) { match value { OtelValue::StringValue(str_val) => { @@ -97,27 +153,11 @@ fn insert_json_from_value(map: &mut Map, key: &str, value: OtelVa OtelValue::IntValue(int_val) => { map.insert(key.to_string(), Value::String(int_val.to_string())); } - OtelValue::DoubleValue(double_val) => { - if let Some(number) = serde_json::Number::from_f64(double_val) { - map.insert(key.to_string(), Value::Number(number)); - } - } - OtelValue::ArrayValue(array_val) => { - let json_array_value = collect_json_from_array_value(&array_val); - // Convert the array to a JSON string - let json_array_string = match serde_json::to_string(&json_array_value) { - Ok(s) => s, - Err(e) => { - tracing::warn!("failed to serialise array value: {e}"); - String::default() - } - }; - // Insert the array into the result map - map.insert(key.to_string(), Value::String(json_array_string)); - } + OtelValue::DoubleValue(double_val) => insert_json_double(map, key, double_val), + OtelValue::ArrayValue(array_val) => insert_json_array(map, key, &array_val), OtelValue::KvlistValue(kv_list_val) => { // Create a JSON object to store the key-value list - let kv_object = collect_json_from_key_value_list(kv_list_val); + let kv_object = collect_json_from_key_value_list(&kv_list_val); map.extend(kv_object); } OtelValue::BytesValue(bytes_val) => { @@ -138,7 +178,15 @@ fn insert_json_from_value(map: &mut Map, key: &str, value: OtelVa /// This handles nested array values and key-value lists by recursively /// converting them to JSON fn collect_json_from_array_value(array_value: &ArrayValue) -> Value { - let mut json_array = Vec::with_capacity(array_value.values.len()); + // Sized by the values that will be pushed, as `attribute_capacity` does for maps + let mut json_array = Vec::with_capacity( + array_value + .values + .iter() + .filter(|value| value.value.is_some()) + .take(ATTRIBUTE_CAPACITY_HINT_MAX) + .count(), + ); for value in &array_value.values { if let Some(val) = &value.value { match val { @@ -162,7 +210,7 @@ fn collect_json_from_array_value(array_value: &ArrayValue) -> Value { } OtelValue::KvlistValue(kv_list) => { // Recursively collect JSON from nested key-value lists - let nested_json = collect_json_from_key_value_list(kv_list.clone()); + let nested_json = collect_json_from_key_value_list(kv_list); json_array.push(Value::Object(nested_json)); } OtelValue::StringValueStrindex(str_index) => { @@ -179,12 +227,13 @@ fn collect_json_from_array_value(array_value: &ArrayValue) -> Value { /// Recursively converts an OpenTelemetry KeyValueList into a JSON Map /// The function iterates through the key-value pairs in the list /// and collects their JSON representations into a single Map -fn collect_json_from_key_value_list(key_value_list: KeyValueList) -> Map { - let mut kv_list_json: Map = Map::with_capacity(key_value_list.values.len()); - for key_value in key_value_list.values { - if let Some(val) = key_value.value { - if let Some(val) = val.value { - insert_json_from_value(&mut kv_list_json, &key_value.key, val); +fn collect_json_from_key_value_list(key_value_list: &KeyValueList) -> Map { + let mut kv_list_json: Map = + Map::with_capacity(attribute_capacity(&key_value_list.values)); + for key_value in &key_value_list.values { + if let Some(val) = &key_value.value { + if let Some(val) = &val.value { + insert_json_from_ref(&mut kv_list_json, &key_value.key, val); } else { tracing::warn!("Key '{}' has no value in key-value list", key_value.key); } @@ -202,8 +251,8 @@ pub fn collect_json_from_values(values: &Option, key: &str) -> Map = Map::with_capacity(1); for value in values.iter() { - if let Some(value) = value.value.clone() { - insert_json_from_value(&mut value_json, key, value); + if let Some(value) = value.value.as_ref() { + insert_json_from_ref(&mut value_json, key, value); } } @@ -219,12 +268,13 @@ pub fn value_to_string(value: serde_json::Value) -> String { } pub fn flatten_attributes(attributes: &[KeyValue]) -> Map { - let mut attributes_json: Map = Map::with_capacity(attributes.len()); + let mut attributes_json: Map = + Map::with_capacity(attribute_capacity(attributes)); for attribute in attributes { - if let Some(value) = &attribute.value - && let Some(value) = value.value.clone() + if let Some(value) = attribute.value.as_ref() + && let Some(value) = value.value.as_ref() { - insert_json_from_value(&mut attributes_json, &attribute.key, value); + insert_json_from_ref(&mut attributes_json, &attribute.key, value); } } attributes_json @@ -273,12 +323,44 @@ pub fn attribute_capacity(attributes: &[KeyValue]) -> usize { .count() } +/// Inserts `attributes` into `map` like `insert_attributes`, for a map created +/// with room for `capacity` entries, `attribute_capacity(attributes)` of them for +/// these attributes. When the attributes make fewer entries than that (repeated +/// keys), the map is rebuilt with room for that many fewer. +/// +/// Resource, scope, span and metric maps are cloned into rows, or are rows, and +/// `IndexMap::clone` keeps the capacity, while `row_bytes` counts the entries: a +/// scope of 128 attributes with one key made every row of it hold about 10 times +/// what was counted. Attributes with distinct keys rebuild nothing. +pub fn insert_attributes_fitted( + map: &mut Map, + attributes: &[KeyValue], + capacity: usize, +) { + let counted = attribute_capacity(attributes); + let before = map.len(); + insert_attributes(map, attributes); + fit_map(map, capacity, counted, map.len().saturating_sub(before)); +} + +/// Rebuilds `map`, created with room for `capacity` entries of which `counted` +/// were for entries that only `added` turned out to make (repeated keys, or keys +/// its own fields already had), with room for that many fewer. Does nothing when +/// `added` is at least `counted`, so attributes with distinct keys rebuild nothing. +pub fn fit_map(map: &mut Map, capacity: usize, counted: usize, added: usize) { + if added < counted { + let mut fitted = Map::with_capacity(capacity.saturating_sub(counted - added)); + fitted.extend(std::mem::take(map)); + *map = fitted; + } +} + pub fn insert_attributes(map: &mut Map, attributes: &[KeyValue]) { for attribute in attributes { - if let Some(value) = &attribute.value - && let Some(value) = value.value.clone() + if let Some(value) = attribute.value.as_ref() + && let Some(value) = value.value.as_ref() { - insert_json_from_value(map, &attribute.key, value); + insert_json_from_ref(map, &attribute.key, value); } } } diff --git a/src/otel/protobuf_stream.rs b/src/otel/protobuf_stream.rs new file mode 100644 index 000000000..ee249651f --- /dev/null +++ b/src/otel/protobuf_stream.rs @@ -0,0 +1,737 @@ +/* + * Parseable Server (C) 2022 - 2025 Parseable, Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + */ + +//! Decodes an OTLP/HTTP protobuf export request one leaf record (`LogRecord`, +//! `Span`, `Metric`) at a time, instead of decoding the whole request first. +//! +//! The request, resource and scope levels are walked as prost walks them: the same +//! keys, wire type checks, recursion limit, unknown-field skipping and error +//! messages (each error gets the `Message.field` path the generated code would +//! push). A resource or scope level is read twice over its own bytes: first its +//! singular fields (`resource`, `scope`, `schema_url`) are merged as prost merges +//! them, so a field that occurs more than once ends up as whole-request decoding +//! leaves it whatever the field order, while its children are only stepped over; +//! then its children are visited in order. A child is decoded from the rest of the +//! body with the decode context prost would use for it where it occurs, so it fails +//! exactly as it fails in place. +//! +//! A request is read in two walks. [`outline`] walks only the levels above the +//! records and counts the records without decoding one, so a body whose framing +//! is broken there is refused before anything is staged. [`flatten_request`] then +//! walks it again and decodes every leaf record once, with +//! `prost::encoding::message::merge` as whole-request decoding decodes it, hands +//! its rows to the sink and drops it. A record whose decoded size could be over +//! [`max_record_bytes`] is measured first, and refused without being decoded when +//! it is over. + +use std::convert::Infallible; +use std::ops::Range; +use std::sync::atomic::{AtomicBool, Ordering}; + +use bytes::{Buf, Bytes}; +use opentelemetry_proto::tonic::common::v1::InstrumentationScope; +use opentelemetry_proto::tonic::logs::v1::LogRecord; +use opentelemetry_proto::tonic::metrics::v1::Metric; +use opentelemetry_proto::tonic::resource::v1::Resource; +use opentelemetry_proto::tonic::trace::v1::Span; +use prost::encoding::{ + DecodeContext, WireType, check_wire_type, decode_key, decode_varint, message, skip_field, + string, +}; +use prost::{DecodeError, Message}; +use serde_json::Map; + +use super::decoded_size::{Leaf, leaf_decoded_size, metric_points, needs_measuring}; +use super::logs::{log_record_row, resource_log_fields, scope_log_fields}; +use super::metrics::{ResourceMetricFields, metric_rows_into}; +use super::sink::RowSink; +use super::traces::{SpanParents, resource_span_fields, scope_span_fields, span_rows}; +use crate::utils::json::flatten::FlattenBudget; + +/// Most memory one leaf record may take once decoded, for a payload limit of +/// `max_payload` bytes: 16 bytes per payload byte. Realistic records decode to +/// 2.4-4.2 bytes per byte, exponential histograms with small buckets to 12.5; a +/// span of 2 million empty events decodes to 32 bytes per byte. +pub fn max_record_bytes(max_payload: usize) -> usize { + max_payload.saturating_mul(16) +} + +/// Why a body could not be read, or what the consumer of its records refused +#[derive(Debug)] +pub enum StreamError { + /// The body is not a valid request; the error prost gives for it + Decode(DecodeError), + /// A leaf record would take more than `limit` bytes once decoded + RecordTooLarge { leaf: Leaf, limit: usize }, + /// The consumer refused a record + Consumer(E), +} + +impl StreamError { + /// The same error, with a refusal of the consumer mapped by `f` + pub fn map_consumer(self, f: impl FnOnce(E) -> F) -> StreamError { + match self { + Self::Decode(e) => StreamError::Decode(e), + Self::RecordTooLarge { leaf, limit } => StreamError::RecordTooLarge { leaf, limit }, + Self::Consumer(e) => StreamError::Consumer(f(e)), + } + } +} + +impl StreamError { + /// The same error, as one of a consumer of any type + pub fn widen(self) -> StreamError { + self.map_consumer(|never| match never {}) + } +} + +/// The names prost's error messages use for the levels of one signal +pub struct Names { + request: &'static str, + resources: &'static str, + resource_level: &'static str, + scopes: &'static str, + scope_level: &'static str, + records: &'static str, +} + +pub const LOGS: Names = Names { + request: "ExportLogsServiceRequest", + resources: "resource_logs", + resource_level: "ResourceLogs", + scopes: "scope_logs", + scope_level: "ScopeLogs", + records: "log_records", +}; + +pub const TRACES: Names = Names { + request: "ExportTraceServiceRequest", + resources: "resource_spans", + resource_level: "ResourceSpans", + scopes: "scope_spans", + scope_level: "ScopeSpans", + records: "spans", +}; + +pub const METRICS: Names = Names { + request: "ExportMetricsServiceRequest", + resources: "resource_metrics", + resource_level: "ResourceMetrics", + scopes: "scope_metrics", + scope_level: "ScopeMetrics", + records: "metrics", +}; + +/// The signal of a protobuf body +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Signal { + Logs, + Metrics, + Traces, +} + +impl Signal { + fn names(self) -> &'static Names { + match self { + Self::Logs => &LOGS, + Self::Metrics => &METRICS, + Self::Traces => &TRACES, + } + } +} + +/// A leaf record type and how it is measured +pub trait LeafRecord: Message + Default { + const LEAF: Leaf; +} + +impl LeafRecord for LogRecord { + const LEAF: Leaf = Leaf::LogRecord; +} + +impl LeafRecord for Span { + const LEAF: Leaf = Leaf::Span; +} + +impl LeafRecord for Metric { + const LEAF: Leaf = Leaf::Metric; +} + +/// A length-delimited child: where it starts in the body (at its length prefix) +/// and the context prost would decode it with there. It is decoded from the rest +/// of the body, as prost decodes it: a broken length inside it can run past its end +/// before decoding fails, and fails the way it fails in place. +#[derive(Clone)] +struct Child { + start: usize, + prefix: usize, + len: usize, + ctx: DecodeContext, +} + +impl Child { + /// Steps over the child at the front of `buf`, which ends at `end` in the body, + /// failing like prost's `message::merge_repeated` on its framing + fn take( + wire_type: WireType, + buf: &mut impl Buf, + end: usize, + ctx: DecodeContext, + ) -> Result { + check_wire_type(WireType::LengthDelimited, wire_type)?; + let start = end - buf.remaining(); + let mut peek = buf.chunk(); + let contiguous = peek.len(); + let len = decode_varint(&mut peek)?; + let prefix = contiguous - peek.len(); + if len > (buf.remaining() - prefix) as u64 { + return Err(DecodeError::new("buffer underflow")); + } + buf.advance(prefix + len as usize); + Ok(Self { + start, + prefix, + len: len as usize, + ctx, + }) + } + + /// Decodes the child into `msg`, as prost decodes it where it occurs + fn merge(&self, body: &Bytes, msg: &mut M) -> Result<(), DecodeError> { + message::merge( + WireType::LengthDelimited, + msg, + &mut body.slice(self.start..), + self.ctx.clone(), + ) + } + + /// Where the encoding of the child, without its length prefix, is in the body + fn content(&self) -> Range { + self.start + self.prefix..self.start + self.prefix + self.len + } + + /// The encoding of the child, without its length prefix + fn body<'b>(&self, body: &'b [u8]) -> &'b [u8] { + &body[self.content()] + } +} + +fn push(mut error: DecodeError, message: &'static str, field: &'static str) -> DecodeError { + error.push(message, field); + error +} + +/// The singular fields of a resource or scope level, merged as prost merges them. +/// Its children (field 2) are only stepped over, which checks their framing. +struct Fields

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

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

Fields

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

{ + fn encode_raw(&self, _buf: &mut impl bytes::BufMut) { + unreachable!("only decoded") + } + + fn merge_field( + &mut self, + tag: u32, + wire_type: WireType, + buf: &mut impl Buf, + ctx: DecodeContext, + ) -> Result<(), DecodeError> { + if self.ctx.is_none() { + self.ctx = Some(ctx.clone()); + } + match tag { + 1 => message::merge( + wire_type, + self.parent.get_or_insert_with(Default::default), + buf, + ctx, + ) + .map_err(|e| push(e, self.message, self.parent_field)), + 2 => { + // Only the framing; `Child::take` needs no position for that + let end = buf.remaining(); + Child::take(wire_type, buf, end, ctx) + .map(drop) + .map_err(|e| push(e, self.message, self.children_field)) + } + 3 => string::merge(wire_type, &mut self.schema_url, buf, ctx) + .map_err(|e| push(e, self.message, "schema_url")), + _ => skip_field(wire_type, tag, buf, ctx), + } + } + + fn encoded_len(&self) -> usize { + 0 + } + + fn clear(&mut self) { + self.parent = None; + self.schema_url.clear(); + } +} + +/// Hands every child (fields numbered `tag`) of the level whose fields are +/// `body[range]` to `visit`, in order, stepping over its other fields as prost +/// does. `ctx` is the context prost decodes the fields of the level with; `path` +/// adds the field of the children to a framing error. +fn children( + body: &Bytes, + range: Range, + ctx: &DecodeContext, + tag: u32, + path: impl Fn(DecodeError) -> DecodeError, + visit: &mut dyn FnMut(Child) -> Result<(), StreamError>, +) -> Result<(), StreamError> { + let end = range.end; + let mut buf = &body[range]; + while buf.has_remaining() { + let (field, wire_type) = decode_key(&mut buf).map_err(StreamError::Decode)?; + if field == tag { + let child = Child::take(wire_type, &mut buf, end, ctx.clone()) + .map_err(|e| StreamError::Decode(path(e)))?; + visit(child)?; + } else { + skip_field(wire_type, field, &mut buf, ctx.clone()).map_err(StreamError::Decode)?; + } + } + Ok(()) +} + +/// What a request is made of, in the order of the body +enum Item { + /// A resource level starts: its `resource` and `schema_url` + Resource(Option, String), + /// A scope level of the current resource starts + Scope(Option, String), + /// A leaf record of the current scope, not decoded + Record(Child), + /// The current resource level ends + ResourceEnd, +} + +/// Walks the levels of the request `body` above its leaf records and hands their +/// items to `consume`, in order. Fails with prost's error where one of those levels +/// is broken (a record is only stepped over, so its framing is checked but not its +/// content), or with the first refusal of `consume`. +fn walk( + body: &Bytes, + names: &'static Names, + consume: &mut dyn FnMut(Item) -> Result<(), StreamError>, +) -> Result<(), StreamError> { + let in_request = |e| push(e, names.request, names.resources); + let in_resource = |e| in_request(push(e, names.resource_level, names.scopes)); + let in_scope = |e| in_resource(push(e, names.scope_level, names.records)); + // `Message::merge` decodes the fields of a request with the default context + let top = DecodeContext::default(); + children(body, 0..body.len(), &top, 1, in_request, &mut |resource| { + let mut level = Fields::::new(names.resource_level, "resource", names.scopes); + resource + .merge(body, &mut level) + .map_err(|e| StreamError::Decode(in_request(e)))?; + consume(Item::Resource( + level.parent.take(), + std::mem::take(&mut level.schema_url), + ))?; + if let Some(ctx) = &level.ctx { + children( + body, + resource.content(), + ctx, + 2, + in_resource, + &mut |scope| { + let mut level = Fields::::new( + names.scope_level, + "scope", + names.records, + ); + scope + .merge(body, &mut level) + .map_err(|e| StreamError::Decode(in_resource(e)))?; + consume(Item::Scope( + level.parent.take(), + std::mem::take(&mut level.schema_url), + ))?; + match &level.ctx { + Some(ctx) => { + children(body, scope.content(), ctx, 2, in_scope, &mut |record| { + consume(Item::Record(record)) + }) + } + None => Ok(()), + } + }, + )?; + } + consume(Item::ResourceEnd) + }) +} + +/// What [`outline`] found in a request +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct Outline { + /// Leaf records (log records, spans or metrics) of the request + pub records: u64, +} + +/// Reads the levels of the request `body` above its leaf records, without decoding +/// a record, and counts the records. Needs no limit, so a body that is not a +/// request of the signal at all is refused before anything else is looked at. +/// The error is the first break met in those levels; [`refusal`] turns it into +/// the error whole-request decoding gives. +pub fn outline(body: &Bytes, signal: Signal) -> Result { + let mut outline = Outline::default(); + walk::(body, signal.names(), &mut |item| { + if let Item::Record(_) = item { + outline.records += 1; + } + Ok(()) + }) + .map_err(|error| match error { + StreamError::Decode(error) => error, + StreamError::RecordTooLarge { .. } => unreachable!("no record is measured"), + StreamError::Consumer(never) => match never {}, + })?; + Ok(outline) +} + +/// The error to refuse a body with that [`outline`] found broken (`error`): the one +/// whole-request decoding gives, found by decoding the body in wire order one record +/// at a time (`first_error`), or a record over the cap met before the break. +/// `max_record` is asked for only once a record is met, so a body that is not a +/// request is refused without it. +pub fn refusal( + body: &Bytes, + signal: Signal, + error: DecodeError, + max_record: impl FnOnce() -> usize, +) -> StreamError { + let found = match first_error(body, signal, None) { + FirstError::NeedsCap => first_error(body, signal, Some(max_record())), + found => found, + }; + match found { + FirstError::Found(found) => found, + // Not reached: a body broken above its records does not decode + FirstError::None | FirstError::NeedsCap => StreamError::Decode(error), + } +} + +/// Decodes the leaf record `child` of `body`, refusing it before it is decoded if +/// it would take more than `max_record` bytes +fn decode_leaf( + body: &Bytes, + child: &Child, + names: &'static Names, + max_record: usize, +) -> Result> { + let encoded = child.body(body); + if needs_measuring(encoded.len(), L::LEAF, max_record) + && leaf_decoded_size(encoded, L::LEAF) > max_record + { + return Err(StreamError::RecordTooLarge { + leaf: L::LEAF, + limit: max_record, + }); + } + let mut record = L::default(); + child.merge(body, &mut record).map_err(|e| { + let e = push(e, names.scope_level, names.records); + let e = push(e, names.resource_level, names.scopes); + StreamError::Decode(push(e, names.request, names.resources)) + })?; + Ok(record) +} + +/// Hands the rows of the request `body` to `sink`, decoding one record at a time: +/// the same rows, in the same order, as decoding the whole request and flattening +/// it. `body` must have passed [`outline`]; then the only errors are those of a +/// record (it does not decode, or is over `max_record`) and refusals of `sink`, +/// and the rows of every record before it were handed over. +pub fn flatten_request( + body: &Bytes, + signal: Signal, + max_record: usize, + budget: &mut FlattenBudget, + flatten_exemplars: bool, + sink: &mut S, +) -> Result<(), StreamError> { + let names = signal.names(); + match signal { + Signal::Logs => { + let (mut resource_fields, mut scope_fields) = (Map::new(), Map::new()); + walk(body, names, &mut |item| { + match item { + Item::Resource(resource, url) => { + resource_fields = resource_log_fields(resource.as_ref(), &url) + } + Item::Scope(scope, url) => { + scope_fields = scope_log_fields(scope.as_ref(), &url) + } + Item::Record(child) => { + let record: LogRecord = decode_leaf(body, &child, names, max_record)?; + let row = log_record_row(&record, &scope_fields, &resource_fields, budget) + .map_err(|e| StreamError::Consumer(e.into()))?; + sink.row(row).map_err(StreamError::Consumer)?; + sink.record_end(); + } + Item::ResourceEnd => {} + } + Ok(()) + }) + } + Signal::Traces => { + let (mut resource_fields, mut scope_fields) = (Map::new(), Map::new()); + let mut scope_url = String::new(); + walk(body, names, &mut |item| { + match item { + Item::Resource(resource, url) => { + resource_fields = resource_span_fields(resource.as_ref(), &url) + } + Item::Scope(scope, url) => { + scope_fields = scope_span_fields(scope.as_ref()); + scope_url = url; + } + Item::Record(child) => { + let span: Span = decode_leaf(body, &child, names, max_record)?; + span_rows( + &span, + &SpanParents { + scope_fields: &scope_fields, + scope_schema_url: &scope_url, + resource_fields: &resource_fields, + }, + sink, + ) + .map_err(StreamError::Consumer)? + } + Item::ResourceEnd => {} + } + Ok(()) + }) + } + Signal::Metrics => { + let mut resource: Option = None; + let mut envelope = Map::new(); + let mut latest: Option = None; + walk(body, names, &mut |item| { + match item { + Item::Resource(r, url) => { + resource = Some(ResourceMetricFields::new(r.as_ref(), &url)); + latest = None; + } + Item::Scope(scope, url) => { + envelope = resource + .as_ref() + .expect("a scope is inside a resource") + .scope_envelope(scope.as_ref(), &url); + } + Item::Record(child) => { + let metric: Metric = decode_leaf(body, &child, names, max_record)?; + metric_rows_into(&metric, &envelope, flatten_exemplars, &mut latest, sink) + .map_err(StreamError::Consumer)? + } + Item::ResourceEnd => { + if let Some(target) = resource + .take() + .and_then(|resource| resource.target_info(latest.take())) + { + sink.row(target).map_err(StreamError::Consumer)?; + } + } + } + Ok(()) + }) + } + } +} + +/// Data points of the metrics request `body`, counted from the wire without +/// decoding a metric (see `metric_points`). For the rejected count of a partial +/// success, so only read after a failure. `body` must have passed [`outline`]. +pub fn count_points(body: &Bytes) -> u64 { + let mut points = 0u64; + let _ = walk::(body, &METRICS, &mut |item| { + if let Item::Record(child) = item { + points += metric_points(child.body(body)); + } + Ok(()) + }); + points +} + +/// One level of `first_error`'s walk: decodes everything in wire order, as prost +/// does, keeping nothing but one record at a time +struct WireOrder<'a> { + names: &'static Names, + leaf: Leaf, + depth: u8, + /// `None` until the cap on one record is known: the walk stops at the first record + max_record: Option, + stopped: &'a AtomicBool, +} + +impl WireOrder<'_> { + fn child(&self) -> WireOrder<'_> { + WireOrder { + names: self.names, + leaf: self.leaf, + depth: self.depth + 1, + max_record: self.max_record, + stopped: self.stopped, + } + } + + fn merge_leaf( + &self, + wire_type: WireType, + buf: &mut impl Buf, + ctx: DecodeContext, + ) -> Result<(), DecodeError> { + match self.leaf { + Leaf::LogRecord => message::merge(wire_type, &mut LogRecord::default(), buf, ctx), + Leaf::Span => message::merge(wire_type, &mut Span::default(), buf, ctx), + Leaf::Metric => message::merge(wire_type, &mut Metric::default(), buf, ctx), + } + } +} + +impl Message for WireOrder<'_> { + fn encode_raw(&self, _buf: &mut impl bytes::BufMut) { + unreachable!("only decoded") + } + + fn merge_field( + &mut self, + tag: u32, + wire_type: WireType, + buf: &mut impl Buf, + ctx: DecodeContext, + ) -> Result<(), DecodeError> { + let names = self.names; + match (self.depth, tag) { + (0, 1) => message::merge(wire_type, &mut self.child(), buf, ctx) + .map_err(|e| push(e, names.request, names.resources)), + (1, 1) => message::merge(wire_type, &mut Resource::default(), buf, ctx) + .map_err(|e| push(e, names.resource_level, "resource")), + (1, 2) => message::merge(wire_type, &mut self.child(), buf, ctx) + .map_err(|e| push(e, names.resource_level, names.scopes)), + (2, 1) => message::merge(wire_type, &mut InstrumentationScope::default(), buf, ctx) + .map_err(|e| push(e, names.scope_level, "scope")), + (2, 2) => { + let Some(max_record) = self.max_record else { + self.stopped.store(true, Ordering::Relaxed); + return Err(DecodeError::new("stopped at the first record")); + }; + // Measured where the framing allows, then decoded in place + let mut peek = buf.chunk(); + if wire_type == WireType::LengthDelimited + && let Ok(len) = decode_varint(&mut peek) + && len <= peek.len() as u64 + && needs_measuring(len as usize, self.leaf, max_record) + && leaf_decoded_size(&peek[..len as usize], self.leaf) > max_record + { + self.stopped.store(true, Ordering::Relaxed); + return Err(DecodeError::new("record over the decoded size cap")); + } + self.merge_leaf(wire_type, buf, ctx) + .map_err(|e| push(e, names.scope_level, names.records)) + } + (1 | 2, 3) => { + let level = if self.depth == 1 { + names.resource_level + } else { + names.scope_level + }; + string::merge(wire_type, &mut String::new(), buf, ctx) + .map_err(|e| push(e, level, "schema_url")) + } + _ => skip_field(wire_type, tag, buf, ctx), + } + } + + fn encoded_len(&self) -> usize { + 0 + } + + fn clear(&mut self) {} +} + +/// What `first_error` found +enum FirstError { + /// The error whole-request decoding gives, or a record over the cap before it + Found(StreamError), + /// The walk met a record and needs the cap on one record to go on + NeedsCap, + /// The body decodes + None, +} + +/// The error whole-request decoding gives for `body`, found by decoding it in wire +/// order one record at a time (`walk` reads each level whole before its children, +/// so where a body is broken in more than one place it can meet another break first) +fn first_error(body: &Bytes, signal: Signal, max_record: Option) -> FirstError { + let stopped = AtomicBool::new(false); + let leaf = match signal { + Signal::Logs => Leaf::LogRecord, + Signal::Traces => Leaf::Span, + Signal::Metrics => Leaf::Metric, + }; + let mut walk = WireOrder { + names: signal.names(), + leaf, + depth: 0, + max_record, + stopped: &stopped, + }; + match walk.merge(body.clone()) { + Ok(()) => FirstError::None, + Err(_) if stopped.load(Ordering::Relaxed) => match max_record { + None => FirstError::NeedsCap, + Some(limit) => FirstError::Found(StreamError::RecordTooLarge { leaf, limit }), + }, + Err(error) => FirstError::Found(StreamError::Decode(error)), + } +} diff --git a/src/otel/realistic_tests.rs b/src/otel/realistic_tests.rs new file mode 100644 index 000000000..7aab1e7b3 --- /dev/null +++ b/src/otel/realistic_tests.rs @@ -0,0 +1,690 @@ +/* + * Parseable Server (C) 2022 - 2025 Parseable, Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + */ + +//! Requests shaped like real collector traffic, at the default payload limit: +//! what their rows hold per body byte (`row_bytes`, the unit of the running total +//! the expansion cap counts while staging; the numbers behind `EXPANSION_FACTOR`), +//! and that the expansion cap accepts every one of them. Nothing here touches +//! `PARSEABLE`. `OTLP_DUMP_DIR=

` makes the ignored `dump_realistic_bodies` +//! write the bodies for end-to-end checks against a server. + +use opentelemetry_proto::tonic::collector::logs::v1::ExportLogsServiceRequest; +use opentelemetry_proto::tonic::collector::metrics::v1::ExportMetricsServiceRequest; +use opentelemetry_proto::tonic::collector::trace::v1::ExportTraceServiceRequest; +use opentelemetry_proto::tonic::common::v1::{AnyValue, InstrumentationScope, KeyValue, any_value}; +use opentelemetry_proto::tonic::logs::v1::{LogRecord, ResourceLogs, ScopeLogs}; +use opentelemetry_proto::tonic::metrics::v1::{ + Exemplar, ExponentialHistogram, ExponentialHistogramDataPoint, Gauge, Histogram, + HistogramDataPoint, Metric, NumberDataPoint, ResourceMetrics, ScopeMetrics, Sum, exemplar, + exponential_histogram_data_point::Buckets, metric, number_data_point, +}; +use opentelemetry_proto::tonic::resource::v1::Resource; +use opentelemetry_proto::tonic::trace::v1::{ResourceSpans, ScopeSpans, Span, Status, span}; +use prost::Message; + +use serde_json::{Map, Value}; + +use super::protobuf_stream::{Signal, flatten_request, max_record_bytes, outline}; +use super::sink::{ + EXPANSION_CEILING_FACTOR, EXPANSION_FACTOR, MIN_EXPANDED_BYTES, RowSink, max_expanded_bytes, + row_bytes, +}; +use crate::utils::json::flatten::{FlattenBudget, FlattenLimits, JsonFlattenError}; + +/// `P_MAX_EVENT_PAYLOAD_SIZE` default +const PAYLOAD: usize = 10 * 1024 * 1024; + +fn kv(key: &str, value: any_value::Value) -> KeyValue { + KeyValue { + key: key.into(), + value: Some(AnyValue { value: Some(value) }), + ..Default::default() + } +} + +fn s(key: &str, value: &str) -> KeyValue { + kv(key, any_value::Value::StringValue(value.into())) +} + +/// What the Kubernetes attributes processor and an SDK add to a resource +fn k8s_resource() -> Option { + Some(Resource { + attributes: vec![ + s("service.name", "checkout"), + s("service.namespace", "shop"), + s("service.version", "1.42.0"), + s( + "service.instance.id", + "6f1c0a52-8a4e-4c21-9a07-3b3c4e9b0d51", + ), + s("deployment.environment.name", "production"), + s("telemetry.sdk.name", "opentelemetry"), + s("telemetry.sdk.language", "java"), + s("telemetry.sdk.version", "1.44.1"), + s( + "telemetry.distro.name", + "opentelemetry-java-instrumentation", + ), + s("telemetry.distro.version", "2.10.0"), + s("host.name", "ip-10-0-12-34.eu-west-1.compute.internal"), + s("host.arch", "amd64"), + s("os.type", "linux"), + s("os.description", "Linux 6.1.112-124.190.amzn2023.x86_64"), + s("process.runtime.name", "OpenJDK Runtime Environment"), + s("process.runtime.version", "21.0.5+11-LTS"), + s("process.pid", "1"), + s( + "container.id", + "3c5a2d0f9b8e7a6c5d4e3f2a1b0c9d8e7f6a5b4c3d2e1f0a9b8c7d6e5f4a3b2c", + ), + s("container.name", "checkout"), + s("container.image.name", "registry.example.com/shop/checkout"), + s("container.image.tag", "1.42.0"), + s("k8s.cluster.name", "prod-eu-west-1"), + s("k8s.namespace.name", "shop"), + s("k8s.node.name", "ip-10-0-12-34.eu-west-1.compute.internal"), + s("k8s.pod.name", "checkout-7d9c8b6f5-x2x9q"), + s("k8s.pod.uid", "0b6e2c1a-4f3d-4e5b-8a9c-7d6e5f4a3b2c"), + s("k8s.deployment.name", "checkout"), + s("k8s.replicaset.name", "checkout-7d9c8b6f5"), + s("cloud.provider", "aws"), + s("cloud.region", "eu-west-1"), + ], + ..Default::default() + }) +} + +fn minimal_resource() -> Option { + Some(Resource { + attributes: vec![s("service.name", "checkout")], + ..Default::default() + }) +} + +fn scope(name: &str) -> Option { + Some(InstrumentationScope { + name: name.into(), + version: "2.10.0".into(), + ..Default::default() + }) +} + +const T0: u64 = 1_700_000_000_000_000_000; + +fn logs(resource: Option, records: Vec) -> ExportLogsServiceRequest { + ExportLogsServiceRequest { + resource_logs: vec![ResourceLogs { + resource, + scope_logs: vec![ScopeLogs { + scope: scope("com.example.checkout"), + log_records: records, + schema_url: String::new(), + }], + schema_url: "https://opentelemetry.io/schemas/1.24.0".into(), + }], + } +} + +fn app_log(i: usize) -> LogRecord { + LogRecord { + time_unix_nano: T0 + i as u64, + observed_time_unix_nano: T0 + 1 + i as u64, + severity_number: 9, + severity_text: "INFO".into(), + body: Some(AnyValue { + value: Some(any_value::Value::StringValue(format!( + "GET /api/v1/items/{i} completed with 200 in 12 ms" + ))), + }), + attributes: vec![ + s("code.function", "handle"), + s("thread.name", "http-nio-8080-exec-7"), + kv("http.response.status_code", any_value::Value::IntValue(200)), + ], + trace_id: vec![0xab; 16], + span_id: vec![0xcd; 8], + flags: 1, + ..Default::default() + } +} + +/// The smallest realistic log record: a time, a severity and a two-byte body +fn short_log(i: usize) -> LogRecord { + LogRecord { + time_unix_nano: T0 + i as u64, + severity_number: 9, + body: Some(AnyValue { + value: Some(any_value::Value::StringValue("ok".into())), + }), + ..Default::default() + } +} + +fn traces(resource: Option, spans: Vec) -> ExportTraceServiceRequest { + ExportTraceServiceRequest { + resource_spans: vec![ResourceSpans { + resource, + scope_spans: vec![ScopeSpans { + scope: scope("io.opentelemetry.tomcat-10.0"), + spans, + schema_url: String::new(), + }], + schema_url: String::new(), + }], + } +} + +fn server_span(i: usize) -> Span { + Span { + trace_id: vec![0xab; 16], + span_id: (i as u64).to_be_bytes().to_vec(), + parent_span_id: vec![0xef; 8], + name: "GET /api/v1/items/{id}".into(), + kind: 2, + start_time_unix_nano: T0 + i as u64, + end_time_unix_nano: T0 + 12_000_000 + i as u64, + attributes: vec![ + s("http.request.method", "GET"), + s("url.path", &format!("/api/v1/items/{i}")), + kv("http.response.status_code", any_value::Value::IntValue(200)), + s("server.address", "checkout.shop.svc.cluster.local"), + ], + status: Some(Status::default()), + ..Default::default() + } +} + +/// The smallest realistic span: ids, a name and its times +fn bare_span(i: usize) -> Span { + Span { + trace_id: vec![0xab; 16], + span_id: (i as u64).to_be_bytes().to_vec(), + name: "query".into(), + start_time_unix_nano: T0 + i as u64, + end_time_unix_nano: T0 + 1000 + i as u64, + ..Default::default() + } +} + +/// A span with an exception event and a link, as instrumentations record them +fn span_with_event(i: usize) -> Span { + Span { + events: vec![span::Event { + time_unix_nano: T0 + 5 + i as u64, + name: "exception".into(), + attributes: vec![ + s("exception.type", "java.io.IOException"), + s("exception.message", "Connection reset by peer"), + ], + ..Default::default() + }], + links: vec![span::Link { + trace_id: vec![0x12; 16], + span_id: vec![0x34; 8], + ..Default::default() + }], + ..server_span(i) + } +} + +fn metrics(resource: Option, metrics: Vec) -> ExportMetricsServiceRequest { + ExportMetricsServiceRequest { + resource_metrics: vec![ResourceMetrics { + resource, + scope_metrics: vec![ScopeMetrics { + scope: scope("io.opentelemetry.runtime-telemetry-java17"), + metrics, + schema_url: String::new(), + }], + schema_url: String::new(), + }], + } +} + +fn sum_points(points: usize) -> Vec { + vec![Metric { + name: "jvm.memory.used".into(), + description: "Measure of memory used.".into(), + unit: "By".into(), + data: Some(metric::Data::Sum(Sum { + data_points: (0..points) + .map(|i| NumberDataPoint { + attributes: vec![ + s("jvm.memory.pool.name", "G1 Eden Space"), + s("jvm.memory.type", "heap"), + ], + start_time_unix_nano: T0, + time_unix_nano: T0 + 60_000_000_000 + i as u64, + value: Some(number_data_point::Value::AsInt(123_456_789 + i as i64)), + ..Default::default() + }) + .collect(), + aggregation_temporality: 2, + is_monotonic: false, + })), + ..Default::default() + }] +} + +/// The smallest realistic data point: a time and a value +fn bare_gauge_points(points: usize) -> Vec { + vec![Metric { + name: "up".into(), + data: Some(metric::Data::Gauge(Gauge { + data_points: (0..points) + .map(|i| NumberDataPoint { + time_unix_nano: T0 + i as u64, + value: Some(number_data_point::Value::AsDouble(1.0)), + ..Default::default() + }) + .collect(), + })), + ..Default::default() + }] +} + +/// Explicit-bucket histograms with the SDK's 16 default bounds and one exemplar +fn histogram_points(points: usize) -> Vec { + vec![Metric { + name: "http.server.request.duration".into(), + unit: "s".into(), + data: Some(metric::Data::Histogram(Histogram { + data_points: (0..points) + .map(|i| HistogramDataPoint { + attributes: vec![ + s("http.request.method", "GET"), + s("http.route", "/api/v1/items/{id}"), + kv("http.response.status_code", any_value::Value::IntValue(200)), + ], + start_time_unix_nano: T0, + time_unix_nano: T0 + 60_000_000_000 + i as u64, + count: 1000, + sum: Some(12.5), + bucket_counts: (0..16).map(|b| b * 3).collect(), + explicit_bounds: vec![ + 0.0, 0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1.0, 2.5, 5.0, + 7.5, 10.0, + ], + exemplars: vec![Exemplar { + time_unix_nano: T0 + i as u64, + trace_id: vec![0xab; 16], + span_id: vec![0xcd; 8], + value: Some(exemplar::Value::AsDouble(0.012)), + ..Default::default() + }], + min: Some(0.001), + max: Some(1.2), + ..Default::default() + }) + .collect(), + aggregation_temporality: 2, + })), + ..Default::default() + }] +} + +/// Exponential histograms with 160 small buckets on each side (the SDK maximum) +fn exp_histogram_points(points: usize) -> Vec { + vec![Metric { + name: "http.server.duration".into(), + data: Some(metric::Data::ExponentialHistogram(ExponentialHistogram { + data_points: (0..points) + .map(|i| ExponentialHistogramDataPoint { + attributes: vec![s("http.route", "/api/v1/items")], + start_time_unix_nano: T0, + time_unix_nano: T0 + i as u64, + count: 1000, + sum: Some(12.5), + scale: 3, + positive: Some(Buckets { + offset: -10, + bucket_counts: (0..160).map(|b| b % 100).collect(), + }), + negative: Some(Buckets { + offset: -10, + bucket_counts: (0..160).map(|b| b % 7).collect(), + }), + ..Default::default() + }) + .collect(), + aggregation_temporality: 2, + })), + ..Default::default() + }] +} + +/// One realistic request, built to fill most of the payload limit +pub(crate) struct Shape { + pub name: &'static str, + pub signal: &'static str, + pub body: Vec, + /// The same request with 1, 10 and 100 records + pub small: Vec>, +} + +/// What the rows of a request add up to, as staging counts them +#[derive(Debug, Default, Clone, Copy)] +pub(crate) struct Totals { + pub rows: u64, + /// `row_bytes` of every row: what the expansion cap counts + pub bytes: u64, + pub records: u64, + pub points: u64, +} + +impl RowSink for Totals { + type Error = JsonFlattenError; + + fn row(&mut self, row: Map) -> Result<(), Self::Error> { + self.rows += 1; + self.bytes += row_bytes(&row) as u64; + Ok(()) + } + + fn point(&mut self, row: Map) -> Result<(), Self::Error> { + self.points += 1; + self.row(row) + } + + fn record_end(&mut self) { + self.records += 1; + } +} + +/// The totals of the protobuf `body` of `signal`, read as ingestion reads it +pub(crate) fn totals(signal: &str, body: &[u8]) -> Totals { + let signal = match signal { + "logs" => Signal::Logs, + "traces" => Signal::Traces, + "metrics" => Signal::Metrics, + other => panic!("{other}"), + }; + let body = bytes::Bytes::copy_from_slice(body); + outline(&body, signal).unwrap(); + let mut totals = Totals::default(); + flatten_request( + &body, + signal, + max_record_bytes(PAYLOAD), + &mut FlattenBudget::new(FlattenLimits::DEFAULT), + false, + &mut totals, + ) + .unwrap(); + totals +} + +/// Records of `one` bytes each that fit in `PAYLOAD`, with room for framing +fn fitting(one: usize) -> usize { + (PAYLOAD - 64 * 1024) / one +} + +fn shape( + name: &'static str, + signal: &'static str, + build: impl Fn(usize) -> M, +) -> Shape { + let probe = build(1000).encoded_len(); + let mut n = fitting(probe.div_ceil(1000)); + let mut request = build(n); + // Records can grow with their index + while request.encoded_len() > PAYLOAD - 16 * 1024 { + n = n * 99 / 100; + request = build(n); + } + let body = request.encode_to_vec(); + let small = [1, 10, 100] + .into_iter() + .map(|n| build(n).encode_to_vec()) + .collect(); + Shape { + name, + signal, + body, + small, + } +} + +pub(crate) fn shapes() -> Vec { + vec![ + shape("logs, 30 k8s resource attributes", "logs", |n| { + logs(k8s_resource(), (0..n).map(app_log).collect()) + }), + shape("logs, service.name only", "logs", |n| { + logs(minimal_resource(), (0..n).map(app_log).collect()) + }), + shape( + "logs, short records (time, severity, body \"ok\")", + "logs", + |n| logs(None, (0..n).map(short_log).collect()), + ), + shape( + "logs, short records, 30 k8s resource attributes", + "logs", + |n| logs(k8s_resource(), (0..n).map(short_log).collect()), + ), + shape("traces, 30 k8s resource attributes", "traces", |n| { + traces(k8s_resource(), (0..n).map(server_span).collect()) + }), + shape("traces, service.name only", "traces", |n| { + traces(minimal_resource(), (0..n).map(server_span).collect()) + }), + shape("traces, bare spans (ids, name, times)", "traces", |n| { + traces(minimal_resource(), (0..n).map(bare_span).collect()) + }), + shape( + "traces, bare spans, 30 k8s resource attributes", + "traces", + |n| traces(k8s_resource(), (0..n).map(bare_span).collect()), + ), + shape("traces, an event and a link per span, k8s", "traces", |n| { + traces(k8s_resource(), (0..n).map(span_with_event).collect()) + }), + shape( + "metrics, sum points, 30 k8s resource attributes", + "metrics", + |n| metrics(k8s_resource(), sum_points(n)), + ), + shape("metrics, sum points, service.name only", "metrics", |n| { + metrics(minimal_resource(), sum_points(n)) + }), + shape("metrics, bare gauge points (time, value)", "metrics", |n| { + metrics(minimal_resource(), bare_gauge_points(n)) + }), + shape( + "metrics, bare gauge points, 30 k8s resource attributes", + "metrics", + |n| metrics(k8s_resource(), bare_gauge_points(n)), + ), + shape( + "metrics, histograms with an exemplar, k8s", + "metrics", + |n| metrics(k8s_resource(), histogram_points(n)), + ), + shape( + "metrics, exponential histograms, 160 buckets", + "metrics", + |n| metrics(minimal_resource(), exp_histogram_points(n)), + ), + ] +} + +/// Every realistic shape at the payload limit is under the expansion cap for its +/// body, counted as staging counts it: the `row_bytes` of every row. There the +/// ceiling of the cap decides, and leaves at least 2x headroom. The same shape +/// with 1, 10 and 100 records, and with as many records as fill a quarter of the +/// payload limit (counted from the rows of the full body, which all hold about +/// the same), has at least 8x. +#[test] +fn realistic_requests_at_the_payload_limit_are_under_the_expansion_cap() { + use rayon::prelude::*; + let mut worst: f64 = 0.0; + // Flattened at once: a few seconds each in a debug build + let measured: Vec<(Shape, Totals)> = shapes() + .into_par_iter() + .map(|shape| { + let totals = totals(shape.signal, &shape.body); + (shape, totals) + }) + .collect(); + for (shape, totals) in measured { + let cap = max_expanded_bytes(shape.body.len(), PAYLOAD); + let ratio = totals.bytes as f64 / shape.body.len() as f64; + worst = worst.max(ratio); + println!( + "EXPANSION {}: body {:.2} MiB, {} records, {} rows, {:.0} row bytes per row, {:.1} row bytes per body byte ({:.0}% of the cap)", + shape.name, + shape.body.len() as f64 / (1024.0 * 1024.0), + totals.records, + totals.rows, + totals.bytes as f64 / totals.rows as f64, + ratio, + 100.0 * totals.bytes as f64 / cap as f64 + ); + assert!( + totals.bytes.saturating_mul(2) <= cap, + "{} is under 2x headroom at the payload limit", + shape.name + ); + // A quarter of the payload limit of the same records: the factor decides + let quarter = (PAYLOAD / 4) as u64; + let quarter_bytes = + (totals.bytes as u128 * quarter as u128 / shape.body.len() as u128) as u64; + assert!( + quarter_bytes.saturating_mul(8) <= max_expanded_bytes(PAYLOAD / 4, PAYLOAD), + "{} is under 8x headroom at a quarter of the payload limit", + shape.name + ); + for body in &shape.small { + let small = self::totals(shape.signal, body); + let ratio = small.bytes as f64 / body.len() as f64; + println!( + "EXPANSION {}, {} records: body {} B, {} row bytes, {ratio:.1} row bytes per body byte", + shape.name, + small.records, + body.len(), + small.bytes + ); + assert!( + small.bytes.saturating_mul(8) <= max_expanded_bytes(body.len(), PAYLOAD), + "{} with {} records", + shape.name, + small.records + ); + } + } + println!( + "EXPANSION worst {worst:.1} row bytes per body byte, cap {EXPANSION_FACTOR} per body byte, at least {MIN_EXPANDED_BYTES}, at most {EXPANSION_CEILING_FACTOR} per byte of the payload limit" + ); +} + +/// The request that copies a 15 KB resource into empty records of two bytes each: +/// half a MiB of protobuf +fn copied_resource_over_empty_records() -> ExportLogsServiceRequest { + let resource = Some(Resource { + attributes: (0..500) + .map(|i| s(&format!("attribute.{i:03}"), "value-0123456789")) + .collect(), + ..Default::default() + }); + logs(resource, vec![LogRecord::default(); 1 << 18]) +} + +/// Copied fields that no collector sends: a 15 KB resource over empty records of +/// two bytes each, which expand to tens of GiB of rows, pass the expansion cap. +/// Counted from the rows of the first records (they all hold the same), not by +/// building all of them. +#[test] +fn copied_fields_over_tiny_records_are_over_the_expansion_cap() { + let request = copied_resource_over_empty_records(); + let records = request.resource_logs[0].scope_logs[0].log_records.len() as u64; + let mut first = request.clone(); + first.resource_logs[0].scope_logs[0] + .log_records + .truncate(1000); + let totals = totals("logs", &first.encode_to_vec()); + let bytes = totals.bytes / 1000 * records; + println!( + "EXPANSION copied resource: {records} records, {:.0} row bytes each, {:.1} GiB of rows", + totals.bytes as f64 / 1000.0, + bytes as f64 / (1u64 << 30) as f64 + ); + assert!(request.encoded_len() <= PAYLOAD); + assert!(bytes > max_expanded_bytes(request.encoded_len(), PAYLOAD)); +} + +/// Writes the body of every shape to `OTLP_DUMP_DIR`, named after its signal +/// and position, for end-to-end checks against a server +#[test] +#[ignore = "writes request bodies for an end-to-end check"] +fn dump_realistic_bodies() { + let dir = std::env::var("OTLP_DUMP_DIR").expect("OTLP_DUMP_DIR"); + let mut index = String::new(); + let mut write = |file: String, signal: &str, name: &str, body: &[u8]| { + let totals = totals(signal, body); + std::fs::write(format!("{dir}/{file}"), body).unwrap(); + index.push_str(&format!( + "{file}\t{signal}\t{}\t{}\t{name}\n", + totals.records, totals.points + )); + }; + for (i, shape) in shapes().into_iter().enumerate() { + let file = format!("{i:02}-{}.pb", shape.signal); + write(file, shape.signal, shape.name, &shape.body); + } + // Crafted: one span of 2 million empty events (4 MiB), 400k empty spans (0.8 MB) + let events = traces( + None, + vec![Span { + events: vec![span::Event::default(); 1 << 21], + ..Default::default() + }], + ); + write( + "20-traces.pb".into(), + "traces", + "one span of 2 million empty events", + &events.encode_to_vec(), + ); + let spans = traces(None, vec![Span::default(); 400_000]); + write( + "21-traces.pb".into(), + "traces", + "400k empty spans", + &spans.encode_to_vec(), + ); + // Requests of 100 records, as an SDK or a collector with a small batch sends them + let small: [(&str, Vec); 3] = [ + ( + "logs", + logs(k8s_resource(), (0..100).map(app_log).collect()).encode_to_vec(), + ), + ( + "traces", + traces(k8s_resource(), (0..100).map(server_span).collect()).encode_to_vec(), + ), + ( + "metrics", + metrics(k8s_resource(), sum_points(100)).encode_to_vec(), + ), + ]; + for (signal, body) in small { + std::fs::write(format!("{dir}/small-{signal}.pb"), body).unwrap(); + } + std::fs::write(format!("{dir}/index.tsv"), index).unwrap(); +} diff --git a/src/otel/regression_tests.rs b/src/otel/regression_tests.rs new file mode 100644 index 000000000..3f4f6745c --- /dev/null +++ b/src/otel/regression_tests.rs @@ -0,0 +1,477 @@ +/* + * Parseable Server (C) 2022 - 2025 Parseable, Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + */ + +//! Regression tests for what two reviews of chunked OTLP ingestion found: the +//! memory of rows whose shared maps were sized by repeated attribute keys, and +//! the memory of walking a body of millions of empty resource or scope levels. +//! Measured with the test allocator (layout bytes, calling thread). Each test +//! prints `REGRESSION : ...`. None touches `PARSEABLE`, so they may be run +//! with the name filter `otel::regression_tests`. + +use bytes::Bytes; +use opentelemetry_proto::tonic::collector::logs::v1::ExportLogsServiceRequest; +use opentelemetry_proto::tonic::common::v1::{AnyValue, InstrumentationScope, KeyValue, any_value}; +use opentelemetry_proto::tonic::logs::v1::{LogRecord, ResourceLogs, ScopeLogs}; +use opentelemetry_proto::tonic::metrics::v1::{Gauge, Metric, NumberDataPoint, metric}; +use opentelemetry_proto::tonic::resource::v1::Resource; +use opentelemetry_proto::tonic::trace::v1::Span; +use opentelemetry_proto::tonic::trace::v1::span::{Event, Link}; +use prost::Message as _; +use serde_json::{Map, Value}; + +use super::protobuf_stream::{Signal, count_points, flatten_request, max_record_bytes, outline}; +use super::sink::{CHUNK_LIMITS, Chunker, RowSink, row_bytes}; +use crate::test_alloc::measure; +use crate::utils::json::flatten::{FlattenBudget, FlattenLimits, JsonFlattenError}; + +const MIB: usize = 1024 * 1024; + +/// What a request may make the server hold while its rows are built and staged, +/// as `memory_tests` states it: two chunks of rows and a little more +const PEAK_BOUND: usize = 2 * CHUNK_LIMITS.bytes + 8 * MIB; + +/// `P_MAX_EVENT_PAYLOAD_SIZE` default +const PAYLOAD: usize = 10 * MIB; + +fn mb(bytes: impl TryInto) -> f64 { + bytes.try_into().ok().unwrap() as f64 / MIB as f64 +} + +fn kv(key: &str, value: &str) -> KeyValue { + KeyValue { + key: key.into(), + value: Some(AnyValue { + value: Some(any_value::Value::StringValue(value.into())), + }), + ..Default::default() + } +} + +/// 128 attributes that all have the key `k`: one field, counted as 128 by +/// `attribute_capacity` +fn repeated_keys() -> Vec { + (0..128).map(|_| kv("k", "v")).collect() +} + +fn scope(attributes: Vec) -> Option { + Some(InstrumentationScope { + name: "scope".into(), + version: "1".into(), + attributes, + ..Default::default() + }) +} + +fn resource(attributes: Vec) -> Option { + Some(Resource { + attributes, + ..Default::default() + }) +} + +/// Keeps the last row it is handed, and nothing else +#[derive(Default)] +struct Last(Option>); + +impl RowSink for Last { + type Error = JsonFlattenError; + + fn row(&mut self, row: Map) -> Result<(), Self::Error> { + self.0 = Some(row); + Ok(()) + } +} + +/// Builds one row into a `Last` +type BuildRow = Box; + +/// Bytes the row built by `build` holds once built, and its `row_bytes` +fn held_and_estimated(build: impl FnOnce(&mut Last)) -> (isize, usize) { + let mut last = Last::default(); + let ((), allocated) = measure(|| build(&mut last)); + let row = last.0.expect("a row"); + (allocated.retained, row_bytes(&row)) +} + +/// Review finding 1: resource, scope, span and metric maps are sized from the +/// attribute count, which counts repeated keys, and `IndexMap::clone` keeps the +/// capacity, so a row cloned from such a map held about 10x what `row_bytes` +/// counts (a scope of 128 attributes with one key: 25,917 B against 2,613 B). +/// Every shared map now holds no more than its entries need before it is cloned. +/// +/// The same holds for the maps that are rows themselves: a log record's own +/// fields, a span event, a span link and a metric data point. +#[test] +fn rows_copied_from_maps_with_repeated_keys_hold_what_row_bytes_counts() { + let record = LogRecord { + time_unix_nano: 1_700_000_000_000_000_000, + observed_time_unix_nano: 1_700_000_000_000_000_000, + ..Default::default() + }; + let span = Span { + trace_id: vec![1; 16], + span_id: vec![2; 8], + start_time_unix_nano: 1_700_000_000_000_000_000, + end_time_unix_nano: 1_700_000_000_000_000_001, + ..Default::default() + }; + let span_with_event = Span { + events: vec![Event { + time_unix_nano: 1_700_000_000_000_000_000, + name: "e".into(), + ..Default::default() + }], + ..span.clone() + }; + let gauge = |metadata: Vec, attributes: Vec| Metric { + name: "m".into(), + metadata, + data: Some(metric::Data::Gauge(Gauge { + data_points: vec![NumberDataPoint { + attributes, + time_unix_nano: 1_700_000_000_000_000_000, + ..Default::default() + }], + })), + ..Default::default() + }; + let with_identity = |mut attributes: Vec| { + attributes.push(kv("service.name", "api")); + attributes + }; + + let mut cases: Vec<(&str, BuildRow)> = Vec::new(); + for (level, resource_attributes, scope_attributes) in [ + ("resource", repeated_keys(), vec![]), + ("scope", vec![], repeated_keys()), + ] { + let (ra, sa) = (resource_attributes.clone(), scope_attributes.clone()); + let record = record.clone(); + cases.push(( + if level == "resource" { + "logs, resource" + } else { + "logs, scope" + }, + Box::new(move |sink: &mut Last| { + let resource_fields = + super::logs::resource_log_fields(resource(ra.clone()).as_ref(), ""); + let scope_fields = super::logs::scope_log_fields(scope(sa.clone()).as_ref(), ""); + let row = super::logs::log_record_row( + &record, + &scope_fields, + &resource_fields, + &mut FlattenBudget::new(FlattenLimits::DEFAULT), + ) + .unwrap(); + drop((resource_fields, scope_fields)); + sink.row(row).unwrap(); + }), + )); + } + // The record's own map is the row (or becomes it), so it must not keep the + // room its repeated keys were counted for either + let repeated_record = LogRecord { + attributes: repeated_keys(), + ..record.clone() + }; + cases.push(( + "logs, record", + Box::new(move |sink: &mut Last| { + let resource_fields = super::logs::resource_log_fields( + resource(vec![kv("service.name", "api")]).as_ref(), + "", + ); + let scope_fields = super::logs::scope_log_fields(scope(vec![]).as_ref(), ""); + let row = super::logs::log_record_row( + &repeated_record, + &scope_fields, + &resource_fields, + &mut FlattenBudget::new(FlattenLimits::DEFAULT), + ) + .unwrap(); + drop((resource_fields, scope_fields)); + sink.row(row).unwrap(); + }), + )); + for (name, resource_attributes, scope_attributes, span) in [ + ("traces, resource", repeated_keys(), vec![], span.clone()), + ("traces, scope", vec![], repeated_keys(), span.clone()), + ( + "traces, span", + vec![], + vec![], + Span { + attributes: repeated_keys(), + ..span.clone() + }, + ), + ( + "traces, span with an event", + vec![], + vec![], + Span { + attributes: repeated_keys(), + ..span_with_event.clone() + }, + ), + ( + "traces, event", + vec![kv("service.name", "api")], + vec![], + Span { + attributes: vec![kv("http.method", "GET")], + events: vec![Event { + attributes: repeated_keys(), + ..span_with_event.events[0].clone() + }], + ..span.clone() + }, + ), + ( + "traces, link", + vec![kv("service.name", "api")], + vec![], + Span { + attributes: vec![kv("http.method", "GET")], + links: vec![Link { + trace_id: vec![3; 16], + span_id: vec![4; 8], + attributes: repeated_keys(), + ..Default::default() + }], + ..span.clone() + }, + ), + ] { + cases.push(( + name, + Box::new(move |sink: &mut Last| { + let resource_fields = super::traces::resource_span_fields( + resource(resource_attributes.clone()).as_ref(), + "", + ); + let scope_fields = + super::traces::scope_span_fields(scope(scope_attributes.clone()).as_ref()); + super::traces::span_rows( + &span, + &super::traces::SpanParents { + scope_fields: &scope_fields, + scope_schema_url: "", + resource_fields: &resource_fields, + }, + sink, + ) + .unwrap(); + }), + )); + } + for (name, resource_attributes, scope_attributes, metadata, point, target_info) in [ + ( + "metrics, resource", + with_identity(repeated_keys()), + vec![], + vec![], + vec![], + false, + ), + ( + "metrics, resource, target_info row", + with_identity(repeated_keys()), + vec![], + vec![], + vec![], + true, + ), + ( + "metrics, scope", + with_identity(vec![]), + repeated_keys(), + vec![], + vec![], + false, + ), + ( + "metrics, metric metadata", + with_identity(vec![]), + vec![], + repeated_keys(), + vec![], + false, + ), + ( + "metrics, data point", + with_identity(vec![]), + vec![], + vec![], + repeated_keys(), + false, + ), + ] { + let metric = gauge(metadata, point); + cases.push(( + name, + Box::new(move |sink: &mut Last| { + let fields = super::metrics::ResourceMetricFields::new( + resource(resource_attributes.clone()).as_ref(), + "", + ); + let envelope = fields.scope_envelope(scope(scope_attributes.clone()).as_ref(), ""); + let mut latest = None; + super::metrics::metric_rows_into(&metric, &envelope, false, &mut latest, sink) + .unwrap(); + if target_info { + sink.row(fields.target_info(latest).expect("a target_info row")) + .unwrap(); + } + }), + )); + } + + let mut failed = Vec::new(); + for (name, build) in &cases { + let (held, estimated) = held_and_estimated(build); + let ratio = held as f64 / estimated as f64; + println!( + "REGRESSION repeated keys, {name}: row holds {held} B, row_bytes {estimated} B, held/estimated {ratio:.2}" + ); + if ratio > 2.0 { + failed.push(*name); + } + } + + // The reviewer's request: 65,536 records under that scope, 1.25 MiB of protobuf + let request = ExportLogsServiceRequest { + resource_logs: vec![ResourceLogs { + scope_logs: vec![ScopeLogs { + scope: scope(repeated_keys()), + log_records: vec![record; 1 << 16], + ..Default::default() + }], + ..Default::default() + }], + }; + let (rows, allocated) = measure(|| { + let mut rows = 0usize; + let mut chunker = Chunker::new(CHUNK_LIMITS, |chunk: Vec, _bytes: usize| { + rows += chunk.len(); + Ok::<_, JsonFlattenError>(()) + }); + super::logs::flatten_logs_into( + &request.resource_logs, + &mut FlattenBudget::new(FlattenLimits::DEFAULT), + &mut chunker, + ) + .and_then(|()| chunker.finish()) + .unwrap(); + drop(chunker); + rows + }); + println!( + "REGRESSION repeated keys, request: protobuf {} KiB, {rows} rows, peak {:.1} MiB, bound {:.0} MiB", + request.encoded_len() / 1024, + mb(allocated.peak), + mb(PEAK_BOUND) + ); + assert!(failed.is_empty(), "rows hold over 2x row_bytes: {failed:?}"); + assert_eq!(rows, 1 << 16); + assert!( + allocated.peak <= PEAK_BOUND, + "peak {:.1} MiB", + mb(allocated.peak) + ); +} + +/// A body of `count` two-byte empty entries of field 1 (`resource_logs`, +/// `resource_metrics`, `resource_spans`): every one an empty resource level +fn empty_resources(count: usize) -> Bytes { + Bytes::from([0x0a, 0x00].repeat(count)) +} + +/// One resource level holding `count` two-byte empty scope levels (field 2) +fn empty_scopes_in_one_resource(count: usize) -> Bytes { + let scopes = [0x12, 0x00].repeat(count); + let mut body = vec![0x0a]; + prost::encoding::encode_varint(scopes.len() as u64, &mut body); + body.extend_from_slice(&scopes); + Bytes::from(body) +} + +/// Security review finding 1: the outer levels of a protobuf body were indexed +/// (32 bytes per entry) before the first was read, so a 10 MiB body of 5.2 million +/// empty two-byte `resource_logs` entries held 384 MiB while it was answered 200. +/// The levels are walked as they are read: what reading a body holds for them does +/// not grow with how many there are, for empty resources and for empty scopes of +/// one resource, in every pass over the body. +#[test] +fn outer_levels_are_read_in_memory_independent_of_their_count() { + let max_record = max_record_bytes(PAYLOAD); + for (shape, body) in [ + ("empty resources", empty_resources(PAYLOAD / 2)), + ( + "empty scopes of one resource", + empty_scopes_in_one_resource((PAYLOAD - 8) / 2), + ), + ] { + assert!(body.len() <= PAYLOAD); + for (name, signal) in [ + ("logs", Signal::Logs), + ("metrics", Signal::Metrics), + ("traces", Signal::Traces), + ] { + let (read, outlined) = measure(|| outline(&body, signal).expect("the body decodes")); + let (rows, flattened) = measure(|| { + let mut rows = 0usize; + let mut chunker = Chunker::new(CHUNK_LIMITS, |chunk: Vec, _bytes: usize| { + rows += chunk.len(); + Ok::<_, JsonFlattenError>(()) + }); + flatten_request( + &body, + signal, + max_record, + &mut FlattenBudget::new(FlattenLimits::DEFAULT), + false, + &mut chunker, + ) + .map_err(|_| "flatten failed") + .and_then(|()| chunker.finish().map_err(|_| "staging failed")) + .unwrap(); + drop(chunker); + rows + }); + let (points, counted) = measure(|| count_points(&body)); + println!( + "REGRESSION outer levels, {shape}, {name}: body {:.1} MiB, {} records, {rows} rows, {points} points; peak: outline {} B, flatten_request {} B, count_points {} B", + mb(body.len()), + read.records, + outlined.peak, + flattened.peak, + counted.peak + ); + assert_eq!((read.records, rows, points), (0, 0, 0)); + for (pass, peak) in [ + ("outline", outlined.peak), + ("flatten_request", flattened.peak), + ("count_points", counted.peak), + ] { + assert!(peak < 64 * 1024, "{shape}, {name}: {pass} held {peak} B"); + } + } + } +} diff --git a/src/otel/sink.rs b/src/otel/sink.rs new file mode 100644 index 000000000..3b35228ac --- /dev/null +++ b/src/otel/sink.rs @@ -0,0 +1,420 @@ +/* + * Parseable Server (C) 2022 - 2025 Parseable, Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + */ + +//! Rows of an OTLP request, handed over one at a time. +//! +//! The flatteners build one row per log record, span event or link (or span), and +//! metric data point, and hand each to a [`RowSink`] as soon as it is built. A +//! [`Chunker`] collects them into chunks limited by rows and by an estimate of the +//! memory the rows hold ([`row_bytes`]), and passes every full chunk on before the +//! next is built. So the rows of a request are never all held at once. + +use std::collections::HashSet; +use std::mem::size_of; + +use serde_json::{Map, Value}; + +use crate::utils::json::flatten::JsonFlattenError; + +/// Receives the rows of one request, in order, as they are built +pub trait RowSink { + type Error: From; + + /// Takes one finished row + fn row(&mut self, row: Map) -> Result<(), Self::Error>; + + /// Takes one finished row that is one metric data point + fn point(&mut self, row: Map) -> Result<(), Self::Error> { + self.row(row) + } + + /// Every row of one leaf record (a log record, a span or a metric) was handed over + fn record_end(&mut self) {} +} + +/// Collects every row, for callers that want them all at once (tests, benchmarks) +impl RowSink for Vec { + type Error = JsonFlattenError; + + fn row(&mut self, row: Map) -> Result<(), Self::Error> { + self.push(Value::Object(row)); + Ok(()) + } +} + +/// `size_of::()`: every value in a map or array takes this much in place +pub const VALUE_BYTES: usize = size_of::(); + +/// One entry of a row map (`serde_json::Map` is an `IndexMap`): its bucket holds the +/// hash, the key `String` and the `Value` (104 B), the hash table one index and one +/// control byte, and both grow by doubling, so on average about a third more +/// capacity is held than used +pub const ENTRY_BYTES: usize = 128; + +/// What the system allocator adds to one heap block (header and rounding), counted +/// so that rows of many tiny strings are not underestimated +pub const HEAP_BLOCK_BYTES: usize = 16; + +/// Estimated bytes of the heap block of a string with this capacity +#[inline] +pub fn heap_bytes(capacity: usize) -> usize { + if capacity == 0 { + 0 + } else { + capacity + HEAP_BLOCK_BYTES + } +} + +/// Estimate of the memory one row holds, including the cells of the column tables +/// that structural flattening later builds from its arrays of objects (one `Value` +/// per distinct key and element, see `flatten_array_objects`). It tracks the real +/// `Value` memory, not the length of the row as JSON: a field `"a":0` is 6 bytes of +/// JSON and about 150 bytes of memory. +pub fn row_bytes(row: &Map) -> usize { + VALUE_BYTES + map_bytes(row) +} + +fn map_bytes(map: &Map) -> usize { + let mut bytes = 0; + for (key, value) in map { + bytes += ENTRY_BYTES + heap_bytes(key.capacity()) + value_heap_bytes(value); + } + bytes +} + +/// Heap bytes owned by `value` (its own `VALUE_BYTES` are counted by its container) +fn value_heap_bytes(value: &Value) -> usize { + match value { + Value::Null | Value::Bool(_) | Value::Number(_) => 0, + Value::String(s) => heap_bytes(s.capacity()), + Value::Object(map) => map_bytes(map), + Value::Array(values) => array_bytes(values), + } +} + +fn array_bytes(values: &Vec) -> usize { + let mut bytes = heap_bytes(values.capacity() * VALUE_BYTES); + let mut objects = false; + for value in values { + objects |= value.is_object(); + bytes += value_heap_bytes(value); + } + if objects { + // Structural flattening turns the elements into one column per distinct key, + // with a cell for every element + let keys: HashSet<&str> = values + .iter() + .filter_map(Value::as_object) + .flat_map(|object| object.keys().map(String::as_str)) + .collect(); + bytes += keys.len() * (ENTRY_BYTES + values.len() * VALUE_BYTES); + } + bytes +} + +/// Limits of one chunk of rows +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ChunkLimits { + /// Rows of one chunk + pub rows: usize, + /// Estimated memory of the rows of one chunk, see [`row_bytes`] + pub bytes: usize, +} + +/// Default chunk limits. A chunk is full at 8192 rows (the default batch size of the +/// OpenTelemetry collector) or 16 MiB of estimated row memory, whichever comes first. +/// Rows of realistic requests hold 1-10 KiB each, so the memory limit usually decides. +pub const CHUNK_LIMITS: ChunkLimits = ChunkLimits { + rows: 8192, + bytes: 16 * 1024 * 1024, +}; + +/// What a [`Chunker`] passed on +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct Staged { + /// Chunks passed on + pub chunks: u64, + /// Rows passed on + pub rows: u64, + /// Leaf records all of whose rows were passed on + pub records: u64, + /// Data point rows passed on + pub points: u64, +} + +/// Row bytes per body byte one request may expand to: the rows of a request may +/// hold at most `EXPANSION_FACTOR` times the length of its body (decompressed) of +/// estimated memory ([`row_bytes`]) in all, counted while they are staged, at +/// least [`MIN_EXPANDED_BYTES`] and at most [`EXPANSION_CEILING_FACTOR`] times +/// the payload limit. +/// +/// Every row carries its own copy of the resource, scope, span and metric fields, +/// so a small request can expand to a very large number of row bytes: 15 KB of +/// resource attributes copied into each of 5 million two-byte log records is tens +/// of GiB. Chunking bounds the memory this takes at once, not what is written to +/// staging. The most measured for a request shaped like collector traffic is +/// below 500 row bytes per body byte (short log records or bare gauge points under +/// 30 Kubernetes resource attributes; ordinary k8s logs, spans and metrics expand +/// 40-110x, see `realistic_tests`), and a request of such records expands less the +/// fewer records share its resource, so 4096 leaves at least 8x headroom wherever +/// the ceiling does not decide, and stops the requests that copy kilobytes of +/// shared fields into millions of records of a few bytes. +pub const EXPANSION_FACTOR: u64 = 4096; + +/// Estimated bytes of rows any request may expand to, whatever the length of its +/// body: one chunk. Below it the cap would only cut requests whose rows fit in one +/// chunk, whose memory the chunk limit bounds anyway. The bodies it decides for are +/// under 4 KiB, which realistic records expand to at most 2 MiB of rows (500 bytes +/// per body byte), 8x under it. +pub const MIN_EXPANDED_BYTES: u64 = CHUNK_LIMITS.bytes as u64; + +/// Estimated row bytes per byte of the payload limit (`P_MAX_EVENT_PAYLOAD_SIZE`) +/// that no request may pass, however long its body: 10 GiB at the default limit +/// of 10 MiB. +/// +/// What a request stages stays in the staging buffers until they are converted, as +/// record batches of about a sixth of the estimate (1.6 GiB measured for 10 GiB of +/// rows), so `EXPANSION_FACTOR` alone would let one body of the full payload limit +/// add 40 GiB of rows, 6 GiB of record batches. The ceiling decides for bodies +/// over a quarter of the payload limit. The largest realistic request measured, +/// short log records under 30 Kubernetes resource attributes filling the payload +/// limit, takes 4.1 GiB, so the ceiling leaves 2.4x headroom there, and the 8x of +/// `EXPANSION_FACTOR` up to a quarter of the limit: 138,000 such records, 16 times +/// the 8192 records of a collector's default batch. +pub const EXPANSION_CEILING_FACTOR: u64 = 1024; + +/// Estimated bytes of rows one request may expand to, for a body of `body_len` +/// bytes (decompressed) under a payload limit of `max_payload` bytes +pub fn max_expanded_bytes(body_len: usize, max_payload: usize) -> u64 { + let ceiling = (max_payload as u64) + .saturating_mul(EXPANSION_CEILING_FACTOR) + .max(MIN_EXPANDED_BYTES); + (body_len as u64) + .saturating_mul(EXPANSION_FACTOR) + .clamp(MIN_EXPANDED_BYTES, ceiling) +} + +/// Collects rows into chunks and passes every full chunk to `stage`, with the +/// estimated bytes of its rows, dropping it before the next row is taken. Call +/// [`Chunker::finish`] to pass on the rest. +pub struct Chunker { + limits: ChunkLimits, + stage: F, + rows: Vec, + bytes: usize, + /// Records and data points whose rows are all in `rows`, not yet passed on + pending_records: u64, + pending_points: u64, + staged: Staged, +} + +impl Chunker +where + F: FnMut(Vec, usize) -> Result<(), E>, + E: From, +{ + pub fn new(limits: ChunkLimits, stage: F) -> Self { + Self { + limits, + stage, + rows: Vec::new(), + bytes: 0, + pending_records: 0, + pending_points: 0, + staged: Staged::default(), + } + } + + /// What was passed on so far + pub fn staged(&self) -> Staged { + self.staged + } + + fn flush(&mut self) -> Result<(), E> { + let rows = std::mem::take(&mut self.rows); + let count = rows.len() as u64; + let bytes = std::mem::take(&mut self.bytes); + (self.stage)(rows, bytes)?; + self.staged.chunks += 1; + self.staged.rows += count; + self.staged.records += std::mem::take(&mut self.pending_records); + self.staged.points += std::mem::take(&mut self.pending_points); + Ok(()) + } + + /// Passes on the rows taken since the last full chunk, if any + pub fn finish(&mut self) -> Result<(), E> { + if !self.rows.is_empty() { + self.flush()?; + } + Ok(()) + } +} + +impl RowSink for Chunker +where + F: FnMut(Vec, usize) -> Result<(), E>, + E: From, +{ + type Error = E; + + fn row(&mut self, row: Map) -> Result<(), E> { + self.bytes += row_bytes(&row); + self.rows.push(Value::Object(row)); + if self.rows.len() >= self.limits.rows || self.bytes >= self.limits.bytes { + self.flush()?; + } + Ok(()) + } + + fn point(&mut self, row: Map) -> Result<(), E> { + // Counted with the chunk it is in, which `row` may already have passed on + let flushed_before = self.staged.chunks; + self.row(row)?; + if self.staged.chunks == flushed_before { + self.pending_points += 1; + } else { + self.staged.points += 1; + } + Ok(()) + } + + fn record_end(&mut self) { + if self.rows.is_empty() { + // Its last row (if it had any) filled a chunk that was passed on + self.staged.records += 1; + } else { + self.pending_records += 1; + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn object(value: Value) -> Map { + match value { + Value::Object(map) => map, + _ => unreachable!(), + } + } + + #[test] + fn value_is_72_bytes() { + assert_eq!(VALUE_BYTES, 72); + } + + #[test] + fn chunks_are_cut_by_rows_and_by_bytes() { + let mut chunks: Vec = Vec::new(); + let mut chunker = Chunker::new( + ChunkLimits { + rows: 3, + bytes: usize::MAX, + }, + |rows, _| { + chunks.push(rows.len()); + Ok::<_, JsonFlattenError>(()) + }, + ); + for i in 0..7 { + chunker.row(object(json!({ "i": i }))).unwrap(); + chunker.record_end(); + } + chunker.finish().unwrap(); + let staged = chunker.staged(); + drop(chunker); + assert_eq!(chunks, [3, 3, 1]); + assert_eq!(staged.rows, 7); + assert_eq!(staged.records, 7); + assert_eq!(staged.chunks, 3); + + let row = object(json!({ "a": "x" })); + let one = row_bytes(&row); + let mut chunks: Vec = Vec::new(); + let mut chunker = Chunker::new( + ChunkLimits { + rows: usize::MAX, + bytes: 2 * one, + }, + |rows, _| { + chunks.push(rows.len()); + Ok::<_, JsonFlattenError>(()) + }, + ); + for _ in 0..5 { + chunker.row(row.clone()).unwrap(); + } + chunker.finish().unwrap(); + drop(chunker); + assert_eq!(chunks, [2, 2, 1]); + } + + #[test] + fn a_record_counts_once_all_its_rows_are_passed_on() { + let mut fail_at = 2; + let mut chunker = Chunker::new( + ChunkLimits { + rows: 2, + bytes: usize::MAX, + }, + |_, _| { + fail_at -= 1; + if fail_at == 0 { + Err(JsonFlattenError::CannotFlatten) + } else { + Ok(()) + } + }, + ); + // Record 1: rows 1-3 (second chunk fails); record 0: row 0 + chunker.point(object(json!({ "r": 0 }))).unwrap(); + chunker.record_end(); + chunker.point(object(json!({ "r": 1 }))).unwrap(); + assert_eq!(chunker.staged().records, 1); + assert_eq!(chunker.staged().points, 2); + chunker.point(object(json!({ "r": 2 }))).unwrap(); + assert!(chunker.point(object(json!({ "r": 3 }))).is_err()); + assert_eq!(chunker.staged().records, 1); + assert_eq!(chunker.staged().points, 2); + assert_eq!(chunker.staged().rows, 2); + } + + #[test] + fn records_without_rows_count_when_finished() { + let mut chunker = Chunker::new(CHUNK_LIMITS, |_, _| Ok::<_, JsonFlattenError>(())); + chunker.record_end(); + chunker.finish().unwrap(); + let staged = chunker.staged(); + assert_eq!(staged.records, 1); + assert_eq!(staged.chunks, 0); + } + + #[test] + fn row_bytes_counts_the_column_table_of_arrays_of_objects() { + let objects: Vec = (0..100).map(|i| json!({ format!("k{i}"): 1 })).collect(); + let row = object(json!({ "exemplars": objects })); + // 100 distinct keys x 100 elements + assert!(row_bytes(&row) > 100 * 100 * VALUE_BYTES); + let same: Vec = (0..100).map(|_| json!({ "k": 1 })).collect(); + let row = object(json!({ "exemplars": same })); + assert!(row_bytes(&row) < 100 * 3 * ENTRY_BYTES); + } +} diff --git a/src/otel/traces.rs b/src/otel/traces.rs index b0c142081..8ee032d3f 100644 --- a/src/otel/traces.rs +++ b/src/otel/traces.rs @@ -16,9 +16,12 @@ * */ use opentelemetry_proto::tonic::collector::trace::v1::ExportTraceServiceRequest; +use opentelemetry_proto::tonic::common::v1::InstrumentationScope; use opentelemetry_proto::tonic::common::v1::KeyValue; -use opentelemetry_proto::tonic::trace::v1::ScopeSpans; +use opentelemetry_proto::tonic::resource::v1::Resource; +use opentelemetry_proto::tonic::trace::v1::ResourceSpans; use opentelemetry_proto::tonic::trace::v1::Span; +#[cfg(test)] use opentelemetry_proto::tonic::trace::v1::Status; use opentelemetry_proto::tonic::trace::v1::TracesData; use opentelemetry_proto::tonic::trace::v1::span::Event; @@ -30,7 +33,9 @@ use crate::otel::otel_utils::flatten_attributes; use super::otel_utils::attribute_capacity; use super::otel_utils::convert_epoch_nano_to_timestamp; -use super::otel_utils::insert_attributes; +use super::otel_utils::fit_map; +use super::otel_utils::insert_attributes_fitted; +use super::sink::RowSink; pub const OTEL_TRACES_KNOWN_FIELD_LIST: [&str; 32] = [ "scope_name", @@ -66,108 +71,140 @@ pub const OTEL_TRACES_KNOWN_FIELD_LIST: [&str; 32] = [ "span_status_description", "span_status_message", ]; -/// this function flattens the `ScopeSpans` object -/// and returns a `Vec` of `Map` of the flattened json -fn flatten_scope_span(scope_span: &ScopeSpans, tenant_id: &str) -> Vec> { - let mut vec_scope_span_json = Vec::with_capacity(scope_span.spans.len()); - let mut scope_span_json = Map::with_capacity( - 5 + scope_span - .scope - .as_ref() - .map_or(0, |scope| attribute_capacity(&scope.attributes)), +/// Fields every row of one `ScopeSpans` gets from its scope, when it has one +pub fn scope_span_fields(scope: Option<&InstrumentationScope>) -> Map { + let Some(scope) = scope else { + return Map::new(); + }; + let capacity = 5 + attribute_capacity(&scope.attributes); + let mut scope_span_json = Map::with_capacity(capacity); + scope_span_json.insert("scope_name".to_string(), Value::String(scope.name.clone())); + scope_span_json.insert( + "scope_version".to_string(), + Value::String(scope.version.clone()), ); - for span in &scope_span.spans { - let span_record_json = flatten_span_record(span); - vec_scope_span_json.extend(span_record_json); - } - - let date = chrono::Utc::now().date_naive().to_string(); - increment_traces_collected_by_date(scope_span.spans.len() as u64, &date, tenant_id); + insert_attributes_fitted(&mut scope_span_json, &scope.attributes, capacity); + scope_span_json.insert( + "scope_dropped_attributes_count".to_string(), + Value::Number(scope.dropped_attributes_count.into()), + ); + scope_span_json +} - if let Some(scope) = &scope_span.scope { - scope_span_json.insert("scope_name".to_string(), Value::String(scope.name.clone())); - scope_span_json.insert( - "scope_version".to_string(), - Value::String(scope.version.clone()), - ); - insert_attributes(&mut scope_span_json, &scope.attributes); - scope_span_json.insert( - "scope_dropped_attributes_count".to_string(), - Value::Number(scope.dropped_attributes_count.into()), +/// Fields every row of one `ResourceSpans` gets, after all others +pub fn resource_span_fields(resource: Option<&Resource>, schema_url: &str) -> Map { + let capacity = 4 + resource.map_or(0, |resource| attribute_capacity(&resource.attributes)); + let mut resource_span_json = Map::with_capacity(capacity); + if let Some(resource) = resource { + insert_attributes_fitted(&mut resource_span_json, &resource.attributes, capacity); + resource_span_json.insert( + "resource_dropped_attributes_count".to_string(), + Value::Number(resource.dropped_attributes_count.into()), ); - - for span_json in &mut vec_scope_span_json { - for (key, value) in &scope_span_json { - span_json.insert(key.clone(), value.clone()); - } - } } + resource_span_json.insert( + "resource_schema_url".to_string(), + Value::String(schema_url.to_string()), + ); + resource_span_json +} - for span_json in &mut vec_scope_span_json { - span_json.insert( +/// The fields a span row gets from its scope and resource, in the order they are +/// merged over the span's own fields +pub struct SpanParents<'a> { + pub scope_fields: &'a Map, + pub scope_schema_url: &'a str, + pub resource_fields: &'a Map, +} + +impl SpanParents<'_> { + fn finish(&self, mut row: Map) -> Map { + for (key, value) in self.scope_fields { + row.insert(key.clone(), value.clone()); + } + row.insert( "scope_schema_url".to_string(), - Value::String(scope_span.schema_url.clone()), + Value::String(self.scope_schema_url.to_string()), ); + for (key, value) in self.resource_fields { + row.insert(key.clone(), value.clone()); + } + row } - - vec_scope_span_json } -/// Common function to process resource spans and merge resource-level fields -fn process_resource_spans( - resource_spans: &[T], - get_resource: fn(&T) -> Option<&opentelemetry_proto::tonic::resource::v1::Resource>, - get_scope_spans: fn(&T) -> &[ScopeSpans], - get_schema_url: fn(&T) -> &str, - tenant_id: &str, -) -> Vec -where - T: std::fmt::Debug, -{ - let mut vec_otel_json = Vec::new(); - - for resource_span in resource_spans { - let resource = get_resource(resource_span); - let mut resource_span_json = Map::with_capacity( - 4 + resource.map_or(0, |resource| attribute_capacity(&resource.attributes)), - ); - - // Process resource attributes if present - if let Some(resource) = resource { - insert_attributes(&mut resource_span_json, &resource.attributes); - resource_span_json.insert( - "resource_dropped_attributes_count".to_string(), - Value::Number(resource.dropped_attributes_count.into()), - ); +/// Hands the rows of one span to `sink`: one per event, then one per link, each with +/// the span's fields merged over it, or the span's own row when it has neither. Each +/// event or link row is built only once the one before it was handed over. +pub fn span_rows( + span: &Span, + parents: &SpanParents<'_>, + sink: &mut S, +) -> Result<(), S::Error> { + // The scope, schema URL and resource fields every row of the span gets + let extra = parents.scope_fields.len() + 1 + parents.resource_fields.len(); + let span_record_json = flatten_span_fields(span, extra); + if span.events.is_empty() && span.links.is_empty() { + sink.row(parents.finish(span_record_json))?; + } else { + // Sized so that the merges below never have to grow a row map: a growth + // rehashes every entry of the row. + let row_extra = extra + span_record_json.len(); + for event in &span.events { + let mut row = event_row(event, span.start_time_unix_nano, row_extra); + for (key, value) in &span_record_json { + row.insert(key.clone(), value.clone()); + } + sink.row(parents.finish(row))?; } - - // Process scope spans - let scope_spans = get_scope_spans(resource_span); - let mut vec_resource_spans_json = Vec::with_capacity( - scope_spans - .iter() - .map(|scope_span| scope_span.spans.len()) - .sum(), - ); - for scope_span in scope_spans { - let scope_span_json = flatten_scope_span(scope_span, tenant_id); - vec_resource_spans_json.extend(scope_span_json); + for link in &span.links { + let mut row = link_row(link, row_extra); + for (key, value) in &span_record_json { + row.insert(key.clone(), value.clone()); + } + sink.row(parents.finish(row))?; } + } + sink.record_end(); + Ok(()) +} - // Add resource schema URL - resource_span_json.insert( - "resource_schema_url".to_string(), - Value::String(get_schema_url(resource_span).to_string()), - ); - - // Merge resource-level fields into each span record - for mut resource_spans_json in vec_resource_spans_json { - resource_spans_json.extend(resource_span_json.clone()); - vec_otel_json.push(Value::Object(resource_spans_json)); +/// Hands the rows of every span of `resource_spans` to `sink`, one at a time +pub fn flatten_traces_into( + resource_spans: &[ResourceSpans], + sink: &mut S, +) -> Result<(), S::Error> { + for resource_span in resource_spans { + let resource_fields = + resource_span_fields(resource_span.resource.as_ref(), &resource_span.schema_url); + for scope_span in &resource_span.scope_spans { + let scope_fields = scope_span_fields(scope_span.scope.as_ref()); + let parents = SpanParents { + scope_fields: &scope_fields, + scope_schema_url: &scope_span.schema_url, + resource_fields: &resource_fields, + }; + for span in &scope_span.spans { + span_rows(span, &parents, sink)?; + } } } + Ok(()) +} - vec_otel_json +/// All rows of `resource_spans` at once, counting the spans for `tenant_id`. +/// Ingestion streams the rows instead, see `flatten_traces_into`. +fn collect_resource_spans(resource_spans: &[ResourceSpans], tenant_id: &str) -> Vec { + let mut rows = Vec::new(); + flatten_traces_into(resource_spans, &mut rows).expect("span rows are never refused"); + let spans: usize = resource_spans + .iter() + .flat_map(|resource_span| &resource_span.scope_spans) + .map(|scope_span| scope_span.spans.len()) + .sum(); + let date = chrono::Utc::now().date_naive().to_string(); + increment_traces_collected_by_date(spans as u64, &date, tenant_id); + rows } /// Flattens OpenTelemetry traces from protobuf format @@ -175,98 +212,98 @@ pub fn flatten_otel_traces_protobuf( message: &ExportTraceServiceRequest, tenant_id: &str, ) -> Vec { - process_resource_spans( - &message.resource_spans, - |rs| rs.resource.as_ref(), - |rs| &rs.scope_spans, - |rs| &rs.schema_url, - tenant_id, - ) + collect_resource_spans(&message.resource_spans, tenant_id) } /// this function performs the custom flattening of the otel traces event /// and returns a `Vec` of `Value::Object` of the flattened json pub fn flatten_otel_traces(message: &TracesData, tenant_id: &str) -> Vec { - process_resource_spans( - &message.resource_spans, - |rs| rs.resource.as_ref(), - |rs| &rs.scope_spans, - |rs| &rs.schema_url, - tenant_id, - ) + collect_resource_spans(&message.resource_spans, tenant_id) +} + +/// The own fields of the row of one span event; `extra` is the capacity the +/// span, scope and resource fields merged over it will take +fn event_row(event: &Event, span_start_time_unix_nano: u64, extra: usize) -> Map { + let counted = attribute_capacity(&event.attributes); + let capacity = 6 + counted + extra; + let mut event_json = Map::with_capacity(capacity); + event_json.insert( + "event_time_unix_nano".to_string(), + Value::String(convert_epoch_nano_to_timestamp(event.time_unix_nano as i64)), + ); + // add epoch value of event time in json + event_json.insert( + "event_time_unix_nano_epoch".to_string(), + Value::Number(serde_json::Number::from(event.time_unix_nano)), + ); + event_json.insert("event_name".to_string(), Value::String(event.name.clone())); + + // Calculate event duration in nanoseconds from span start + let duration_nanos = event + .time_unix_nano + .saturating_sub(span_start_time_unix_nano); + event_json.insert( + "event_duration_ns".to_string(), + Value::Number(serde_json::Number::from(duration_nanos)), + ); + + let before = event_json.len(); + insert_events_attributes(&mut event_json, &event.attributes); + // Repeated attribute keys must not leave room in the row + let added = event_json.len() - before; + fit_map(&mut event_json, capacity, counted, added); + event_json.insert( + "event_dropped_attributes_count".to_string(), + Value::Number(event.dropped_attributes_count.into()), + ); + event_json } -/// otel traces has json array of events -/// this function flattens the `Event` object -/// and returns a `Vec` of `Map` of the flattened json +/// The own fields of the row of one span link; `extra` is the capacity the span, +/// scope and resource fields merged over it will take +fn link_row(link: &Link, extra: usize) -> Map { + let counted = attribute_capacity(&link.attributes); + let capacity = 5 + counted + extra; + let mut link_json = Map::with_capacity(capacity); + link_json.insert( + "link_span_id".to_string(), + Value::String(hex::encode(&link.span_id)), + ); + link_json.insert( + "link_trace_id".to_string(), + Value::String(hex::encode(&link.trace_id)), + ); + + let before = link_json.len(); + insert_links_attributes(&mut link_json, &link.attributes); + // Repeated attribute keys must not leave room in the row + let added = link_json.len() - before; + fit_map(&mut link_json, capacity, counted, added); + link_json.insert( + "link_dropped_attributes_count".to_string(), + Value::Number(link.dropped_attributes_count.into()), + ); + link_json +} + +#[cfg(test)] fn flatten_events(events: &[Event], span_start_time_unix_nano: u64) -> Vec> { events .iter() - .map(|event| { - let mut event_json = Map::with_capacity(6 + attribute_capacity(&event.attributes)); - event_json.insert( - "event_time_unix_nano".to_string(), - Value::String( - convert_epoch_nano_to_timestamp(event.time_unix_nano as i64).to_string(), - ), - ); - // add epoch value of event time in json - event_json.insert( - "event_time_unix_nano_epoch".to_string(), - Value::Number(serde_json::Number::from(event.time_unix_nano)), - ); - event_json.insert("event_name".to_string(), Value::String(event.name.clone())); - - // Calculate event duration in nanoseconds from span start - let duration_nanos = event - .time_unix_nano - .saturating_sub(span_start_time_unix_nano); - event_json.insert( - "event_duration_ns".to_string(), - Value::Number(serde_json::Number::from(duration_nanos)), - ); - - insert_events_attributes(&mut event_json, &event.attributes); - event_json.insert( - "event_dropped_attributes_count".to_string(), - Value::Number(event.dropped_attributes_count.into()), - ); - event_json - }) + .map(|event| event_row(event, span_start_time_unix_nano, 0)) .collect() } -/// otel traces has json array of links -/// this function flattens the `Link` object -/// and returns a `Vec` of `Map` of the flattened json +#[cfg(test)] fn flatten_links(links: &[Link]) -> Vec> { - links - .iter() - .map(|link| { - let mut link_json = Map::with_capacity(5 + attribute_capacity(&link.attributes)); - link_json.insert( - "link_span_id".to_string(), - Value::String(hex::encode(&link.span_id)), - ); - link_json.insert( - "link_trace_id".to_string(), - Value::String(hex::encode(&link.trace_id)), - ); - - insert_links_attributes(&mut link_json, &link.attributes); - link_json.insert( - "link_dropped_attributes_count".to_string(), - Value::Number(link.dropped_attributes_count.into()), - ); - link_json - }) - .collect() + links.iter().map(|link| link_row(link, 0)).collect() } /// otel trace event has status /// there is a mapping of status code to status description provided in proto /// this function fetches the status description from the status code /// and adds it to the flattened json +#[cfg(test)] fn flatten_status(status: &Status) -> Map { let mut status_json = Map::new(); status_json.insert( @@ -277,50 +314,67 @@ fn flatten_status(status: &Status) -> Map { "span_status_code".to_string(), Value::Number(status.code.into()), ); - let description = match status.code { - 0 => "UNSET", - 1 => "OK", - 2 => "ERROR", - _ => "", - }; status_json.insert( "span_status_description".to_string(), - Value::String(description.to_string()), + Value::String(status_description(status.code).to_string()), ); status_json } +fn status_description(code: i32) -> &'static str { + match code { + 0 => "UNSET", + 1 => "OK", + 2 => "ERROR", + _ => "", + } +} + /// otel log event has flags /// there is a mapping of flags to flags description provided in proto /// this function fetches the flags description from the flags /// and adds it to the flattened json +#[cfg(test)] fn flatten_flags(flags: u32) -> Map { let mut flags_json = Map::new(); flags_json.insert("span_flags".to_string(), Value::Number(flags.into())); - let description = match flags { - 0 => "DO_NOT_USE", - 255 => "TRACE_FLAGS_MASK", - 256 => "CONTEXT_HAS_IS_REMOTE_MASK", - 512 => "CONTEXT_IS_REMOTE_MASK", - _ => "", - }; flags_json.insert( "span_flags_description".to_string(), - Value::String(description.to_string()), + Value::String(flags_description(flags).to_string()), ); flags_json } +fn flags_description(flags: u32) -> &'static str { + match flags { + 0 => "DO_NOT_USE", + 255 => "TRACE_FLAGS_MASK", + 256 => "CONTEXT_HAS_IS_REMOTE_MASK", + 512 => "CONTEXT_IS_REMOTE_MASK", + _ => "", + } +} + /// otel span event has kind /// there is a mapping of kind to kind description provided in proto /// this function fetches the kind description from the kind /// and adds it to the flattened json +#[cfg(test)] fn flatten_kind(kind: i32) -> Map { let mut kind_json = Map::new(); kind_json.insert("span_kind".to_string(), Value::Number(kind.into())); - let description = match kind { + kind_json.insert( + "span_kind_description".to_string(), + Value::String(kind_description(kind).to_string()), + ); + + kind_json +} + +fn kind_description(kind: i32) -> &'static str { + match kind { 0 => "UNSPECIFIED", 1 => "INTERNAL", 2 => "SERVER", @@ -328,21 +382,16 @@ fn flatten_kind(kind: i32) -> Map { 4 => "PRODUCER", 5 => "CONSUMER", _ => "", - }; - kind_json.insert( - "span_kind_description".to_string(), - Value::String(description.to_string()), - ); - - kind_json + } } -/// this function flattens the `Span` object -/// and returns a `Vec` of `Map` of the flattened json -/// this function is called recursively for each span record object in the otel traces event -fn flatten_span_record(span_record: &Span) -> Vec> { - let mut span_records_json = Vec::new(); - let mut span_record_json = Map::with_capacity(40 + attribute_capacity(&span_record.attributes)); +/// The fields of one span that every row of it gets; `extra` is the capacity the +/// scope and resource fields merged over it will take +fn flatten_span_fields(span_record: &Span, extra: usize) -> Map { + // The span's own 20 fields (the status adds 3 of them), its attributes, and + // the scope and resource fields merged into the span's own row + let capacity = 20 + attribute_capacity(&span_record.attributes) + extra; + let mut span_record_json = Map::with_capacity(capacity); span_record_json.insert( "span_trace_id".to_string(), Value::String(hex::encode(&span_record.trace_id)), @@ -359,12 +408,28 @@ fn flatten_span_record(span_record: &Span) -> Vec> { "span_parent_span_id".to_string(), Value::String(hex::encode(&span_record.parent_span_id)), ); - span_record_json.extend(flatten_flags(span_record.flags)); + // The flags, kind and status fields are inserted directly: a map of their + // own only to be merged into this one bought their keys a second hash + span_record_json.insert( + "span_flags".to_string(), + Value::Number(span_record.flags.into()), + ); + span_record_json.insert( + "span_flags_description".to_string(), + Value::String(flags_description(span_record.flags).to_string()), + ); span_record_json.insert( "span_name".to_string(), Value::String(span_record.name.clone()), ); - span_record_json.extend(flatten_kind(span_record.kind)); + span_record_json.insert( + "span_kind".to_string(), + Value::Number(span_record.kind.into()), + ); + span_record_json.insert( + "span_kind_description".to_string(), + Value::String(kind_description(span_record.kind).to_string()), + ); span_record_json.insert( "span_start_time_unix_nano".to_string(), Value::String(convert_epoch_nano_to_timestamp( @@ -397,40 +462,57 @@ fn flatten_span_record(span_record: &Span) -> Vec> { Value::Number(serde_json::Number::from(duration_nanos)), ); - insert_attributes(&mut span_record_json, &span_record.attributes); + insert_attributes_fitted(&mut span_record_json, &span_record.attributes, capacity); span_record_json.insert( "span_dropped_attributes_count".to_string(), Value::Number(span_record.dropped_attributes_count.into()), ); - let events_json = flatten_events(&span_record.events, span_record.start_time_unix_nano); - span_records_json.extend(events_json); span_record_json.insert( "span_dropped_events_count".to_string(), Value::Number(span_record.dropped_events_count.into()), ); - let links_json = flatten_links(&span_record.links); - span_records_json.extend(links_json); span_record_json.insert( "span_dropped_links_count".to_string(), Value::Number(span_record.dropped_links_count.into()), ); if let Some(status) = &span_record.status { - span_record_json.extend(flatten_status(status)); - } - // if span_record.events is null, code should still flatten other elements in the span record - this is handled in the if block - // else block handles the flattening the span record that includes events and links records in each span record - if span_records_json.is_empty() { - span_records_json = vec![span_record_json]; - } else { - for span_json in &mut span_records_json { - for (key, value) in &span_record_json { - span_json.insert(key.clone(), value.clone()); - } - } + span_record_json.insert( + "span_status_message".to_string(), + Value::String(status.message.clone()), + ); + span_record_json.insert( + "span_status_code".to_string(), + Value::Number(status.code.into()), + ); + span_record_json.insert( + "span_status_description".to_string(), + Value::String(status_description(status.code).to_string()), + ); } + span_record_json +} - span_records_json +/// The rows of one span without its scope and resource fields +#[cfg(test)] +fn flatten_span_record(span_record: &Span) -> Vec> { + let empty = Map::new(); + let parents = SpanParents { + scope_fields: &empty, + scope_schema_url: "", + resource_fields: &empty, + }; + let mut rows = Vec::new(); + span_rows(span_record, &parents, &mut rows).expect("span rows are never refused"); + rows.into_iter() + .map(|row| { + let Value::Object(mut row) = row else { + unreachable!("rows are objects") + }; + row.shift_remove("scope_schema_url"); + row + }) + .collect() } pub fn insert_events_attributes(map: &mut Map, attributes: &[KeyValue]) { @@ -454,7 +536,7 @@ mod tests { use super::*; use opentelemetry_proto::tonic::common::v1::{AnyValue, EntityRef, KeyValue}; use opentelemetry_proto::tonic::resource::v1::Resource; - use opentelemetry_proto::tonic::trace::v1::{ResourceSpans, TracesData}; + use opentelemetry_proto::tonic::trace::v1::{ResourceSpans, ScopeSpans, TracesData}; /// Helper function to create a sample trace ID fn sample_trace_id() -> Vec { @@ -1188,8 +1270,6 @@ mod tests { use opentelemetry_proto::tonic::trace::v1::span::{Event, Link}; use opentelemetry_proto::tonic::trace::v1::{ResourceSpans, ScopeSpans, Span, Status}; - use super::super::flatten_otel_traces_protobuf; - const SPANS_PER_SCOPE: usize = 250; const ITERS: usize = 20; @@ -1322,8 +1402,12 @@ mod tests { ExportTraceServiceRequest { resource_spans } } + /// What ingestion does with a decoded request: its rows handed over in + /// chunks (collected here) fn flatten(request: &ExportTraceServiceRequest) -> Vec { - flatten_otel_traces_protobuf(request, "perfbench") + bench::chunked(|chunker| { + super::super::flatten_traces_into(&request.resource_spans, chunker) + }) } #[test] diff --git a/src/test_alloc.rs b/src/test_alloc.rs new file mode 100644 index 000000000..c7571a0d9 --- /dev/null +++ b/src/test_alloc.rs @@ -0,0 +1,108 @@ +/* + * Parseable Server (C) 2022 - 2025 Parseable, Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + */ + +//! The global allocator of the library's test binary. It forwards to the system +//! allocator and, on a thread that asked for it, counts the bytes that thread +//! allocates, so a test can assert how much memory a call needs instead of +//! inferring it. Other threads (other tests) are never counted. Sizes are +//! layout sizes, not what the system allocator rounds them up to, and a +//! reallocation counts the old and the new block together at its peak. + +use std::{ + alloc::{GlobalAlloc, Layout, System}, + cell::Cell, +}; + +#[derive(Debug, Clone, Copy)] +struct Counter { + live: isize, + peak: isize, +} + +std::thread_local! { + static COUNTER: Cell> = const { Cell::new(None) }; +} + +fn add(bytes: isize) { + let _ = COUNTER.try_with(|counter| { + if let Some(mut c) = counter.get() { + c.live += bytes; + c.peak = c.peak.max(c.live); + counter.set(Some(c)); + } + }); +} + +struct Tracking; + +unsafe impl GlobalAlloc for Tracking { + unsafe fn alloc(&self, layout: Layout) -> *mut u8 { + let ptr = unsafe { System.alloc(layout) }; + if !ptr.is_null() { + add(layout.size() as isize); + } + ptr + } + unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { + add(-(layout.size() as isize)); + unsafe { System.dealloc(ptr, layout) } + } + unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, size: usize) -> *mut u8 { + // A move holds the old and the new block at once, so the peak counts both + add(size as isize); + let result = unsafe { System.realloc(ptr, layout, size) }; + if result.is_null() { + add(-(size as isize)); + } else { + add(-(layout.size() as isize)); + } + result + } +} + +#[global_allocator] +static ALLOCATOR: Tracking = Tracking; + +/// What a call allocated on the calling thread +#[derive(Debug, Clone, Copy)] +pub struct Allocated { + /// Bytes still allocated when the call returned, its result included + pub retained: isize, + /// The most bytes the call held at once, above what was allocated before it + pub peak: usize, +} + +/// Runs `f` on this thread and reports what it allocated. Not reentrant. +pub fn measure(f: impl FnOnce() -> T) -> (T, Allocated) { + COUNTER.with(|c| c.set(Some(Counter { live: 0, peak: 0 }))); + let value = f(); + let counter = COUNTER.with(|c| c.replace(None)).expect("measuring"); + ( + value, + Allocated { + retained: counter.live, + peak: counter.peak.max(0) as usize, + }, + ) +} + +/// Bytes `f` still holds allocated when it returns, its result included +pub fn retained(f: impl FnOnce() -> T) -> (T, isize) { + let (value, allocated) = measure(f); + (value, allocated.retained) +} diff --git a/src/utils/json/flatten.rs b/src/utils/json/flatten.rs index 2bb68c4fa..13a25575b 100644 --- a/src/utils/json/flatten.rs +++ b/src/utils/json/flatten.rs @@ -142,6 +142,7 @@ pub fn flatten( time_partition_limit: Option, custom_partition: Option<&String>, validation_required: bool, + budget: &mut FlattenBudget, ) -> Result<(), JsonFlattenError> { match nested_value { Value::Object(nested_dict) => { @@ -156,7 +157,7 @@ pub fn flatten( } let original = std::mem::take(nested_dict); let mut map = Map::with_capacity(original.len()); - flatten_object(&mut map, None, original, separator)?; + flatten_object(&mut map, None, original, separator, budget)?; *nested_dict = map; } Value::Array(arr) => { @@ -169,6 +170,7 @@ pub fn flatten( time_partition_limit, custom_partition, validation_required, + budget, )?; } } @@ -311,6 +313,7 @@ fn flatten_object( parent_key: Option<&str>, nested_map: Map, separator: &str, + budget: &mut FlattenBudget, ) -> Result<(), JsonFlattenError> { for (key, mut value) in nested_map { let new_key = match parent_key { @@ -321,10 +324,10 @@ fn flatten_object( match &mut value { Value::Object(obj) => { let obj = std::mem::take(obj); - flatten_object(output_map, Some(&new_key), obj, separator)?; + flatten_object(output_map, Some(&new_key), obj, separator, budget)?; } Value::Array(arr) if arr.iter().any(Value::is_object) => { - flatten_array_objects(output_map, &new_key, arr, separator)?; + flatten_array_objects(output_map, &new_key, arr, separator, budget)?; } _ => { output_map.insert(new_key, value); @@ -334,21 +337,58 @@ fn flatten_object( Ok(()) } -// Flattens a nested JSON Array into the parent Map +// Flattens a nested JSON Array into the parent Map: one column (array) per distinct key of +// its objects, with a cell for every element, null where an element lacks the key. Every +// null cell is a `Value` of its own, so the cells added are charged to `budget` at that +// size before the columns are built: 3,600 objects with one distinct key each would +// otherwise hold 13 million cells, about 900 MiB. pub fn flatten_array_objects( output_map: &mut Map, parent_key: &str, arr: &mut [Value], separator: &str, + budget: &mut FlattenBudget, ) -> Result<(), JsonFlattenError> { - let mut columns: BTreeMap> = BTreeMap::new(); - - for (index, value) in arr.iter_mut().enumerate() { + // Each element flattened on its own first, to count the cells of the table + let mut elements: Vec>> = Vec::with_capacity(arr.len()); + let mut keys: BTreeMap<&str, ()> = BTreeMap::new(); + let mut present = 0usize; + for value in arr.iter_mut() { match value { Value::Object(nested_object) => { let mut output_map = Map::new(); let nested_object = std::mem::take(nested_object); - flatten_object(&mut output_map, Some(parent_key), nested_object, separator)?; + flatten_object( + &mut output_map, + Some(parent_key), + nested_object, + separator, + budget, + )?; + present += output_map.len(); + elements.push(Some(output_map)); + } + Value::Null => elements.push(None), + _ => return Err(JsonFlattenError::NonObjectInArray), + } + } + for element in elements.iter().flatten() { + keys.extend(element.keys().map(|key| (key.as_str(), ()))); + } + let nulls = keys + .len() + .saturating_mul(elements.len()) + .saturating_sub(present); + budget.charge_event(FlattenCost { + rows: 0, + bytes: nulls.saturating_mul(std::mem::size_of::()), + })?; + drop(keys); + + let mut columns: BTreeMap> = BTreeMap::new(); + for (index, element) in elements.into_iter().enumerate() { + match element { + Some(output_map) => { for (key, value) in output_map { let column = columns .entry(key) @@ -356,12 +396,11 @@ pub fn flatten_array_objects( column.push(value); } } - Value::Null => { + None => { for column in columns.values_mut() { column.push(Value::Null); } } - _ => return Err(JsonFlattenError::NonObjectInArray), } // Ensure all columns are extended with null values if they weren't updated in this iteration @@ -1523,7 +1562,10 @@ mod tests { Some(&key), std::num::NonZeroU32::new(1), None, - true + true, + &mut crate::utils::json::flatten::FlattenBudget::new( + crate::utils::json::flatten::GENEROUS_LIMITS + ) ), Err(JsonFlattenError::TimestampTooOld(_, 1, _)) )); @@ -1535,6 +1577,9 @@ mod tests { std::num::NonZeroU32::new(1), None, true, + &mut crate::utils::json::flatten::FlattenBudget::new( + crate::utils::json::flatten::GENEROUS_LIMITS, + ), ) .unwrap(); let mut old = json!({"ts": (now - chrono::Duration::hours(4)).to_rfc3339()}); @@ -1545,7 +1590,10 @@ mod tests { Some(&key), std::num::NonZeroU32::new(1), None, - true + true, + &mut crate::utils::json::flatten::FlattenBudget::new( + crate::utils::json::flatten::GENEROUS_LIMITS + ) ), Err(JsonFlattenError::TimestampTooOldRelative(_, 3, _, _)) )); @@ -1575,6 +1623,9 @@ mod tests { None, custom_partition, validation_required, + &mut crate::utils::json::flatten::FlattenBudget::new( + crate::utils::json::flatten::GENEROUS_LIMITS, + ), ) }; result @@ -1838,7 +1889,18 @@ mod tests { (json!({"a": {"b": 2}, "a_b": 1}), json!({"a_b": 1})), ] { let mut obj = input.clone(); - flatten(&mut obj, "_", None, None, None, false).unwrap(); + flatten( + &mut obj, + "_", + None, + None, + None, + false, + &mut crate::utils::json::flatten::FlattenBudget::new( + crate::utils::json::flatten::GENEROUS_LIMITS, + ), + ) + .unwrap(); if preserves_order { assert_eq!(obj, expected); } @@ -1852,7 +1914,18 @@ mod tests { #[test] fn flatten_drops_nested_empty_object() { let mut obj = json!({"a": {}, "b": {"c": {}}, "d": 1}); - flatten(&mut obj, "_", None, None, None, false).unwrap(); + flatten( + &mut obj, + "_", + None, + None, + None, + false, + &mut crate::utils::json::flatten::FlattenBudget::new( + crate::utils::json::flatten::GENEROUS_LIMITS, + ), + ) + .unwrap(); assert_eq!(obj, json!({"d": 1})); } @@ -1860,17 +1933,47 @@ mod tests { fn flatten_flat_object_still_validates() { let mut obj = json!({"a": "x.y", "b": 1}); assert!(matches!( - flatten(&mut obj, "_", None, None, Some(&"a".to_owned()), true), + flatten( + &mut obj, + "_", + None, + None, + Some(&"a".to_owned()), + true, + &mut crate::utils::json::flatten::FlattenBudget::new( + crate::utils::json::flatten::GENEROUS_LIMITS + ) + ), Err(JsonFlattenError::FieldContainsPeriod(_)) )); let mut obj = json!({"b": 1}); assert!(matches!( - flatten(&mut obj, "_", None, None, Some(&"a".to_owned()), true), + flatten( + &mut obj, + "_", + None, + None, + Some(&"a".to_owned()), + true, + &mut crate::utils::json::flatten::FlattenBudget::new( + crate::utils::json::flatten::GENEROUS_LIMITS + ) + ), Err(JsonFlattenError::FieldNotPartOfLog(_)) )); let mut obj = json!(1); assert!(matches!( - flatten(&mut obj, "_", None, None, None, false), + flatten( + &mut obj, + "_", + None, + None, + None, + false, + &mut crate::utils::json::flatten::FlattenBudget::new( + crate::utils::json::flatten::GENEROUS_LIMITS + ) + ), Err(JsonFlattenError::CannotFlatten) )); } @@ -1879,7 +1982,18 @@ mod tests { fn flatten_single_key_string() { let mut obj = json!({"key": "value"}); let expected = obj.clone(); - flatten(&mut obj, "_", None, None, None, false).unwrap(); + flatten( + &mut obj, + "_", + None, + None, + None, + false, + &mut crate::utils::json::flatten::FlattenBudget::new( + crate::utils::json::flatten::GENEROUS_LIMITS, + ), + ) + .unwrap(); assert_eq!(obj, expected); } @@ -1887,7 +2001,18 @@ mod tests { fn flatten_single_key_int() { let mut obj = json!({"key": 1}); let expected = obj.clone(); - flatten(&mut obj, "_", None, None, None, false).unwrap(); + flatten( + &mut obj, + "_", + None, + None, + None, + false, + &mut crate::utils::json::flatten::FlattenBudget::new( + crate::utils::json::flatten::GENEROUS_LIMITS, + ), + ) + .unwrap(); assert_eq!(obj, expected); } @@ -1895,7 +2020,18 @@ mod tests { fn flatten_multiple_key_value() { let mut obj = json!({"key1": 1, "key2": "value2"}); let expected = obj.clone(); - flatten(&mut obj, "_", None, None, None, false).unwrap(); + flatten( + &mut obj, + "_", + None, + None, + None, + false, + &mut crate::utils::json::flatten::FlattenBudget::new( + crate::utils::json::flatten::GENEROUS_LIMITS, + ), + ) + .unwrap(); assert_eq!(obj, expected); } @@ -1903,7 +2039,18 @@ mod tests { fn flatten_nested_single_key_value() { let mut obj = json!({"key": "value", "nested_key": {"key":"value"}}); let expected = json!({"key": "value", "nested_key.key": "value"}); - flatten(&mut obj, ".", None, None, None, false).unwrap(); + flatten( + &mut obj, + ".", + None, + None, + None, + false, + &mut crate::utils::json::flatten::FlattenBudget::new( + crate::utils::json::flatten::GENEROUS_LIMITS, + ), + ) + .unwrap(); assert_eq!(obj, expected); } @@ -1912,7 +2059,18 @@ mod tests { let mut obj = json!({"key": "value", "nested_key": {"key1":"value1", "key2": "value2"}}); let expected = json!({"key": "value", "nested_key.key1": "value1", "nested_key.key2": "value2"}); - flatten(&mut obj, ".", None, None, None, false).unwrap(); + flatten( + &mut obj, + ".", + None, + None, + None, + false, + &mut crate::utils::json::flatten::FlattenBudget::new( + crate::utils::json::flatten::GENEROUS_LIMITS, + ), + ) + .unwrap(); assert_eq!(obj, expected); } @@ -1920,7 +2078,18 @@ mod tests { fn nested_key_value_with_array() { let mut obj = json!({"key": "value", "nested_key": {"key1":[1,2,3]}}); let expected = json!({"key": "value", "nested_key.key1": [1,2,3]}); - flatten(&mut obj, ".", None, None, None, false).unwrap(); + flatten( + &mut obj, + ".", + None, + None, + None, + false, + &mut crate::utils::json::flatten::FlattenBudget::new( + crate::utils::json::flatten::GENEROUS_LIMITS, + ), + ) + .unwrap(); assert_eq!(obj, expected); } @@ -1928,7 +2097,18 @@ mod tests { fn nested_obj_array() { let mut obj = json!({"key": [{"a": "value0"}, {"a": "value1"}]}); let expected = json!({"key.a": ["value0", "value1"]}); - flatten(&mut obj, ".", None, None, None, false).unwrap(); + flatten( + &mut obj, + ".", + None, + None, + None, + false, + &mut crate::utils::json::flatten::FlattenBudget::new( + crate::utils::json::flatten::GENEROUS_LIMITS, + ), + ) + .unwrap(); assert_eq!(obj, expected); } @@ -1936,7 +2116,18 @@ mod tests { fn nested_obj_array_nulls() { let mut obj = json!({"key": [{"a": "value0"}, {"a": "value1", "b": "value1"}]}); let expected = json!({"key.a": ["value0", "value1"], "key.b": [null, "value1"]}); - flatten(&mut obj, ".", None, None, None, false).unwrap(); + flatten( + &mut obj, + ".", + None, + None, + None, + false, + &mut crate::utils::json::flatten::FlattenBudget::new( + crate::utils::json::flatten::GENEROUS_LIMITS, + ), + ) + .unwrap(); assert_eq!(obj, expected); } @@ -1944,7 +2135,18 @@ mod tests { fn nested_obj_array_nulls_reversed() { let mut obj = json!({"key": [{"a": "value0", "b": "value0"}, {"a": "value1"}]}); let expected = json!({"key.a": ["value0", "value1"], "key.b": ["value0", null]}); - flatten(&mut obj, ".", None, None, None, false).unwrap(); + flatten( + &mut obj, + ".", + None, + None, + None, + false, + &mut crate::utils::json::flatten::FlattenBudget::new( + crate::utils::json::flatten::GENEROUS_LIMITS, + ), + ) + .unwrap(); assert_eq!(obj, expected); } @@ -1952,7 +2154,18 @@ mod tests { fn nested_obj_array_nested_obj() { let mut obj = json!({"key": [{"a": {"p": 0}, "b": "value0"}, {"b": "value1"}]}); let expected = json!({"key.a.p": [0, null], "key.b": ["value0", "value1"]}); - flatten(&mut obj, ".", None, None, None, false).unwrap(); + flatten( + &mut obj, + ".", + None, + None, + None, + false, + &mut crate::utils::json::flatten::FlattenBudget::new( + crate::utils::json::flatten::GENEROUS_LIMITS, + ), + ) + .unwrap(); assert_eq!(obj, expected); } @@ -1960,14 +2173,38 @@ mod tests { fn nested_obj_array_nested_obj_array() { let mut obj = json!({"key": [{"a": [{"p": "value0", "q": "value0"}, {"p": "value1", "q": null}], "b": "value0"}, {"b": "value1"}]}); let expected = json!({"key.a.p": [["value0", "value1"], null], "key.a.q": [["value0", null], null], "key.b": ["value0", "value1"]}); - flatten(&mut obj, ".", None, None, None, false).unwrap(); + flatten( + &mut obj, + ".", + None, + None, + None, + false, + &mut crate::utils::json::flatten::FlattenBudget::new( + crate::utils::json::flatten::GENEROUS_LIMITS, + ), + ) + .unwrap(); assert_eq!(obj, expected); } #[test] fn flatten_mixed_object() { let mut obj = json!({"a": 42, "arr": ["1", {"key": "2"}, {"key": {"nested": "3"}}]}); - assert!(flatten(&mut obj, ".", None, None, None, false).is_err()); + assert!( + flatten( + &mut obj, + ".", + None, + None, + None, + false, + &mut crate::utils::json::flatten::FlattenBudget::new( + crate::utils::json::flatten::GENEROUS_LIMITS + ) + ) + .is_err() + ); } #[test] @@ -1981,7 +2218,14 @@ mod tests { }; let mut map = Map::new(); - flatten_array_objects(&mut map, "key", &mut arr, ".").unwrap(); + flatten_array_objects( + &mut map, + "key", + &mut arr, + ".", + &mut FlattenBudget::new(GENEROUS_LIMITS), + ) + .unwrap(); assert_eq!(map.len(), 2); assert_eq!(map.get("key.p").unwrap(), &json!([null, 2, null])); @@ -1995,7 +2239,14 @@ mod tests { }; let mut map = Map::new(); - flatten_array_objects(&mut map, "key", &mut arr, ".").unwrap(); + flatten_array_objects( + &mut map, + "key", + &mut arr, + ".", + &mut FlattenBudget::new(GENEROUS_LIMITS), + ) + .unwrap(); assert_eq!(map.len(), 2); assert_eq!(map.get("key.a").unwrap(), &json!([1, 2, null])); @@ -2009,7 +2260,14 @@ mod tests { }; let mut map = Map::new(); - flatten_array_objects(&mut map, "key", &mut arr, ".").unwrap(); + flatten_array_objects( + &mut map, + "key", + &mut arr, + ".", + &mut FlattenBudget::new(GENEROUS_LIMITS), + ) + .unwrap(); assert_eq!(map.len(), 3); assert_eq!(map.get("key.a").unwrap(), &json!([1, null, 3])); @@ -2028,7 +2286,14 @@ mod tests { }; let mut map = Map::new(); - flatten_array_objects(&mut map, "key", &mut arr, ".").unwrap(); + flatten_array_objects( + &mut map, + "key", + &mut arr, + ".", + &mut FlattenBudget::new(GENEROUS_LIMITS), + ) + .unwrap(); assert_eq!(map.len(), 3); assert_eq!(map.get("key.p").unwrap(), &json!([1, null, 3])); @@ -2047,7 +2312,14 @@ mod tests { }; let mut map = Map::new(); - flatten_array_objects(&mut map, "key", &mut arr, ".").unwrap(); + flatten_array_objects( + &mut map, + "key", + &mut arr, + ".", + &mut FlattenBudget::new(GENEROUS_LIMITS), + ) + .unwrap(); assert_eq!(map.len(), 3); assert_eq!(map.get("key.p").unwrap(), &json!([1, null, 3])); @@ -2060,22 +2332,74 @@ mod tests { let mut value = json!({ "a": 1, }); - assert!(flatten(&mut value, "_", None, None, Some(&"a".to_string()), true).is_ok()); + assert!( + flatten( + &mut value, + "_", + None, + None, + Some(&"a".to_string()), + true, + &mut crate::utils::json::flatten::FlattenBudget::new( + crate::utils::json::flatten::GENEROUS_LIMITS + ) + ) + .is_ok() + ); let mut value = json!({ "a": true, }); - assert!(flatten(&mut value, "_", None, None, Some(&"a".to_string()), true).is_ok()); + assert!( + flatten( + &mut value, + "_", + None, + None, + Some(&"a".to_string()), + true, + &mut crate::utils::json::flatten::FlattenBudget::new( + crate::utils::json::flatten::GENEROUS_LIMITS + ) + ) + .is_ok() + ); let mut value = json!({ "a": "yes", }); - assert!(flatten(&mut value, "_", None, None, Some(&"a".to_string()), true).is_ok()); + assert!( + flatten( + &mut value, + "_", + None, + None, + Some(&"a".to_string()), + true, + &mut crate::utils::json::flatten::FlattenBudget::new( + crate::utils::json::flatten::GENEROUS_LIMITS + ) + ) + .is_ok() + ); let mut value = json!({ "a": -1, }); - assert!(flatten(&mut value, "_", None, None, Some(&"a".to_string()), true).is_ok()); + assert!( + flatten( + &mut value, + "_", + None, + None, + Some(&"a".to_string()), + true, + &mut crate::utils::json::flatten::FlattenBudget::new( + crate::utils::json::flatten::GENEROUS_LIMITS + ) + ) + .is_ok() + ); } #[test] @@ -2084,7 +2408,18 @@ mod tests { "a": null, }); matches!( - flatten(&mut value, "_", None, None, Some(&"a".to_string()), true).unwrap_err(), + flatten( + &mut value, + "_", + None, + None, + Some(&"a".to_string()), + true, + &mut crate::utils::json::flatten::FlattenBudget::new( + crate::utils::json::flatten::GENEROUS_LIMITS + ) + ) + .unwrap_err(), JsonFlattenError::FieldEmptyOrNull(_) ); @@ -2092,7 +2427,18 @@ mod tests { "a": "", }); matches!( - flatten(&mut value, "_", None, None, Some(&"a".to_string()), true).unwrap_err(), + flatten( + &mut value, + "_", + None, + None, + Some(&"a".to_string()), + true, + &mut crate::utils::json::flatten::FlattenBudget::new( + crate::utils::json::flatten::GENEROUS_LIMITS + ) + ) + .unwrap_err(), JsonFlattenError::FieldEmptyOrNull(_) ); @@ -2100,7 +2446,18 @@ mod tests { "a": {"b": 1}, }); matches!( - flatten(&mut value, "_", None, None, Some(&"a".to_string()), true).unwrap_err(), + flatten( + &mut value, + "_", + None, + None, + Some(&"a".to_string()), + true, + &mut crate::utils::json::flatten::FlattenBudget::new( + crate::utils::json::flatten::GENEROUS_LIMITS + ) + ) + .unwrap_err(), JsonFlattenError::FieldIsObject(_) ); @@ -2108,7 +2465,18 @@ mod tests { "a": ["b", "c"], }); matches!( - flatten(&mut value, "_", None, None, Some(&"a".to_string()), true).unwrap_err(), + flatten( + &mut value, + "_", + None, + None, + Some(&"a".to_string()), + true, + &mut crate::utils::json::flatten::FlattenBudget::new( + crate::utils::json::flatten::GENEROUS_LIMITS + ) + ) + .unwrap_err(), JsonFlattenError::FieldIsArray(_) ); @@ -2116,7 +2484,18 @@ mod tests { "a": "b.c", }); matches!( - flatten(&mut value, "_", None, None, Some(&"a".to_string()), true).unwrap_err(), + flatten( + &mut value, + "_", + None, + None, + Some(&"a".to_string()), + true, + &mut crate::utils::json::flatten::FlattenBudget::new( + crate::utils::json::flatten::GENEROUS_LIMITS + ) + ) + .unwrap_err(), JsonFlattenError::FieldContainsPeriod(_) ); @@ -2124,7 +2503,18 @@ mod tests { "a": 1.0, }); matches!( - flatten(&mut value, "_", None, None, Some(&"a".to_string()), true).unwrap_err(), + flatten( + &mut value, + "_", + None, + None, + Some(&"a".to_string()), + true, + &mut crate::utils::json::flatten::FlattenBudget::new( + crate::utils::json::flatten::GENEROUS_LIMITS + ) + ) + .unwrap_err(), JsonFlattenError::FieldContainsPeriod(_) ); } @@ -2440,7 +2830,18 @@ mod tests { for row in rows { let mut row = row.clone(); if let Value::Object(_) = row { - flatten(&mut row, "_", None, None, None, false).unwrap(); + flatten( + &mut row, + "_", + None, + None, + None, + false, + &mut crate::utils::json::flatten::FlattenBudget::new( + crate::utils::json::flatten::GENEROUS_LIMITS, + ), + ) + .unwrap(); fields += row.as_object().unwrap().len(); } bytes += serde_json::to_vec(&row).unwrap().len(); @@ -2551,7 +2952,18 @@ mod tests { ] { let built = generic_flattening_with_limits(&value, GENEROUS_LIMITS).unwrap(); let mut flattened = Value::Array(built.clone()); - flatten(&mut flattened, "_", None, None, None, false).unwrap(); + flatten( + &mut flattened, + "_", + None, + None, + None, + false, + &mut crate::utils::json::flatten::FlattenBudget::new( + crate::utils::json::flatten::GENEROUS_LIMITS, + ), + ) + .unwrap(); assert_eq!(flattened, expected, "input: {value}"); let cost = flatten_pipeline_cost(&value, &GENEROUS_LIMITS).unwrap(); let expected = expected.as_array().unwrap(); diff --git a/src/utils/json/mod.rs b/src/utils/json/mod.rs index 1a7f72ee5..e0bb60fe9 100644 --- a/src/utils/json/mod.rs +++ b/src/utils/json/mod.rs @@ -85,6 +85,7 @@ fn flatten_json_body_inner( time_partition_limit, custom_partition, validation_required, + budget, )?; Ok(nested_value) } @@ -121,6 +122,7 @@ pub fn apply_generic_flattening_for_partition( time_partition_limit, custom_partition, true, + budget, )?; Ok(vec![nested_value]) } else { @@ -135,6 +137,7 @@ pub fn apply_generic_flattening_for_partition( time_partition_limit, custom_partition, true, + budget, )?; result.push(processed_item); } @@ -169,6 +172,7 @@ fn process_partitioned_element( time_partition_limit, custom_partition, true, + budget, )?; Ok(vec![nested_value]) } diff --git a/src/utils/json/strict.rs b/src/utils/json/strict.rs index 5851f925b..4232e67cb 100644 --- a/src/utils/json/strict.rs +++ b/src/utils/json/strict.rs @@ -438,51 +438,7 @@ mod tests { // serde_json::Map hides IndexMap's capacity. Compare retained allocation // bytes with the oracle as well as inspecting Vec capacities directly. - mod allocations { - use std::{ - alloc::{GlobalAlloc, Layout, System}, - cell::Cell, - }; - std::thread_local! { - static LIVE: Cell> = const { Cell::new(None) }; - } - struct Tracking; - fn add(bytes: isize) { - let _ = LIVE.try_with(|live| { - if let Some(n) = live.get() { - live.set(Some(n + bytes)); - } - }); - } - unsafe impl GlobalAlloc for Tracking { - unsafe fn alloc(&self, layout: Layout) -> *mut u8 { - let ptr = unsafe { System.alloc(layout) }; - if !ptr.is_null() { - add(layout.size() as isize); - } - ptr - } - unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { - add(-(layout.size() as isize)); - unsafe { System.dealloc(ptr, layout) } - } - unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, size: usize) -> *mut u8 { - let result = unsafe { System.realloc(ptr, layout, size) }; - if !result.is_null() { - add(size as isize - layout.size() as isize); - } - result - } - } - #[global_allocator] - static ALLOCATOR: Tracking = Tracking; - pub fn retained(f: impl FnOnce() -> T) -> (T, isize) { - LIVE.with(|n| n.set(Some(0))); - let value = f(); - let bytes = LIVE.with(|n| n.replace(None).unwrap()); - (value, bytes) - } - } + use crate::test_alloc as allocations; #[test] fn final_container_capacities_match_oracle() {