micromegas_datafusion_extensions/histogram/
otel_merge.rs1use super::otel_codec::{ExpBuckets, MIN_EXP_SCALE, OtelBuckets, OtelHistogram, decode_column};
3use datafusion::arrow::array::ArrayRef;
4use datafusion::error::{DataFusionError, Result};
5use datafusion::logical_expr::Accumulator;
6use datafusion::scalar::ScalarValue;
7
8pub const MAX_EXP_BUCKETS: usize = 160;
10
11const NAME: &str = "sum_histograms";
12
13fn exec_err<T>(msg: &str) -> Result<T> {
14 Err(DataFusionError::Execution(format!("{NAME}: {msg}")))
15}
16
17fn merge_opt(a: Option<f64>, b: Option<f64>, f: impl Fn(f64, f64) -> f64) -> Option<f64> {
18 Some(f(a?, b?))
19}
20
21fn add_counts(a: &[u64], b: &[u64]) -> Vec<u64> {
22 a.iter().zip(b).map(|(x, y)| x.saturating_add(*y)).collect()
23}
24
25fn downscale(b: &ExpBuckets, shift: u32) -> ExpBuckets {
26 if shift == 0 || b.counts.is_empty() {
27 return b.clone();
28 }
29 let shift = shift.min(31);
30 let first = i64::from(b.offset) >> shift;
31 let last = (i64::from(b.offset) + b.counts.len() as i64 - 1) >> shift;
32 let mut counts = vec![0u64; (last - first) as usize + 1];
33 for (j, c) in b.counts.iter().enumerate() {
34 let index = (i64::from(b.offset) + j as i64) >> shift;
35 let slot = &mut counts[(index - first) as usize];
36 *slot = slot.saturating_add(*c);
37 }
38 ExpBuckets {
39 offset: first as i32,
40 counts,
41 }
42}
43
44fn add_buckets(a: &ExpBuckets, b: &ExpBuckets) -> ExpBuckets {
46 if a.counts.is_empty() {
47 return b.clone();
48 }
49 if b.counts.is_empty() {
50 return a.clone();
51 }
52 let lo = a.offset.min(b.offset);
53 let hi = (i64::from(a.offset) + a.counts.len() as i64)
54 .max(i64::from(b.offset) + b.counts.len() as i64);
55 let mut counts = vec![0u64; (hi - i64::from(lo)) as usize];
56 for src in [a, b] {
57 for (j, c) in src.counts.iter().enumerate() {
58 let slot = &mut counts[(i64::from(src.offset) - i64::from(lo)) as usize + j];
59 *slot = slot.saturating_add(*c);
60 }
61 }
62 ExpBuckets { offset: lo, counts }
63}
64
65fn shift_between(from: i32, to: i32) -> u32 {
66 (i64::from(from) - i64::from(to)).clamp(0, 31) as u32
67}
68
69fn shifted_range(b: &ExpBuckets, shift: u32) -> Option<(i64, i64)> {
71 if b.counts.is_empty() {
72 return None;
73 }
74 Some((
75 i64::from(b.offset) >> shift,
76 (i64::from(b.offset) + b.counts.len() as i64 - 1) >> shift,
77 ))
78}
79
80fn merged_span(a: (&ExpBuckets, i32), b: (&ExpBuckets, i32), scale: i32) -> usize {
82 let ranges = [a, b]
83 .into_iter()
84 .filter_map(|(r, from)| shifted_range(r, shift_between(from, scale)));
85 let (lo, hi) = ranges.fold((i64::MAX, i64::MIN), |(lo, hi), (l, h)| {
86 (lo.min(l), hi.max(h))
87 });
88 if lo > hi { 0 } else { (hi - lo + 1) as usize }
89}
90
91fn fold_into_zero(b: &mut ExpBuckets, scale: i32, threshold: f64) -> u64 {
94 let step = (-f64::from(scale)).exp2();
95 let mut folded = 0u64;
96 let mut nb_folded_buckets = 0;
97 for (j, c) in b.counts.iter().enumerate() {
98 let upper = ((f64::from(b.offset) + j as f64 + 1.0) * step).exp2();
99 if upper > threshold {
100 break;
101 }
102 folded = folded.saturating_add(*c);
103 nb_folded_buckets += 1;
104 }
105 b.counts.drain(..nb_folded_buckets);
106 b.offset = b.offset.saturating_add(nb_folded_buckets as i32);
107 folded
108}
109
110fn merge_exponential(a: &OtelHistogram, b: &OtelHistogram) -> Result<OtelBuckets> {
111 let (
112 OtelBuckets::Exponential {
113 scale: scale_a,
114 zero_count: zero_a,
115 zero_threshold: threshold_a,
116 positive: pos_a,
117 negative: neg_a,
118 },
119 OtelBuckets::Exponential {
120 scale: scale_b,
121 zero_count: zero_b,
122 zero_threshold: threshold_b,
123 positive: pos_b,
124 negative: neg_b,
125 },
126 ) = (&a.buckets, &b.buckets)
127 else {
128 unreachable!("caller checks both sides are exponential");
129 };
130 let widest_input = [pos_a, neg_a, pos_b, neg_b]
131 .iter()
132 .map(|r| r.counts.len())
133 .max()
134 .unwrap_or(0);
135 let cap = MAX_EXP_BUCKETS.max(widest_input);
136 let mut scale = *scale_a.min(scale_b);
138 while merged_span((pos_a, *scale_a), (pos_b, *scale_b), scale) > cap
139 || merged_span((neg_a, *scale_a), (neg_b, *scale_b), scale) > cap
140 {
141 if scale <= MIN_EXP_SCALE {
144 return exec_err("merged exponential buckets exceed the bucket limit");
145 }
146 scale -= 1;
147 }
148 let shift = |from: i32| shift_between(from, scale);
149 let mut positive = add_buckets(
150 &downscale(pos_a, shift(*scale_a)),
151 &downscale(pos_b, shift(*scale_b)),
152 );
153 let mut negative = add_buckets(
154 &downscale(neg_a, shift(*scale_a)),
155 &downscale(neg_b, shift(*scale_b)),
156 );
157 let threshold = threshold_a.max(*threshold_b);
158 let mut zero_count = zero_a.saturating_add(*zero_b);
159 zero_count = zero_count.saturating_add(fold_into_zero(&mut positive, scale, threshold));
160 zero_count = zero_count.saturating_add(fold_into_zero(&mut negative, scale, threshold));
161 Ok(OtelBuckets::Exponential {
162 scale,
163 zero_count,
164 zero_threshold: threshold,
165 positive,
166 negative,
167 })
168}
169
170pub fn merge(a: &OtelHistogram, b: &OtelHistogram) -> Result<OtelHistogram> {
172 let buckets = match (&a.buckets, &b.buckets) {
173 (
174 OtelBuckets::Explicit {
175 bounds: bounds_a,
176 counts: counts_a,
177 },
178 OtelBuckets::Explicit {
179 bounds: bounds_b,
180 counts: counts_b,
181 },
182 ) => {
183 let same_bounds = bounds_a.len() == bounds_b.len()
184 && bounds_a
185 .iter()
186 .zip(bounds_b)
187 .all(|(x, y)| x.to_bits() == y.to_bits());
188 if !same_bounds {
189 return exec_err("cannot merge explicit histograms with different bucket bounds");
190 }
191 OtelBuckets::Explicit {
192 bounds: bounds_a.clone(),
193 counts: add_counts(counts_a, counts_b),
194 }
195 }
196 (OtelBuckets::Exponential { .. }, OtelBuckets::Exponential { .. }) => {
197 merge_exponential(a, b)?
198 }
199 _ => return exec_err("cannot merge explicit and exponential histograms"),
200 };
201 Ok(OtelHistogram {
202 count: a.count.saturating_add(b.count),
203 sum: merge_opt(a.sum, b.sum, |x, y| x + y),
204 min: merge_opt(a.min, b.min, f64::min),
205 max: merge_opt(a.max, b.max, f64::max),
206 buckets,
207 })
208}
209
210#[derive(Debug, Default)]
212pub struct OtelHistogramAccumulator {
213 merged: Option<OtelHistogram>,
214}
215
216impl OtelHistogramAccumulator {
217 pub fn new() -> Self {
218 Self::default()
219 }
220
221 fn fold(&mut self, array: &ArrayRef) -> Result<()> {
222 for histogram in decode_column(NAME, array)?.into_iter().flatten() {
223 self.merged = Some(match self.merged.take() {
224 None => histogram,
225 Some(acc) => merge(&acc, &histogram)?,
226 });
227 }
228 Ok(())
229 }
230
231 fn to_scalar(&self) -> ScalarValue {
232 ScalarValue::Binary(self.merged.as_ref().map(OtelHistogram::encode))
233 }
234}
235
236impl Accumulator for OtelHistogramAccumulator {
237 fn update_batch(&mut self, values: &[ArrayRef]) -> Result<()> {
238 let [array] = values else {
239 return exec_err("expected exactly one argument");
240 };
241 self.fold(array)
242 }
243
244 fn evaluate(&mut self) -> Result<ScalarValue> {
245 Ok(self.to_scalar())
246 }
247
248 fn size(&self) -> usize {
249 size_of_val(self)
250 + self.merged.as_ref().map_or(0, |h| match &h.buckets {
251 OtelBuckets::Explicit { bounds, counts } => (bounds.len() + counts.len()) * 8,
252 OtelBuckets::Exponential {
253 positive, negative, ..
254 } => (positive.counts.len() + negative.counts.len()) * 8,
255 })
256 }
257
258 fn state(&mut self) -> Result<Vec<ScalarValue>> {
259 Ok(vec![self.to_scalar()])
260 }
261
262 fn merge_batch(&mut self, states: &[ArrayRef]) -> Result<()> {
263 let [array] = states else {
264 return exec_err("expected exactly one state column");
265 };
266 self.fold(array)
267 }
268}