Skip to main content

micromegas_datafusion_extensions/histogram/
otel_codec.rs

1//! Compact, versioned binary encoding of OTLP histogram data points.
2use super::histogram_udaf::make_histogram_arrow_type;
3use crate::binary_column_accessor::create_binary_accessor;
4use anyhow::{Result, bail, ensure};
5use datafusion::arrow::array::ArrayRef;
6use datafusion::arrow::datatypes::DataType;
7use datafusion::error::DataFusionError;
8use datafusion::logical_expr::{Signature, TypeSignature, Volatility};
9
10const MAGIC: &[u8; 4] = b"MMOH";
11const VERSION: u8 = 1;
12const KIND_EXPLICIT: u8 = 1;
13const KIND_EXPONENTIAL: u8 = 2;
14const HAS_SUM: u8 = 1;
15const HAS_MIN: u8 = 2;
16const HAS_MAX: u8 = 4;
17
18/// Populated buckets of one sign of an exponential histogram: `counts[i]` is the bucket at index
19/// `offset + i`.
20#[derive(Debug, Clone, PartialEq, Eq, Default)]
21pub struct ExpBuckets {
22    pub offset: i32,
23    pub counts: Vec<u64>,
24}
25
26/// Bucket layout of a histogram.
27#[derive(Debug, Clone, PartialEq)]
28pub enum OtelBuckets {
29    /// `counts.len() == bounds.len() + 1`
30    Explicit { bounds: Vec<f64>, counts: Vec<u64> },
31    Exponential {
32        scale: i32,
33        zero_count: u64,
34        zero_threshold: f64,
35        positive: ExpBuckets,
36        negative: ExpBuckets,
37    },
38}
39
40/// One bucket of a histogram, in a layout-independent form.
41#[derive(Debug, Clone, Copy, PartialEq)]
42pub struct Bucket {
43    pub lower: f64,
44    pub upper: f64,
45    pub count: u64,
46    /// true for non-zero buckets of an exponential histogram, which interpolate log-linearly
47    pub exponential: bool,
48}
49
50/// A decoded OTLP histogram data point.
51#[derive(Debug, Clone, PartialEq)]
52pub struct OtelHistogram {
53    pub count: u64,
54    pub sum: Option<f64>,
55    pub min: Option<f64>,
56    pub max: Option<f64>,
57    pub buckets: OtelBuckets,
58}
59
60fn put_uleb(out: &mut Vec<u8>, mut v: u64) {
61    loop {
62        let byte = (v & 0x7f) as u8;
63        v >>= 7;
64        if v == 0 {
65            out.push(byte);
66            return;
67        }
68        out.push(byte | 0x80);
69    }
70}
71
72fn put_sleb(out: &mut Vec<u8>, mut v: i64) {
73    loop {
74        let byte = (v & 0x7f) as u8;
75        v >>= 7;
76        let done = (v == 0 && byte & 0x40 == 0) || (v == -1 && byte & 0x40 != 0);
77        if done {
78            out.push(byte);
79            return;
80        }
81        out.push(byte | 0x80);
82    }
83}
84
85fn put_f64(out: &mut Vec<u8>, v: f64) {
86    out.extend_from_slice(&v.to_le_bytes());
87}
88
89fn put_exp_buckets(out: &mut Vec<u8>, b: &ExpBuckets) {
90    put_sleb(out, i64::from(b.offset));
91    put_uleb(out, b.counts.len() as u64);
92    for c in &b.counts {
93        put_uleb(out, *c);
94    }
95}
96
97struct Reader<'a> {
98    bytes: &'a [u8],
99    pos: usize,
100}
101
102impl<'a> Reader<'a> {
103    fn take(&mut self, n: usize) -> Result<&'a [u8]> {
104        ensure!(
105            self.bytes.len() - self.pos >= n,
106            "truncated OTel histogram blob"
107        );
108        let s = &self.bytes[self.pos..self.pos + n];
109        self.pos += n;
110        Ok(s)
111    }
112
113    fn u8(&mut self) -> Result<u8> {
114        Ok(self.take(1)?[0])
115    }
116
117    fn f64(&mut self) -> Result<f64> {
118        let b = self.take(8)?;
119        Ok(f64::from_le_bytes(b.try_into().expect("8 bytes")))
120    }
121
122    fn uleb(&mut self) -> Result<u64> {
123        let mut result = 0u64;
124        let mut shift = 0u32;
125        loop {
126            let byte = self.u8()?;
127            ensure!(shift < 64, "varint too long in OTel histogram blob");
128            result |= u64::from(byte & 0x7f) << shift;
129            if byte & 0x80 == 0 {
130                return Ok(result);
131            }
132            shift += 7;
133        }
134    }
135
136    fn sleb(&mut self) -> Result<i64> {
137        let mut result = 0i64;
138        let mut shift = 0u32;
139        loop {
140            let byte = self.u8()?;
141            ensure!(shift < 64, "varint too long in OTel histogram blob");
142            result |= i64::from(byte & 0x7f) << shift;
143            shift += 7;
144            if byte & 0x80 == 0 {
145                if shift < 64 && byte & 0x40 != 0 {
146                    result |= -1i64 << shift;
147                }
148                return Ok(result);
149            }
150        }
151    }
152
153    // A length must be coverable by the remaining bytes (every element takes at least one byte),
154    // which stops a corrupt blob from requesting a huge allocation.
155    fn len(&mut self, min_bytes_per_item: usize) -> Result<usize> {
156        let n = self.uleb()?;
157        let remaining = (self.bytes.len() - self.pos) as u64;
158        ensure!(
159            n.saturating_mul(min_bytes_per_item as u64) <= remaining,
160            "truncated OTel histogram blob"
161        );
162        Ok(n as usize)
163    }
164
165    fn exp_buckets(&mut self) -> Result<ExpBuckets> {
166        let offset = i32::try_from(self.sleb()?)?;
167        let n = self.len(1)?;
168        let mut counts = Vec::with_capacity(n);
169        for _ in 0..n {
170            counts.push(self.uleb()?);
171        }
172        Ok(ExpBuckets { offset, counts })
173    }
174}
175
176/// Valid range of the OTLP exponential histogram scale.
177pub const MIN_EXP_SCALE: i32 = -10;
178pub const MAX_EXP_SCALE: i32 = 20;
179
180fn exp_bounds(scale: i32, index: i64) -> f64 {
181    (index as f64 * (-f64::from(scale)).exp2()).exp2()
182}
183
184impl OtelHistogram {
185    pub fn encode(&self) -> Vec<u8> {
186        let mut out = Vec::new();
187        out.extend_from_slice(MAGIC);
188        out.push(VERSION);
189        out.push(match self.buckets {
190            OtelBuckets::Explicit { .. } => KIND_EXPLICIT,
191            OtelBuckets::Exponential { .. } => KIND_EXPONENTIAL,
192        });
193        let mut present = 0u8;
194        if self.sum.is_some() {
195            present |= HAS_SUM;
196        }
197        if self.min.is_some() {
198            present |= HAS_MIN;
199        }
200        if self.max.is_some() {
201            present |= HAS_MAX;
202        }
203        out.push(present);
204        put_uleb(&mut out, self.count);
205        for v in [self.sum, self.min, self.max].into_iter().flatten() {
206            put_f64(&mut out, v);
207        }
208        match &self.buckets {
209            OtelBuckets::Explicit { bounds, counts } => {
210                put_uleb(&mut out, bounds.len() as u64);
211                for b in bounds {
212                    put_f64(&mut out, *b);
213                }
214                for c in counts {
215                    put_uleb(&mut out, *c);
216                }
217            }
218            OtelBuckets::Exponential {
219                scale,
220                zero_count,
221                zero_threshold,
222                positive,
223                negative,
224            } => {
225                put_sleb(&mut out, i64::from(*scale));
226                put_uleb(&mut out, *zero_count);
227                put_f64(&mut out, *zero_threshold);
228                put_exp_buckets(&mut out, positive);
229                put_exp_buckets(&mut out, negative);
230            }
231        }
232        out
233    }
234
235    /// Rejects anything that was not produced by [`OtelHistogram::encode`].
236    pub fn decode(bytes: &[u8]) -> Result<Self> {
237        let mut r = Reader { bytes, pos: 0 };
238        ensure!(
239            r.take(4).is_ok_and(|m| m == MAGIC),
240            "not an OTel histogram blob (bad magic)"
241        );
242        let version = r.u8()?;
243        ensure!(
244            version == VERSION,
245            "unsupported OTel histogram blob version {version}"
246        );
247        let kind = r.u8()?;
248        let present = r.u8()?;
249        let count = r.uleb()?;
250        let mut opt = |flag: u8| -> Result<Option<f64>> {
251            if present & flag != 0 {
252                Ok(Some(r.f64()?))
253            } else {
254                Ok(None)
255            }
256        };
257        let sum = opt(HAS_SUM)?;
258        let min = opt(HAS_MIN)?;
259        let max = opt(HAS_MAX)?;
260        let buckets = match kind {
261            KIND_EXPLICIT => {
262                let n = r.len(8)?;
263                let mut bounds = Vec::with_capacity(n);
264                for _ in 0..n {
265                    bounds.push(r.f64()?);
266                }
267                let mut counts = Vec::with_capacity(n + 1);
268                for _ in 0..=n {
269                    counts.push(r.uleb()?);
270                }
271                OtelBuckets::Explicit { bounds, counts }
272            }
273            KIND_EXPONENTIAL => {
274                let scale = i32::try_from(r.sleb()?)?;
275                ensure!(
276                    (MIN_EXP_SCALE..=MAX_EXP_SCALE).contains(&scale),
277                    "OTel exponential histogram scale {scale} out of range"
278                );
279                let zero_count = r.uleb()?;
280                let zero_threshold = r.f64()?;
281                let positive = r.exp_buckets()?;
282                let negative = r.exp_buckets()?;
283                OtelBuckets::Exponential {
284                    scale,
285                    zero_count,
286                    zero_threshold,
287                    positive,
288                    negative,
289                }
290            }
291            other => bail!("unknown OTel histogram kind {other}"),
292        };
293        ensure!(
294            r.pos == bytes.len(),
295            "trailing bytes in OTel histogram blob"
296        );
297        Ok(Self {
298            count,
299            sum,
300            min,
301            max,
302            buckets,
303        })
304    }
305
306    pub fn kind(&self) -> &'static str {
307        match self.buckets {
308            OtelBuckets::Explicit { .. } => "histogram",
309            OtelBuckets::Exponential { .. } => "exponential_histogram",
310        }
311    }
312
313    /// Buckets in ascending order, including empty ones.
314    pub fn bucket_list(&self) -> Vec<Bucket> {
315        match &self.buckets {
316            OtelBuckets::Explicit { bounds, counts } => {
317                let n = bounds.len();
318                if n == 0 {
319                    let mean = match self.sum {
320                        Some(sum) if self.count > 0 => Some(sum / self.count as f64),
321                        _ => None,
322                    };
323                    return vec![Bucket {
324                        lower: self.min.or(mean).unwrap_or(0.0),
325                        upper: self.max.or(mean).unwrap_or(0.0),
326                        count: counts.first().copied().unwrap_or(0),
327                        exponential: false,
328                    }];
329                }
330                counts
331                    .iter()
332                    .enumerate()
333                    .map(|(i, count)| {
334                        let lower = if i == 0 {
335                            self.min.map_or(bounds[0], |m| m.min(bounds[0]))
336                        } else {
337                            bounds[i - 1]
338                        };
339                        let upper = if i == n {
340                            self.max.map_or(bounds[n - 1], |m| m.max(bounds[n - 1]))
341                        } else {
342                            bounds[i]
343                        };
344                        Bucket {
345                            lower,
346                            upper,
347                            count: *count,
348                            exponential: false,
349                        }
350                    })
351                    .collect()
352            }
353            OtelBuckets::Exponential {
354                scale,
355                zero_count,
356                zero_threshold,
357                positive,
358                negative,
359            } => {
360                let mut out = Vec::with_capacity(positive.counts.len() + negative.counts.len() + 1);
361                for (j, count) in negative.counts.iter().enumerate().rev() {
362                    let index = i64::from(negative.offset) + j as i64;
363                    out.push(Bucket {
364                        lower: -exp_bounds(*scale, index + 1),
365                        upper: -exp_bounds(*scale, index),
366                        count: *count,
367                        exponential: true,
368                    });
369                }
370                out.push(Bucket {
371                    lower: -zero_threshold,
372                    upper: *zero_threshold,
373                    count: *zero_count,
374                    exponential: false,
375                });
376                for (j, count) in positive.counts.iter().enumerate() {
377                    let index = i64::from(positive.offset) + j as i64;
378                    out.push(Bucket {
379                        lower: exp_bounds(*scale, index),
380                        upper: exp_bounds(*scale, index + 1),
381                        count: *count,
382                        exponential: true,
383                    });
384                }
385                out
386            }
387        }
388    }
389}
390
391/// Estimates the value at `ratio` (0..=1) of the distribution. None when the histogram is empty.
392pub fn estimate_quantile(h: &OtelHistogram, ratio: f64) -> Option<f64> {
393    let buckets = h.bucket_list();
394    let total: u64 = buckets.iter().map(|b| b.count).sum();
395    if h.count == 0 || total == 0 {
396        return None;
397    }
398    let rank = ratio.clamp(0.0, 1.0) * total as f64;
399    let mut cumulative = 0u64;
400    let mut estimate = None;
401    for b in buckets.iter().filter(|b| b.count > 0) {
402        let before = cumulative as f64;
403        cumulative += b.count;
404        let r = ((rank - before) / b.count as f64).clamp(0.0, 1.0);
405        estimate = Some(interpolate(b, r));
406        if cumulative as f64 >= rank {
407            break;
408        }
409    }
410    estimate.map(|v| match (h.min, h.max) {
411        (Some(min), Some(max)) if min <= max => v.clamp(min, max),
412        (Some(min), None) => v.max(min),
413        (None, Some(max)) => v.min(max),
414        _ => v,
415    })
416}
417
418fn interpolate(b: &Bucket, r: f64) -> f64 {
419    if b.exponential && b.lower != 0.0 && b.upper != 0.0 {
420        b.lower * (b.upper / b.lower).powf(r)
421    } else {
422        b.lower + r * (b.upper - b.lower)
423    }
424}
425
426/// Representative value of a bucket for plotting: the arithmetic midpoint, or the sign-aware
427/// geometric midpoint for non-zero exponential buckets.
428pub fn bucket_center(b: &Bucket) -> f64 {
429    if b.exponential && b.lower != 0.0 && b.upper != 0.0 {
430        (b.lower * b.upper).sqrt().copysign(b.lower)
431    } else {
432        (b.lower + b.upper) / 2.0
433    }
434}
435
436/// True for the column types an encoded OTel histogram can arrive in.
437pub fn is_otel_blob_type(data_type: &DataType) -> bool {
438    matches!(data_type, DataType::Binary | DataType::BinaryView)
439}
440
441/// Signature accepting the native histogram struct or an OTel histogram blob, followed by
442/// `extra_args`.
443pub fn native_or_otel_signature(extra_args: &[DataType]) -> Signature {
444    let variant = |first: DataType| {
445        let mut types = vec![first];
446        types.extend_from_slice(extra_args);
447        TypeSignature::Exact(types)
448    };
449    Signature::one_of(
450        vec![
451            variant(make_histogram_arrow_type()),
452            variant(DataType::Binary),
453            variant(DataType::BinaryView),
454        ],
455        Volatility::Immutable,
456    )
457}
458
459/// Decodes every row of a Binary/BinaryView column; NULL rows stay `None`.
460pub fn decode_column(
461    func_name: &str,
462    array: &ArrayRef,
463) -> Result<Vec<Option<OtelHistogram>>, DataFusionError> {
464    let accessor = create_binary_accessor(array)
465        .map_err(|e| DataFusionError::Execution(format!("{func_name}: {e}")))?;
466    (0..accessor.len())
467        .map(|i| {
468            if accessor.is_null(i) {
469                return Ok(None);
470            }
471            OtelHistogram::decode(accessor.value(i))
472                .map(Some)
473                .map_err(|e| DataFusionError::Execution(format!("{func_name}: {e}")))
474        })
475        .collect()
476}