Skip to main content

micromegas_analytics/lakehouse/otel/
histograms_block_processor.rs

1//! `BlockProcessor` for OTLP `ResourceMetrics` payloads → `otel_histograms` rows.
2//!
3//! Handles Histogram and ExponentialHistogram data points, one row each. The bucket layout is
4//! sealed in the `histogram` column (see `OtelHistogram`); Sum/Gauge/Summary belong to
5//! `measures` and are ignored here.
6
7use super::attrs::attrs_to_jsonb;
8use super::metrics_block_processor::nonzero_time_nanos;
9use crate::lakehouse::{
10    block_partition_spec::BlockProcessor, partition_source_data::PartitionSourceBlock,
11    write_partition::PartitionRowSet,
12};
13use crate::metadata::ProcessMetadata;
14use crate::payload::fetch_block_payload;
15use crate::time::TimeRange;
16use anyhow::{Context, Result};
17use async_trait::async_trait;
18use chrono::DateTime;
19use datafusion::arrow::array::{
20    BinaryBuilder, BinaryDictionaryBuilder, PrimitiveBuilder, StringDictionaryBuilder,
21};
22use datafusion::arrow::datatypes::{Float64Type, Int32Type, TimestampNanosecondType, UInt64Type};
23use datafusion::arrow::record_batch::RecordBatch;
24use micromegas_datafusion_extensions::histogram::otel_codec::{
25    ExpBuckets, MAX_EXP_SCALE, MIN_EXP_SCALE, OtelBuckets, OtelHistogram,
26};
27use micromegas_telemetry::blob_storage::BlobStorage;
28use micromegas_tracing::prelude::*;
29use opentelemetry_proto::tonic::common::v1::KeyValue;
30use opentelemetry_proto::tonic::metrics::v1::{
31    DataPointFlags, ExponentialHistogramDataPoint, HistogramDataPoint, ResourceMetrics,
32    exponential_histogram_data_point::Buckets, metric::Data,
33};
34use prost::Message;
35use std::sync::Arc;
36
37/// Converts a Histogram data point; None when `bucket_counts` and `explicit_bounds` disagree.
38pub fn otel_histogram_from_point(dp: &HistogramDataPoint) -> Option<OtelHistogram> {
39    let counts = if dp.bucket_counts.is_empty() && dp.explicit_bounds.is_empty() {
40        vec![dp.count]
41    } else if dp.bucket_counts.len() == dp.explicit_bounds.len() + 1 {
42        dp.bucket_counts.clone()
43    } else {
44        return None;
45    };
46    Some(OtelHistogram {
47        count: dp.count,
48        sum: dp.sum,
49        min: dp.min,
50        max: dp.max,
51        buckets: OtelBuckets::Explicit {
52            bounds: dp.explicit_bounds.clone(),
53            counts,
54        },
55    })
56}
57
58fn exp_buckets(b: Option<&Buckets>) -> ExpBuckets {
59    b.map(|b| ExpBuckets {
60        offset: b.offset,
61        counts: b.bucket_counts.clone(),
62    })
63    .unwrap_or_default()
64}
65
66/// Converts an ExponentialHistogram data point; `None` if its scale is not decodable.
67pub fn otel_histogram_from_exp_point(dp: &ExponentialHistogramDataPoint) -> Option<OtelHistogram> {
68    if !(MIN_EXP_SCALE..=MAX_EXP_SCALE).contains(&dp.scale) {
69        return None;
70    }
71    Some(OtelHistogram {
72        count: dp.count,
73        sum: dp.sum,
74        min: dp.min,
75        max: dp.max,
76        buckets: OtelBuckets::Exponential {
77            scale: dp.scale,
78            zero_count: dp.zero_count,
79            zero_threshold: dp.zero_threshold,
80            positive: exp_buckets(dp.positive.as_ref()),
81            negative: exp_buckets(dp.negative.as_ref()),
82        },
83    })
84}
85
86#[derive(Debug)]
87pub struct OtelHistogramsBlockProcessor {}
88
89#[async_trait]
90impl BlockProcessor for OtelHistogramsBlockProcessor {
91    #[span_fn]
92    async fn process(
93        &self,
94        blob_storage: Arc<BlobStorage>,
95        src_block: Arc<PartitionSourceBlock>,
96    ) -> Result<Option<PartitionRowSet>> {
97        let payload = fetch_block_payload(
98            blob_storage,
99            sqlx::types::Uuid::from_bytes(*src_block.block.process_id.as_bytes()),
100            sqlx::types::Uuid::from_bytes(*src_block.block.stream_id.as_bytes()),
101            sqlx::types::Uuid::from_bytes(*src_block.block.block_id.as_bytes()),
102        )
103        .await
104        .with_context(|| "fetch_block_payload")?;
105
106        let resource_metrics = ResourceMetrics::decode(payload.objects.as_slice())
107            .with_context(|| "decoding ResourceMetrics proto")?;
108
109        let insert_time_nanos = src_block
110            .block
111            .insert_time
112            .timestamp_nanos_opt()
113            .with_context(|| "block.insert_time → nanos")?;
114        let mut builder = HistogramsRowBuilder::new(
115            src_block.process.process_id.to_string(),
116            src_block.block.stream_id.to_string(),
117            src_block.block.block_id.to_string(),
118            insert_time_nanos,
119            src_block.process.clone(),
120        );
121
122        for scope_metrics in &resource_metrics.scope_metrics {
123            let scope_name = scope_metrics
124                .scope
125                .as_ref()
126                .map(|s| s.name.clone())
127                .unwrap_or_default();
128
129            for metric in &scope_metrics.metrics {
130                let (name, unit) = (metric.name.as_str(), metric.unit.as_str());
131                match metric.data.as_ref() {
132                    Some(Data::Histogram(h)) => {
133                        for dp in &h.data_points {
134                            builder.append_point(
135                                (&scope_name, name, unit, h.aggregation_temporality),
136                                (dp.flags, dp.time_unix_nano, dp.start_time_unix_nano),
137                                &dp.attributes,
138                                otel_histogram_from_point(dp),
139                                "bucket_counts/explicit_bounds mismatch",
140                            )?;
141                        }
142                    }
143                    Some(Data::ExponentialHistogram(h)) => {
144                        for dp in &h.data_points {
145                            builder.append_point(
146                                (&scope_name, name, unit, h.aggregation_temporality),
147                                (dp.flags, dp.time_unix_nano, dp.start_time_unix_nano),
148                                &dp.attributes,
149                                otel_histogram_from_exp_point(dp),
150                                "scale out of range",
151                            )?;
152                        }
153                    }
154                    _ => {}
155                }
156            }
157        }
158
159        builder.finish()
160    }
161}
162
163fn is_no_recorded_value(flags: u32, metric_name: &str) -> bool {
164    let skip = flags & DataPointFlags::NoRecordedValueMask as u32 != 0;
165    if skip {
166        debug!("OTel histogram data point dropped (NO_RECORDED_VALUE): name={metric_name}");
167    }
168    skip
169}
170
171struct RowInputs<'a> {
172    scope_name: &'a str,
173    metric_name: &'a str,
174    unit: &'a str,
175    aggregation_temporality: i32,
176    time_unix_nano: u64,
177    start_time_unix_nano: u64,
178    attributes: &'a [KeyValue],
179    histogram: &'a OtelHistogram,
180}
181
182/// Per-block accumulator for `otel_histograms` rows.
183struct HistogramsRowBuilder {
184    process_ids: StringDictionaryBuilder<Int32Type>,
185    stream_ids: StringDictionaryBuilder<Int32Type>,
186    block_ids: StringDictionaryBuilder<Int32Type>,
187    insert_times: PrimitiveBuilder<TimestampNanosecondType>,
188    exes: StringDictionaryBuilder<Int32Type>,
189    usernames: StringDictionaryBuilder<Int32Type>,
190    computers: StringDictionaryBuilder<Int32Type>,
191    times: PrimitiveBuilder<TimestampNanosecondType>,
192    start_times: PrimitiveBuilder<TimestampNanosecondType>,
193    targets: StringDictionaryBuilder<Int32Type>,
194    names: StringDictionaryBuilder<Int32Type>,
195    units: StringDictionaryBuilder<Int32Type>,
196    kinds: StringDictionaryBuilder<Int32Type>,
197    temporalities: PrimitiveBuilder<Int32Type>,
198    counts: PrimitiveBuilder<UInt64Type>,
199    sums: PrimitiveBuilder<Float64Type>,
200    mins: PrimitiveBuilder<Float64Type>,
201    maxs: PrimitiveBuilder<Float64Type>,
202    histograms: BinaryBuilder,
203    properties: BinaryDictionaryBuilder<Int32Type>,
204    process_properties: BinaryDictionaryBuilder<Int32Type>,
205    audiences: StringDictionaryBuilder<Int32Type>,
206    min_time: i64,
207    max_time: i64,
208    nb_appended: usize,
209    process_id_str: String,
210    stream_id_str: String,
211    block_id_str: String,
212    insert_time_nanos: i64,
213    process: Arc<ProcessMetadata>,
214}
215
216impl HistogramsRowBuilder {
217    fn new(
218        process_id_str: String,
219        stream_id_str: String,
220        block_id_str: String,
221        insert_time_nanos: i64,
222        process: Arc<ProcessMetadata>,
223    ) -> Self {
224        Self {
225            process_ids: StringDictionaryBuilder::new(),
226            stream_ids: StringDictionaryBuilder::new(),
227            block_ids: StringDictionaryBuilder::new(),
228            insert_times: PrimitiveBuilder::new(),
229            exes: StringDictionaryBuilder::new(),
230            usernames: StringDictionaryBuilder::new(),
231            computers: StringDictionaryBuilder::new(),
232            times: PrimitiveBuilder::new(),
233            start_times: PrimitiveBuilder::new(),
234            targets: StringDictionaryBuilder::new(),
235            names: StringDictionaryBuilder::new(),
236            units: StringDictionaryBuilder::new(),
237            kinds: StringDictionaryBuilder::new(),
238            temporalities: PrimitiveBuilder::new(),
239            counts: PrimitiveBuilder::new(),
240            sums: PrimitiveBuilder::new(),
241            mins: PrimitiveBuilder::new(),
242            maxs: PrimitiveBuilder::new(),
243            histograms: BinaryBuilder::new(),
244            properties: BinaryDictionaryBuilder::new(),
245            process_properties: BinaryDictionaryBuilder::new(),
246            audiences: StringDictionaryBuilder::new(),
247            min_time: i64::MAX,
248            max_time: i64::MIN,
249            nb_appended: 0,
250            process_id_str,
251            stream_id_str,
252            block_id_str,
253            insert_time_nanos,
254            process,
255        }
256    }
257
258    fn append_point(
259        &mut self,
260        (scope_name, metric_name, unit, aggregation_temporality): (&str, &str, &str, i32),
261        (flags, time_unix_nano, start_time_unix_nano): (u32, u64, u64),
262        attributes: &[KeyValue],
263        histogram: Option<OtelHistogram>,
264        drop_reason: &str,
265    ) -> Result<()> {
266        if is_no_recorded_value(flags, metric_name) {
267            return Ok(());
268        }
269        let Some(histogram) = histogram else {
270            debug!("OTel histogram data point dropped ({drop_reason}): name={metric_name}");
271            return Ok(());
272        };
273        self.append(RowInputs {
274            scope_name,
275            metric_name,
276            unit,
277            aggregation_temporality,
278            time_unix_nano,
279            start_time_unix_nano,
280            attributes,
281            histogram: &histogram,
282        })
283    }
284
285    fn append(&mut self, row: RowInputs<'_>) -> Result<()> {
286        let Some(time_nanos) = nonzero_time_nanos("histogram", row.metric_name, row.time_unix_nano)
287        else {
288            return Ok(());
289        };
290        self.min_time = self.min_time.min(time_nanos);
291        self.max_time = self.max_time.max(time_nanos);
292
293        self.process_ids.append(&self.process_id_str)?;
294        self.stream_ids.append(&self.stream_id_str)?;
295        self.block_ids.append(&self.block_id_str)?;
296        self.insert_times.append_value(self.insert_time_nanos);
297        self.exes.append(&self.process.exe)?;
298        self.usernames.append(&self.process.username)?;
299        self.computers.append(&self.process.computer)?;
300        self.times.append_value(time_nanos);
301        self.start_times.append_option(
302            (row.start_time_unix_nano != 0).then_some(row.start_time_unix_nano as i64),
303        );
304        self.targets.append(row.scope_name)?;
305        self.names.append(row.metric_name)?;
306        self.units.append(row.unit)?;
307        self.kinds.append(row.histogram.kind())?;
308        self.temporalities.append_value(row.aggregation_temporality);
309        self.counts.append_value(row.histogram.count);
310        self.sums.append_option(row.histogram.sum);
311        self.mins.append_option(row.histogram.min);
312        self.maxs.append_option(row.histogram.max);
313        self.histograms.append_value(row.histogram.encode());
314        self.properties
315            .append(attrs_to_jsonb(row.attributes, &[]))?;
316        self.process_properties.append(&**self.process.properties)?;
317        self.audiences.append(&*self.process.audience)?;
318
319        self.nb_appended += 1;
320        Ok(())
321    }
322
323    fn finish(mut self) -> Result<Option<PartitionRowSet>> {
324        if self.nb_appended == 0 {
325            return Ok(None);
326        }
327        let schema = Arc::new(super::histograms_table::otel_histograms_table_schema());
328        let batch = RecordBatch::try_new(
329            schema,
330            vec![
331                Arc::new(self.process_ids.finish()),
332                Arc::new(self.stream_ids.finish()),
333                Arc::new(self.block_ids.finish()),
334                Arc::new(self.insert_times.finish().with_timezone_utc()),
335                Arc::new(self.exes.finish()),
336                Arc::new(self.usernames.finish()),
337                Arc::new(self.computers.finish()),
338                Arc::new(self.times.finish().with_timezone_utc()),
339                Arc::new(self.start_times.finish().with_timezone_utc()),
340                Arc::new(self.targets.finish()),
341                Arc::new(self.names.finish()),
342                Arc::new(self.units.finish()),
343                Arc::new(self.kinds.finish()),
344                Arc::new(self.temporalities.finish()),
345                Arc::new(self.counts.finish()),
346                Arc::new(self.sums.finish()),
347                Arc::new(self.mins.finish()),
348                Arc::new(self.maxs.finish()),
349                Arc::new(self.histograms.finish()),
350                Arc::new(self.properties.finish()),
351                Arc::new(self.process_properties.finish()),
352                Arc::new(self.audiences.finish()),
353            ],
354        )
355        .with_context(|| "building OTel histograms batch")?;
356
357        Ok(Some(PartitionRowSet::new(
358            TimeRange::new(
359                DateTime::from_timestamp_nanos(self.min_time),
360                DateTime::from_timestamp_nanos(self.max_time),
361            ),
362            batch,
363            None,
364        )))
365    }
366}