Skip to main content

micromegas_analytics/lakehouse/otel/
metrics_block_processor.rs

1//! `BlockProcessor` for OTLP `ResourceMetrics` payloads → `measures` rows.
2//!
3//! Handles Sum and Gauge data points directly, and Summary data points by fanning each
4//! one out into count/sum/min/max rows under suffixed metric names (`<metric>_count`,
5//! `_sum`, `_min`, `_max`); any other `quantile_values` entry (configured percentiles)
6//! is logged and dropped. Histogram and ExponentialHistogram are skipped here: they are
7//! materialized in `otel_histograms` by `OtelHistogramsBlockProcessor`. Aggregation temporality and
8//! `is_monotonic` ride along on per-row properties for Sum/Gauge.
9
10use super::attrs::attrs_to_jsonb;
11use crate::lakehouse::{
12    block_partition_spec::BlockProcessor, partition_source_data::PartitionSourceBlock,
13    write_partition::PartitionRowSet,
14};
15use crate::metadata::ProcessMetadata;
16use crate::payload::fetch_block_payload;
17use crate::time::TimeRange;
18use anyhow::{Context, Result};
19use async_trait::async_trait;
20use chrono::DateTime;
21use datafusion::arrow::array::{
22    BinaryDictionaryBuilder, PrimitiveBuilder, StringDictionaryBuilder,
23};
24use datafusion::arrow::datatypes::{Float64Type, Int32Type, TimestampNanosecondType};
25use datafusion::arrow::record_batch::RecordBatch;
26use jsonb::Value as JsonbValue;
27use micromegas_telemetry::blob_storage::BlobStorage;
28use micromegas_tracing::prelude::*;
29use opentelemetry_proto::tonic::metrics::v1::{
30    DataPointFlags, NumberDataPoint, ResourceMetrics, SummaryDataPoint, metric::Data,
31    number_data_point,
32};
33use prost::Message;
34use std::borrow::Cow;
35use std::sync::Arc;
36
37/// Returns `time_unix_nano` as `i64` unless it's zero, in which case the data point is
38/// logged and skipped. `kind` is the word used in the log message.
39pub(super) fn nonzero_time_nanos(
40    kind: &str,
41    metric_name: &str,
42    time_unix_nano: u64,
43) -> Option<i64> {
44    let time_nanos = time_unix_nano as i64;
45    if time_nanos == 0 {
46        debug!("OTel {kind} data point for {metric_name} dropped (time_unix_nano=0)");
47        return None;
48    }
49    Some(time_nanos)
50}
51
52#[derive(Debug)]
53pub struct OtelMetricsBlockProcessor {}
54
55#[async_trait]
56impl BlockProcessor for OtelMetricsBlockProcessor {
57    #[span_fn]
58    async fn process(
59        &self,
60        blob_storage: Arc<BlobStorage>,
61        src_block: Arc<PartitionSourceBlock>,
62    ) -> Result<Option<PartitionRowSet>> {
63        let payload = fetch_block_payload(
64            blob_storage,
65            sqlx::types::Uuid::from_bytes(*src_block.block.process_id.as_bytes()),
66            sqlx::types::Uuid::from_bytes(*src_block.block.stream_id.as_bytes()),
67            sqlx::types::Uuid::from_bytes(*src_block.block.block_id.as_bytes()),
68        )
69        .await
70        .with_context(|| "fetch_block_payload")?;
71
72        let resource_metrics = ResourceMetrics::decode(payload.objects.as_slice())
73            .with_context(|| "decoding ResourceMetrics proto")?;
74
75        let insert_time_nanos = src_block
76            .block
77            .insert_time
78            .timestamp_nanos_opt()
79            .with_context(|| "block.insert_time → nanos")?;
80        let mut builder = MeasuresRowBuilder::new(
81            src_block.process.process_id.to_string(),
82            src_block.block.stream_id.to_string(),
83            src_block.block.block_id.to_string(),
84            insert_time_nanos,
85            src_block.process.clone(),
86        );
87
88        for scope_metrics in &resource_metrics.scope_metrics {
89            let scope = scope_metrics.scope.as_ref();
90            let scope_name = scope.map(|s| s.name.clone()).unwrap_or_default();
91
92            for metric in &scope_metrics.metrics {
93                match metric.data.as_ref() {
94                    Some(Data::Sum(sum)) => {
95                        let extras = [
96                            (
97                                "otel.metric.aggregation_temporality".to_string(),
98                                JsonbValue::Number(jsonb::Number::Int64(
99                                    sum.aggregation_temporality as i64,
100                                )),
101                            ),
102                            (
103                                "otel.metric.is_monotonic".to_string(),
104                                JsonbValue::Bool(sum.is_monotonic),
105                            ),
106                            (
107                                "otel.metric.kind".to_string(),
108                                JsonbValue::String(Cow::Borrowed("sum")),
109                            ),
110                        ];
111                        for dp in &sum.data_points {
112                            builder.append(&scope_name, &metric.name, &metric.unit, dp, &extras)?;
113                        }
114                    }
115                    Some(Data::Gauge(gauge)) => {
116                        let extras = [(
117                            "otel.metric.kind".to_string(),
118                            JsonbValue::String(Cow::Borrowed("gauge")),
119                        )];
120                        for dp in &gauge.data_points {
121                            builder.append(&scope_name, &metric.name, &metric.unit, dp, &extras)?;
122                        }
123                    }
124                    Some(Data::Histogram(h)) => {
125                        debug!(
126                            "OTel histogram skipped in measures (materialized in otel_histograms): name={} unit={} points={}",
127                            metric.name,
128                            metric.unit,
129                            h.data_points.len()
130                        );
131                    }
132                    Some(Data::ExponentialHistogram(h)) => {
133                        debug!(
134                            "OTel exponential_histogram skipped in measures (materialized in otel_histograms): name={} unit={} points={}",
135                            metric.name,
136                            metric.unit,
137                            h.data_points.len()
138                        );
139                    }
140                    Some(Data::Summary(s)) => {
141                        for dp in &s.data_points {
142                            builder.append_summary(&scope_name, &metric.name, &metric.unit, dp)?;
143                        }
144                    }
145                    None => {}
146                }
147            }
148        }
149
150        builder.finish()
151    }
152}
153
154/// Per-block accumulator for `measures` rows: owns the column builders, time
155/// bounds, and per-block constants so `append` only takes per-data-point inputs.
156struct MeasuresRowBuilder {
157    process_ids: StringDictionaryBuilder<Int32Type>,
158    stream_ids: StringDictionaryBuilder<Int32Type>,
159    block_ids: StringDictionaryBuilder<Int32Type>,
160    insert_times: PrimitiveBuilder<TimestampNanosecondType>,
161    exes: StringDictionaryBuilder<Int32Type>,
162    usernames: StringDictionaryBuilder<Int32Type>,
163    computers: StringDictionaryBuilder<Int32Type>,
164    times: PrimitiveBuilder<TimestampNanosecondType>,
165    targets: StringDictionaryBuilder<Int32Type>,
166    names: StringDictionaryBuilder<Int32Type>,
167    units: StringDictionaryBuilder<Int32Type>,
168    values: PrimitiveBuilder<Float64Type>,
169    properties: BinaryDictionaryBuilder<Int32Type>,
170    process_properties: BinaryDictionaryBuilder<Int32Type>,
171    audiences: StringDictionaryBuilder<Int32Type>,
172    min_time: i64,
173    max_time: i64,
174    nb_appended: usize,
175    process_id_str: String,
176    stream_id_str: String,
177    block_id_str: String,
178    insert_time_nanos: i64,
179    process: Arc<ProcessMetadata>,
180}
181
182impl MeasuresRowBuilder {
183    fn new(
184        process_id_str: String,
185        stream_id_str: String,
186        block_id_str: String,
187        insert_time_nanos: i64,
188        process: Arc<ProcessMetadata>,
189    ) -> Self {
190        Self {
191            process_ids: StringDictionaryBuilder::new(),
192            stream_ids: StringDictionaryBuilder::new(),
193            block_ids: StringDictionaryBuilder::new(),
194            insert_times: PrimitiveBuilder::new(),
195            exes: StringDictionaryBuilder::new(),
196            usernames: StringDictionaryBuilder::new(),
197            computers: StringDictionaryBuilder::new(),
198            times: PrimitiveBuilder::new(),
199            targets: StringDictionaryBuilder::new(),
200            names: StringDictionaryBuilder::new(),
201            units: StringDictionaryBuilder::new(),
202            values: PrimitiveBuilder::new(),
203            properties: BinaryDictionaryBuilder::new(),
204            process_properties: BinaryDictionaryBuilder::new(),
205            audiences: StringDictionaryBuilder::new(),
206            min_time: i64::MAX,
207            max_time: i64::MIN,
208            nb_appended: 0,
209            process_id_str,
210            stream_id_str,
211            block_id_str,
212            insert_time_nanos,
213            process,
214        }
215    }
216
217    /// Appends one `measures` row for an already-extracted point. Shared tail of
218    /// `append` (Sum/Gauge) and `append_summary` (Summary). `props_jsonb` is the
219    /// already-serialized `properties` payload — attributes and derived extras
220    /// merged by `attrs_to_jsonb` — so a caller fanning one data point out into
221    /// several rows serializes it once.
222    fn append_row(
223        &mut self,
224        scope_name: &str,
225        metric_name: &str,
226        unit: &str,
227        time_nanos: i64,
228        value: f64,
229        props_jsonb: &[u8],
230    ) -> Result<()> {
231        self.min_time = self.min_time.min(time_nanos);
232        self.max_time = self.max_time.max(time_nanos);
233
234        self.process_ids.append(&self.process_id_str)?;
235        self.stream_ids.append(&self.stream_id_str)?;
236        self.block_ids.append(&self.block_id_str)?;
237        self.insert_times.append_value(self.insert_time_nanos);
238        self.exes.append(&self.process.exe)?;
239        self.usernames.append(&self.process.username)?;
240        self.computers.append(&self.process.computer)?;
241        self.times.append_value(time_nanos);
242        self.targets.append(scope_name)?;
243        self.names.append(metric_name)?;
244        self.units.append(unit)?;
245        self.values.append_value(value);
246        self.properties.append(props_jsonb)?;
247        self.process_properties.append(&**self.process.properties)?;
248        self.audiences.append(&*self.process.audience)?;
249
250        self.nb_appended += 1;
251        Ok(())
252    }
253
254    fn append(
255        &mut self,
256        scope_name: &str,
257        metric_name: &str,
258        unit: &str,
259        dp: &NumberDataPoint,
260        extras: &[(String, JsonbValue<'static>)],
261    ) -> Result<()> {
262        let Some(time_nanos) = nonzero_time_nanos("metric", metric_name, dp.time_unix_nano) else {
263            return Ok(());
264        };
265
266        let value = match dp.value.as_ref() {
267            Some(number_data_point::Value::AsDouble(d)) => *d,
268            Some(number_data_point::Value::AsInt(i)) => *i as f64,
269            None => {
270                debug!("OTel data point for {metric_name} has no value, skipping");
271                return Ok(());
272            }
273        };
274
275        self.append_row(
276            scope_name,
277            metric_name,
278            unit,
279            time_nanos,
280            value,
281            &attrs_to_jsonb(&dp.attributes, extras),
282        )
283    }
284
285    /// Fans a `SummaryDataPoint` out into rows for the four fixed statistics
286    /// (count, sum, min, max), each under its own suffixed metric name. Any
287    /// `quantile_values` entry other than `q=0.0`/`q=1.0` is logged and dropped —
288    /// configured percentiles are out of scope. No derived `otel.metric.*` extras
289    /// (aggregation_temporality/is_monotonic/kind) are added for Summary rows; the
290    /// per-point `dp.attributes` still populate `properties` the same as Sum/Gauge.
291    ///
292    /// A point flagged `NO_RECORDED_VALUE` is dropped entirely: `count`/`sum` are
293    /// non-optional proto scalars, so materializing it would inject real 0.0 samples
294    /// where the series actually has a gap.
295    fn append_summary(
296        &mut self,
297        scope_name: &str,
298        metric_name: &str,
299        unit: &str,
300        dp: &SummaryDataPoint,
301    ) -> Result<()> {
302        if dp.flags & DataPointFlags::NoRecordedValueMask as u32 != 0 {
303            debug!("OTel summary data point dropped (NO_RECORDED_VALUE): name={metric_name}");
304            return Ok(());
305        }
306
307        let Some(time_nanos) = nonzero_time_nanos("summary", metric_name, dp.time_unix_nano) else {
308            return Ok(());
309        };
310
311        // All four statistics share the same attribute map, so serialize it once.
312        let props_jsonb = attrs_to_jsonb(&dp.attributes, &[]);
313
314        self.append_row(
315            scope_name,
316            &format!("{metric_name}_count"),
317            "",
318            time_nanos,
319            dp.count as f64,
320            &props_jsonb,
321        )?;
322        self.append_row(
323            scope_name,
324            &format!("{metric_name}_sum"),
325            unit,
326            time_nanos,
327            dp.sum,
328            &props_jsonb,
329        )?;
330
331        let mut min_emitted = false;
332        let mut max_emitted = false;
333        for q in &dp.quantile_values {
334            if q.quantile == 0.0 {
335                if min_emitted {
336                    debug!(
337                        "OTel summary quantile dropped (duplicate q=0.0, _min already emitted): \
338                         name={metric_name}"
339                    );
340                    continue;
341                }
342                min_emitted = true;
343                self.append_row(
344                    scope_name,
345                    &format!("{metric_name}_min"),
346                    unit,
347                    time_nanos,
348                    q.value,
349                    &props_jsonb,
350                )?;
351            } else if q.quantile == 1.0 {
352                if max_emitted {
353                    debug!(
354                        "OTel summary quantile dropped (duplicate q=1.0, _max already emitted): \
355                         name={metric_name}"
356                    );
357                    continue;
358                }
359                max_emitted = true;
360                self.append_row(
361                    scope_name,
362                    &format!("{metric_name}_max"),
363                    unit,
364                    time_nanos,
365                    q.value,
366                    &props_jsonb,
367                )?;
368            } else {
369                debug!(
370                    "OTel summary quantile dropped (only count/sum/min/max are materialized): \
371                     name={metric_name} quantile={}",
372                    q.quantile
373                );
374            }
375        }
376        Ok(())
377    }
378
379    fn finish(mut self) -> Result<Option<PartitionRowSet>> {
380        if self.nb_appended == 0 {
381            return Ok(None);
382        }
383        let schema = Arc::new(crate::metrics_table::metrics_table_schema());
384        let batch = RecordBatch::try_new(
385            schema,
386            vec![
387                Arc::new(self.process_ids.finish()),
388                Arc::new(self.stream_ids.finish()),
389                Arc::new(self.block_ids.finish()),
390                Arc::new(self.insert_times.finish().with_timezone_utc()),
391                Arc::new(self.exes.finish()),
392                Arc::new(self.usernames.finish()),
393                Arc::new(self.computers.finish()),
394                Arc::new(self.times.finish().with_timezone_utc()),
395                Arc::new(self.targets.finish()),
396                Arc::new(self.names.finish()),
397                Arc::new(self.units.finish()),
398                Arc::new(self.values.finish()),
399                Arc::new(self.properties.finish()),
400                Arc::new(self.process_properties.finish()),
401                Arc::new(self.audiences.finish()),
402            ],
403        )
404        .with_context(|| "building OTel measures batch")?;
405
406        Ok(Some(PartitionRowSet::new(
407            TimeRange::new(
408                DateTime::from_timestamp_nanos(self.min_time),
409                DateTime::from_timestamp_nanos(self.max_time),
410            ),
411            batch,
412            None,
413        )))
414    }
415}