Skip to main content

datatypes/series/
histogram.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::sync::Arc;
16
17use arrow::array::{
18    Array, ArrayBuilder, ArrayRef, Float64Array, Float64Builder, Int32Array, Int32Builder,
19    Int64Array, Int64Builder, ListArray, ListBuilder, PrimitiveArray, StructArray,
20};
21use arrow::buffer::OffsetBuffer;
22use arrow::datatypes::{ArrowPrimitiveType, DataType, Field, Fields, Float64Type, Int32Type};
23use arrow::error::ArrowError;
24
25use crate::Result;
26use crate::error::InvalidSeriesSnafu;
27
28/// Reset hint retained by native histograms, including values unknown to this version.
29#[derive(Clone, Copy, Debug, PartialEq, Eq)]
30pub enum CounterResetHint {
31    /// The payload must be inspected to determine whether a reset occurred.
32    Unknown,
33    /// This is the first histogram after a counter reset.
34    CounterReset,
35    /// No counter reset occurred since the previous histogram.
36    NotCounterReset,
37    /// This is a gauge histogram, so counter resets do not apply.
38    Gauge,
39    /// A value not understood by this version.
40    Unrecognized(i32),
41}
42impl From<i32> for CounterResetHint {
43    fn from(value: i32) -> Self {
44        match value {
45            0 => Self::Unknown,
46            1 => Self::CounterReset,
47            2 => Self::NotCounterReset,
48            3 => Self::Gauge,
49            v => Self::Unrecognized(v),
50        }
51    }
52}
53impl From<CounterResetHint> for i32 {
54    fn from(value: CounterResetHint) -> Self {
55        match value {
56            CounterResetHint::Unknown => 0,
57            CounterResetHint::CounterReset => 1,
58            CounterResetHint::NotCounterReset => 2,
59            CounterResetHint::Gauge => 3,
60            CounterResetHint::Unrecognized(v) => v,
61        }
62    }
63}
64pub(crate) fn fields() -> Fields {
65    let list = |t| DataType::List(Arc::new(Field::new("item", t, false)));
66    vec![
67        Field::new("schema", DataType::Int32, false),
68        Field::new("zero_threshold", DataType::Float64, false),
69        Field::new("sum", DataType::Float64, false),
70        Field::new("count", DataType::Float64, false),
71        Field::new("zero_count", DataType::Float64, false),
72        Field::new("reset_hint", DataType::Int32, false),
73        Field::new("start_timestamp", DataType::Int64, true),
74        Field::new("custom_values", list(DataType::Float64), false),
75        Field::new("positive_span_offsets", list(DataType::Int32), false),
76        Field::new("positive_span_lengths", list(DataType::Int32), false),
77        Field::new("positive_buckets", list(DataType::Float64), false),
78        Field::new("negative_span_offsets", list(DataType::Int32), false),
79        Field::new("negative_span_lengths", list(DataType::Int32), false),
80        Field::new("negative_buckets", list(DataType::Float64), false),
81    ]
82    .into()
83}
84fn invalid<T>(reason: impl Into<String>) -> Result<T> {
85    Err(InvalidSeriesSnafu {
86        reason: reason.into(),
87    }
88    .build())
89}
90fn arrow_result<T>(r: std::result::Result<T, ArrowError>) -> Result<T> {
91    r.map_err(|e| {
92        InvalidSeriesSnafu {
93            reason: format!("invalid histogram Arrow array: {e}"),
94        }
95        .build()
96    })
97}
98
99/// A borrowed set of spans and absolute bucket counts.
100#[derive(Clone, Copy, Debug)]
101pub struct BucketSideView<'a> {
102    /// Span offsets.
103    pub span_offsets: &'a [i32],
104    /// Span lengths.
105    pub span_lengths: &'a [i32],
106    /// Absolute bucket counts.
107    pub buckets: &'a [f64],
108}
109/// A borrowed histogram row.
110#[derive(Clone, Copy, Debug)]
111pub struct HistogramView<'a> {
112    /// Histogram schema.
113    pub schema: i32,
114    /// Zero bucket threshold.
115    pub zero_threshold: f64,
116    /// Sum of observations.
117    pub sum: f64,
118    /// Total count.
119    pub count: f64,
120    /// Count in the zero bucket.
121    pub zero_count: f64,
122    /// Counter reset hint.
123    pub reset_hint: CounterResetHint,
124    /// Optional start timestamp in milliseconds.
125    pub start_timestamp: Option<i64>,
126    /// Custom bucket bounds.
127    pub custom_values: &'a [f64],
128    /// Positive bucket side.
129    pub positive: BucketSideView<'a>,
130    /// Negative bucket side.
131    pub negative: BucketSideView<'a>,
132}
133
134#[derive(Debug)]
135struct HistogramList<T: ArrowPrimitiveType> {
136    offsets: OffsetBuffer<i32>,
137    values: PrimitiveArray<T>,
138}
139impl<T: ArrowPrimitiveType> HistogramList<T> {
140    fn try_new(a: &ListArray) -> Result<Self> {
141        let v = a
142            .values()
143            .as_any()
144            .downcast_ref::<PrimitiveArray<T>>()
145            .ok_or_else(|| {
146                InvalidSeriesSnafu {
147                    reason: "histogram list item type mismatch".to_string(),
148                }
149                .build()
150            })?;
151        if a.null_count() != 0 || v.null_count() != 0 {
152            return invalid("histogram list rows and items must not be null");
153        }
154        Ok(Self {
155            offsets: a.offsets().clone(),
156            values: v.clone(),
157        })
158    }
159    fn view(&self, row: usize) -> &[T::Native] {
160        let s = self.offsets[row] as usize;
161        let e = self.offsets[row + 1] as usize;
162        &self.values.values()[s..e]
163    }
164}
165/// Columnar owner of native histogram rows.
166#[derive(Debug)]
167pub struct HistogramBatch {
168    array: StructArray,
169    schema: Int32Array,
170    threshold: Float64Array,
171    sum: Float64Array,
172    count: Float64Array,
173    zero: Float64Array,
174    hint: Int32Array,
175    start: Int64Array,
176    custom: HistogramList<Float64Type>,
177    po: HistogramList<Int32Type>,
178    pl: HistogramList<Int32Type>,
179    pb: HistogramList<Float64Type>,
180    no: HistogramList<Int32Type>,
181    nl: HistogramList<Int32Type>,
182    nb: HistogramList<Float64Type>,
183}
184impl HistogramBatch {
185    /// Validates and wraps an Arrow struct with the required ordered schema.
186    pub fn try_from_arrow(array: StructArray) -> Result<Self> {
187        if array.fields() != &fields() {
188            return invalid("histogram fields, order, types, or nullability mismatch");
189        }
190        if array.null_count() != 0 {
191            return invalid("histogram struct rows must not be null");
192        }
193        let c = array.columns();
194        if c.iter()
195            .enumerate()
196            .any(|(i, a)| i != 6 && a.null_count() != 0)
197        {
198            return invalid("non-nullable histogram column contains null");
199        }
200        macro_rules! col {
201            ($i:expr,$t:ty) => {
202                c[$i].as_any().downcast_ref::<$t>().cloned().ok_or_else(|| {
203                    InvalidSeriesSnafu {
204                        reason: format!("histogram column {} type mismatch", $i),
205                    }
206                    .build()
207                })
208            };
209        }
210        macro_rules! list {
211            ($i:expr,$t:ty) => {{
212                let a = c[$i].as_any().downcast_ref::<ListArray>().ok_or_else(|| {
213                    InvalidSeriesSnafu {
214                        reason: format!("histogram list column {} type mismatch", $i),
215                    }
216                    .build()
217                })?;
218                HistogramList::<$t>::try_new(a)?
219            }};
220        }
221        let batch = Self {
222            schema: col!(0, Int32Array)?,
223            threshold: col!(1, Float64Array)?,
224            sum: col!(2, Float64Array)?,
225            count: col!(3, Float64Array)?,
226            zero: col!(4, Float64Array)?,
227            hint: col!(5, Int32Array)?,
228            start: col!(6, Int64Array)?,
229            custom: list!(7, Float64Type),
230            po: list!(8, Int32Type),
231            pl: list!(9, Int32Type),
232            pb: list!(10, Float64Type),
233            no: list!(11, Int32Type),
234            nl: list!(12, Int32Type),
235            nb: list!(13, Float64Type),
236            array,
237        };
238        for i in 0..batch.len() {
239            validate_spans(batch.po.view(i), batch.pl.view(i), batch.pb.view(i).len())?;
240            validate_spans(batch.no.view(i), batch.nl.view(i), batch.nb.view(i).len())?
241        }
242        Ok(batch)
243    }
244    /// Returns the owning Arrow struct array.
245    pub fn as_arrow(&self) -> &StructArray {
246        &self.array
247    }
248    /// Number of rows.
249    pub fn len(&self) -> usize {
250        self.array.len()
251    }
252    /// Whether there are no rows.
253    pub fn is_empty(&self) -> bool {
254        self.array.is_empty()
255    }
256    /// Returns a borrowed row, or `None` when out of bounds.
257    pub fn view(&self, i: usize) -> Option<HistogramView<'_>> {
258        if i >= self.len() {
259            return None;
260        }
261        Some(HistogramView {
262            schema: self.schema.value(i),
263            zero_threshold: self.threshold.value(i),
264            sum: self.sum.value(i),
265            count: self.count.value(i),
266            zero_count: self.zero.value(i),
267            reset_hint: self.hint.value(i).into(),
268            start_timestamp: self.start.is_valid(i).then(|| self.start.value(i)),
269            custom_values: self.custom.view(i),
270            positive: BucketSideView {
271                span_offsets: self.po.view(i),
272                span_lengths: self.pl.view(i),
273                buckets: self.pb.view(i),
274            },
275            negative: BucketSideView {
276                span_offsets: self.no.view(i),
277                span_lengths: self.nl.view(i),
278                buckets: self.nb.view(i),
279            },
280        })
281    }
282}
283fn validate_spans(offsets: &[i32], lengths: &[i32], buckets: usize) -> Result<()> {
284    if offsets.len() != lengths.len() {
285        return invalid("span offsets and lengths differ");
286    }
287    let mut cursor = 0i32;
288    let mut total = 0usize;
289    for (i, (&offset, &length)) in offsets.iter().zip(lengths).enumerate() {
290        if length < 0 || (i > 0 && offset < 0) {
291            return invalid("negative span length or noninitial offset");
292        }
293        if i == 0 {
294            cursor = offset
295        } else {
296            cursor = cursor.checked_add(offset).ok_or_else(|| {
297                InvalidSeriesSnafu {
298                    reason: "span index overflow".to_string(),
299                }
300                .build()
301            })?
302        }
303        total = total.checked_add(length as usize).ok_or_else(|| {
304            InvalidSeriesSnafu {
305                reason: "bucket count overflow".to_string(),
306            }
307            .build()
308        })?;
309        cursor = cursor.checked_add(length).ok_or_else(|| {
310            InvalidSeriesSnafu {
311                reason: "span cursor overflow".to_string(),
312            }
313            .build()
314        })?;
315    }
316    if total != buckets {
317        return invalid("span lengths do not match bucket count");
318    }
319    Ok(())
320}
321
322/// Builds a histogram batch directly in Arrow builders.
323pub struct HistogramBatchBuilder {
324    schema: Int32Builder,
325    threshold: Float64Builder,
326    sum: Float64Builder,
327    count: Float64Builder,
328    zero: Float64Builder,
329    hint: Int32Builder,
330    start: Int64Builder,
331    custom: ListBuilder<Float64Builder>,
332    po: ListBuilder<Int32Builder>,
333    pl: ListBuilder<Int32Builder>,
334    pb: ListBuilder<Float64Builder>,
335    no: ListBuilder<Int32Builder>,
336    nl: ListBuilder<Int32Builder>,
337    nb: ListBuilder<Float64Builder>,
338    rows: usize,
339}
340impl Default for HistogramBatchBuilder {
341    fn default() -> Self {
342        Self::new()
343    }
344}
345impl HistogramBatchBuilder {
346    /// Creates an empty builder.
347    pub fn new() -> Self {
348        // Avoid reserving Arrow's large default capacity for small histogram batches.
349        Self {
350            schema: Int32Builder::with_capacity(0),
351            threshold: Float64Builder::with_capacity(0),
352            sum: Float64Builder::with_capacity(0),
353            count: Float64Builder::with_capacity(0),
354            zero: Float64Builder::with_capacity(0),
355            hint: Int32Builder::with_capacity(0),
356            start: Int64Builder::with_capacity(0),
357            custom: lb64(),
358            po: lb32(),
359            pl: lb32(),
360            pb: lb64(),
361            no: lb32(),
362            nl: lb32(),
363            nb: lb64(),
364            rows: 0,
365        }
366    }
367    /// Validates and appends a row, returning its index without staging bucket vectors.
368    pub fn push(&mut self, r: HistogramView<'_>) -> Result<u32> {
369        preflight(
370            r,
371            self.rows,
372            [
373                self.custom.values_ref().len(),
374                self.po.values_ref().len(),
375                self.pl.values_ref().len(),
376                self.pb.values_ref().len(),
377                self.no.values_ref().len(),
378                self.nl.values_ref().len(),
379                self.nb.values_ref().len(),
380            ],
381        )?;
382        let index = u32::try_from(self.rows).map_err(|_| {
383            InvalidSeriesSnafu {
384                reason: "histogram row index overflow".to_string(),
385            }
386            .build()
387        })?;
388        self.schema.append_value(r.schema);
389        self.threshold.append_value(r.zero_threshold);
390        self.sum.append_value(r.sum);
391        self.count.append_value(r.count);
392        self.zero.append_value(r.zero_count);
393        self.hint.append_value(r.reset_hint.into());
394        if let Some(v) = r.start_timestamp {
395            self.start.append_value(v)
396        } else {
397            self.start.append_null()
398        }
399        append64(&mut self.custom, r.custom_values);
400        append32(&mut self.po, r.positive.span_offsets);
401        append32(&mut self.pl, r.positive.span_lengths);
402        append64(&mut self.pb, r.positive.buckets);
403        append32(&mut self.no, r.negative.span_offsets);
404        append32(&mut self.nl, r.negative.span_lengths);
405        append64(&mut self.nb, r.negative.buckets);
406        self.rows += 1;
407        Ok(index)
408    }
409    /// Finishes by transferring builder buffers to the batch.
410    pub fn finish(mut self) -> Result<Arc<HistogramBatch>> {
411        let arrays: Vec<ArrayRef> = vec![
412            Arc::new(self.schema.finish()),
413            Arc::new(self.threshold.finish()),
414            Arc::new(self.sum.finish()),
415            Arc::new(self.count.finish()),
416            Arc::new(self.zero.finish()),
417            Arc::new(self.hint.finish()),
418            Arc::new(self.start.finish()),
419            Arc::new(self.custom.finish()),
420            Arc::new(self.po.finish()),
421            Arc::new(self.pl.finish()),
422            Arc::new(self.pb.finish()),
423            Arc::new(self.no.finish()),
424            Arc::new(self.nl.finish()),
425            Arc::new(self.nb.finish()),
426        ];
427        Ok(Arc::new(HistogramBatch::try_from_arrow(arrow_result(
428            StructArray::try_new(fields(), arrays, None),
429        )?)?))
430    }
431}
432fn preflight(r: HistogramView<'_>, rows: usize, existing: [usize; 7]) -> Result<()> {
433    if rows >= u32::MAX as usize {
434        return invalid("histogram row index overflow");
435    }
436    let added = [
437        r.custom_values.len(),
438        r.positive.span_offsets.len(),
439        r.positive.span_lengths.len(),
440        r.positive.buckets.len(),
441        r.negative.span_offsets.len(),
442        r.negative.span_lengths.len(),
443        r.negative.buckets.len(),
444    ];
445    for (old, new) in existing.into_iter().zip(added) {
446        if old
447            .checked_add(new)
448            .filter(|n| *n <= i32::MAX as usize)
449            .is_none()
450        {
451            return invalid("histogram list values exceed Arrow offset limit");
452        }
453    }
454    validate_spans(
455        r.positive.span_offsets,
456        r.positive.span_lengths,
457        r.positive.buckets.len(),
458    )?;
459    validate_spans(
460        r.negative.span_offsets,
461        r.negative.span_lengths,
462        r.negative.buckets.len(),
463    )
464}
465fn lb64() -> ListBuilder<Float64Builder> {
466    ListBuilder::new(Float64Builder::with_capacity(0)).with_field(Arc::new(Field::new(
467        "item",
468        DataType::Float64,
469        false,
470    )))
471}
472fn lb32() -> ListBuilder<Int32Builder> {
473    ListBuilder::new(Int32Builder::with_capacity(0)).with_field(Arc::new(Field::new(
474        "item",
475        DataType::Int32,
476        false,
477    )))
478}
479fn append64(b: &mut ListBuilder<Float64Builder>, v: &[f64]) {
480    for x in v {
481        b.values().append_value(*x)
482    }
483    b.append(true)
484}
485fn append32(b: &mut ListBuilder<Int32Builder>, v: &[i32]) {
486    for x in v {
487        b.values().append_value(*x)
488    }
489    b.append(true)
490}
491
492#[cfg(test)]
493mod tests;