Skip to main content

micromegas_datafusion_extensions/histogram/
expand.rs

1use super::histogram_udaf::HistogramArray;
2use super::otel_codec::{OtelHistogram, bucket_center, decode_column, is_otel_blob_type};
3use async_trait::async_trait;
4use datafusion::arrow::array::{ArrayRef, Float64Array, StructArray, UInt64Array};
5use datafusion::arrow::datatypes::{DataType, Field, Schema, SchemaRef};
6use datafusion::arrow::record_batch::RecordBatch;
7use datafusion::catalog::Session;
8use datafusion::catalog::TableFunctionArgs;
9use datafusion::catalog::TableFunctionImpl;
10use datafusion::catalog::TableProvider;
11use datafusion::datasource::TableType;
12use datafusion::datasource::memory::{DataSourceExec, MemorySourceConfig};
13use datafusion::error::DataFusionError;
14use datafusion::logical_expr::{LogicalPlan, LogicalPlanBuilder};
15use datafusion::physical_plan::ExecutionPlan;
16use datafusion::prelude::Expr;
17use datafusion::scalar::ScalarValue;
18use std::sync::Arc;
19
20/// A DataFusion `TableFunctionImpl` that expands a histogram into rows of (bin_center, count).
21///
22/// The histogram is either the native struct or an `otel_histograms.histogram` blob.
23///
24/// Usage:
25/// ```sql
26/// SELECT bin_center, count
27/// FROM expand_histogram(
28///   (SELECT make_histogram(0.0, 100.0, 100, value)
29///    FROM measures WHERE name = 'cpu_usage')
30/// )
31/// ```
32#[derive(Debug)]
33pub struct ExpandHistogramTableFunction {}
34
35impl ExpandHistogramTableFunction {
36    pub fn new() -> Self {
37        Self {}
38    }
39}
40
41impl Default for ExpandHistogramTableFunction {
42    fn default() -> Self {
43        Self::new()
44    }
45}
46
47/// The source of histogram data - either a literal value or a subquery to evaluate.
48#[derive(Debug, Clone)]
49enum HistogramSource {
50    Literal(ScalarValue),
51    Subquery(Arc<LogicalPlan>),
52}
53
54impl TableFunctionImpl for ExpandHistogramTableFunction {
55    fn call_with_args(
56        &self,
57        args: TableFunctionArgs,
58    ) -> datafusion::error::Result<Arc<dyn TableProvider>> {
59        let args = args.exprs();
60        if args.len() != 1 {
61            return Err(DataFusionError::Plan(
62                "expand_histogram requires exactly one argument (a histogram)".into(),
63            ));
64        }
65
66        // Extract the histogram from the expression
67        let source = match &args[0] {
68            Expr::Literal(scalar, _metadata) => HistogramSource::Literal(scalar.clone()),
69            Expr::ScalarSubquery(subquery) => HistogramSource::Subquery(subquery.subquery.clone()),
70            other => {
71                let plan = LogicalPlanBuilder::empty(true)
72                    .project(vec![other.clone()])?
73                    .build()?;
74                HistogramSource::Subquery(Arc::new(plan))
75            }
76        };
77
78        Ok(Arc::new(ExpandHistogramTableProvider { source }))
79    }
80}
81
82fn output_schema() -> SchemaRef {
83    Arc::new(Schema::new(vec![
84        Field::new("bin_center", DataType::Float64, false),
85        Field::new("count", DataType::UInt64, false),
86    ]))
87}
88
89fn expand_histogram_to_batch(
90    histo_array: &HistogramArray,
91    index: usize,
92) -> Result<RecordBatch, DataFusionError> {
93    if histo_array.is_null_at(index) {
94        return Ok(RecordBatch::new_empty(output_schema()));
95    }
96    let start = histo_array.get_start(index)?;
97    let end = histo_array.get_end(index)?;
98    let bins = histo_array.get_bins(index)?;
99
100    let num_bins = bins.len();
101    if num_bins == 0 {
102        return Ok(RecordBatch::new_empty(output_schema()));
103    }
104
105    // Handle edge case where start == end (all values in a single point)
106    let bin_width = if (end - start).abs() < f64::EPSILON {
107        1.0 // Use unit width when range is zero
108    } else {
109        (end - start) / (num_bins as f64)
110    };
111
112    let mut bin_centers = Vec::with_capacity(num_bins);
113    let mut counts = Vec::with_capacity(num_bins);
114
115    for i in 0..num_bins {
116        let bin_center = start + (i as f64 + 0.5) * bin_width;
117        bin_centers.push(bin_center);
118        counts.push(bins.value(i));
119    }
120
121    let bin_center_array: ArrayRef = Arc::new(Float64Array::from(bin_centers));
122    let count_array: ArrayRef = Arc::new(UInt64Array::from(counts));
123
124    RecordBatch::try_new(output_schema(), vec![bin_center_array, count_array])
125        .map_err(|e| DataFusionError::External(e.into()))
126}
127
128fn otel_histogram_to_batch(histogram: &OtelHistogram) -> Result<RecordBatch, DataFusionError> {
129    let buckets = histogram.bucket_list();
130    let bin_centers: Vec<f64> = buckets.iter().map(bucket_center).collect();
131    let counts: Vec<u64> = buckets.iter().map(|b| b.count).collect();
132    RecordBatch::try_new(
133        output_schema(),
134        vec![
135            Arc::new(Float64Array::from(bin_centers)) as ArrayRef,
136            Arc::new(UInt64Array::from(counts)),
137        ],
138    )
139    .map_err(|e| DataFusionError::External(e.into()))
140}
141
142/// Expands the first row of a Binary/BinaryView column; a NULL or missing row gives no rows.
143fn blob_array_to_batch(array: &ArrayRef) -> Result<RecordBatch, DataFusionError> {
144    if array.is_empty() {
145        return Ok(RecordBatch::new_empty(output_schema()));
146    }
147    match decode_column("expand_histogram", &array.slice(0, 1))?.pop() {
148        Some(Some(histogram)) => otel_histogram_to_batch(&histogram),
149        _ => Ok(RecordBatch::new_empty(output_schema())),
150    }
151}
152
153fn extract_histogram_from_struct(
154    struct_array: &Arc<StructArray>,
155) -> Result<RecordBatch, DataFusionError> {
156    let histo_array = HistogramArray::new(struct_array.clone());
157    if histo_array.is_empty() {
158        return Ok(RecordBatch::new_empty(output_schema()));
159    }
160    expand_histogram_to_batch(&histo_array, 0)
161}
162
163fn scalar_to_batch(scalar: &ScalarValue) -> Result<RecordBatch, DataFusionError> {
164    match scalar {
165        ScalarValue::Struct(struct_array) => extract_histogram_from_struct(struct_array),
166        ScalarValue::Binary(_) | ScalarValue::BinaryView(_) => {
167            blob_array_to_batch(&scalar.to_array()?)
168        }
169        ScalarValue::Dictionary(_, inner) => scalar_to_batch(inner.as_ref()),
170        _ => Err(DataFusionError::Plan(format!(
171            "expand_histogram argument must be a struct (histogram) or an OTel histogram binary, got: {:?}",
172            scalar.data_type()
173        ))),
174    }
175}
176
177/// Table provider for expanding histogram data.
178#[derive(Debug)]
179pub struct ExpandHistogramTableProvider {
180    source: HistogramSource,
181}
182
183impl ExpandHistogramTableProvider {
184    /// Creates a new provider from a histogram scalar value.
185    pub fn from_scalar(scalar: ScalarValue) -> Result<Self, DataFusionError> {
186        if !matches!(
187            scalar,
188            ScalarValue::Struct(_) | ScalarValue::Binary(_) | ScalarValue::BinaryView(_)
189        ) {
190            return Err(DataFusionError::Plan(format!(
191                "expand_histogram argument must be a struct (histogram) or an OTel histogram binary, got: {:?}",
192                scalar.data_type()
193            )));
194        }
195        Ok(Self {
196            source: HistogramSource::Literal(scalar),
197        })
198    }
199}
200
201#[async_trait]
202impl TableProvider for ExpandHistogramTableProvider {
203    fn schema(&self) -> SchemaRef {
204        output_schema()
205    }
206
207    fn table_type(&self) -> TableType {
208        TableType::Temporary
209    }
210
211    async fn scan(
212        &self,
213        state: &dyn Session,
214        projection: Option<&Vec<usize>>,
215        _filters: &[Expr],
216        limit: Option<usize>,
217    ) -> datafusion::error::Result<Arc<dyn ExecutionPlan>> {
218        let mut record_batch = match &self.source {
219            HistogramSource::Literal(scalar) => scalar_to_batch(scalar)?,
220            HistogramSource::Subquery(plan) => {
221                // Execute the subquery to get the histogram scalar
222                let physical_plan = state.create_physical_plan(plan).await?;
223                let task_ctx = state.task_ctx();
224                let batches = datafusion::physical_plan::collect(physical_plan, task_ctx).await?;
225
226                if batches.is_empty() || batches[0].num_rows() == 0 {
227                    return Err(DataFusionError::Execution(
228                        "expand_histogram subquery returned no rows".into(),
229                    ));
230                }
231
232                let batch = &batches[0];
233                if batch.num_columns() != 1 {
234                    return Err(DataFusionError::Execution(format!(
235                        "expand_histogram subquery must return exactly one column, got {}",
236                        batch.num_columns()
237                    )));
238                }
239
240                let column = batch.column(0);
241                if is_otel_blob_type(column.data_type()) {
242                    blob_array_to_batch(column)?
243                } else {
244                    let struct_array = column.as_any().downcast_ref::<StructArray>().ok_or_else(
245                    || {
246                        DataFusionError::Execution(format!(
247                            "expand_histogram subquery must return a struct (histogram) or an OTel histogram binary, got {:?}",
248                            column.data_type()
249                        ))
250                    },
251                )?;
252
253                    let histo_array = HistogramArray::new(Arc::new(struct_array.clone()));
254                    if histo_array.is_empty() {
255                        RecordBatch::new_empty(output_schema())
256                    } else {
257                        expand_histogram_to_batch(&histo_array, 0)?
258                    }
259                }
260            }
261        };
262
263        // Apply limit if specified
264        if let Some(n) = limit
265            && n < record_batch.num_rows()
266        {
267            record_batch = record_batch.slice(0, n);
268        }
269
270        let source = MemorySourceConfig::try_new(
271            &[vec![record_batch]],
272            self.schema(),
273            projection.map(|v| v.to_owned()),
274        )?;
275        Ok(DataSourceExec::from_data_source(source))
276    }
277}