Skip to main content

llkv_compute/
fast_numeric.rs

1//! Stack-based arithmetic evaluator that uses native Arrow kernels.
2
3use std::{hash::Hash, sync::Arc};
4
5use arrow::array::{ArrayRef, Float64Array, Int64Array, PrimitiveArray, new_null_array};
6use arrow::compute::kernels::numeric;
7use arrow::datatypes::{
8    DataType, Float32Type, Float64Type, Int8Type, Int16Type, Int32Type, Int64Type, UInt8Type,
9    UInt16Type, UInt32Type, UInt64Type,
10};
11use llkv_expr::{BinaryOp, ScalarExpr, literal::Literal};
12use llkv_result::{Error, Result as LlkvResult};
13use rustc_hash::FxHashMap;
14
15use crate::eval::{NumericArrayMap, ScalarEvaluator};
16use crate::kernels::common_type_for_op;
17
18/// Pre-compiled arithmetic path that evaluates directly using Arrow kernels.
19pub struct NumericFastPath<F> {
20    tokens: Vec<Token>,
21    column_order: Vec<F>,
22    target_type: DataType,
23}
24
25#[derive(Clone)]
26enum Token {
27    Column { slot: usize },
28    Literal(NumericLiteral),
29    Binary(BinaryOp),
30}
31
32#[derive(Clone)]
33enum NumericLiteral {
34    Int(i128),
35    Float(f64),
36    Null,
37}
38
39impl<F: Hash + Eq + Copy> NumericFastPath<F> {
40    pub fn compile(
41        expr: &ScalarExpr<F>,
42        arrays: &NumericArrayMap<F>,
43        target_type: &DataType,
44    ) -> Option<Self> {
45        if !ScalarEvaluator::is_supported_numeric(target_type) {
46            return None;
47        }
48
49        let mut builder = PlanBuilder {
50            tokens: Vec::new(),
51            column_slots: FxHashMap::default(),
52            column_order: Vec::new(),
53            arrays,
54        };
55        let output_type = builder.visit(expr)?;
56
57        // Only proceed if the inferred output type aligns with the preferred target type
58        if &output_type != target_type {
59            return None;
60        }
61
62        Some(Self {
63            tokens: builder.tokens,
64            column_order: builder.column_order,
65            target_type: target_type.clone(),
66        })
67    }
68
69    pub fn execute(&self, len: usize, arrays: &NumericArrayMap<F>) -> LlkvResult<ArrayRef> {
70        let mut column_refs = Vec::with_capacity(self.column_order.len());
71
72        for field in &self.column_order {
73            let array = arrays
74                .get(field)
75                .ok_or_else(|| Error::Internal("missing numeric array for fast path".into()))?;
76            if !ScalarEvaluator::is_supported_numeric(array.data_type()) {
77                return Err(Error::Internal(
78                    "unsupported array type for numeric fast path".into(),
79                ));
80            }
81            let casted = if array.data_type() == &self.target_type {
82                array.clone()
83            } else {
84                arrow::compute::cast(array, &self.target_type)
85                    .map_err(|e| Error::Internal(format!("fast path cast failed: {}", e)))?
86            };
87            column_refs.push(casted);
88        }
89
90        let mut stack: Vec<ArrayRef> = Vec::with_capacity(8);
91
92        for token in &self.tokens {
93            match token {
94                Token::Column { slot } => {
95                    stack.push(column_refs[*slot].clone());
96                }
97                Token::Literal(lit) => {
98                    let array = make_literal_array(lit, len, &self.target_type)?;
99                    stack.push(array);
100                }
101                Token::Binary(op) => {
102                    let rhs = stack
103                        .pop()
104                        .ok_or_else(|| Error::Internal("fast path stack underflow".into()))?;
105                    let lhs = stack
106                        .pop()
107                        .ok_or_else(|| Error::Internal("fast path stack underflow".into()))?;
108
109                    let result = compute_binary_no_coerce(&lhs, &rhs, *op, &self.target_type)?;
110                    stack.push(result);
111                }
112            }
113        }
114
115        let result = stack
116            .pop()
117            .ok_or_else(|| Error::Internal("fast path evaluation missing result".into()))?;
118
119        Ok(result)
120    }
121}
122
123fn make_literal_array(
124    lit: &NumericLiteral,
125    len: usize,
126    target_type: &DataType,
127) -> LlkvResult<ArrayRef> {
128    match target_type {
129        DataType::Int64 => match lit {
130            NumericLiteral::Int(v) => {
131                if *v < i64::MIN as i128 || *v > i64::MAX as i128 {
132                    return Err(Error::Internal("fast path literal out of i64 range".into()));
133                }
134                Ok(Arc::new(Int64Array::from_value(*v as i64, len)))
135            }
136            NumericLiteral::Float(v) => Ok(Arc::new(Int64Array::from_value(*v as i64, len))),
137            NumericLiteral::Null => Ok(new_null_array(target_type, len)),
138        },
139        DataType::UInt64 => match lit {
140            NumericLiteral::Int(v) => {
141                if *v < 0 || *v > u64::MAX as i128 {
142                    return Err(Error::Internal("fast path literal out of u64 range".into()));
143                }
144                Ok(Arc::new(arrow::array::UInt64Array::from_value(
145                    *v as u64, len,
146                )))
147            }
148            NumericLiteral::Float(v) => Ok(Arc::new(arrow::array::UInt64Array::from_value(
149                *v as u64, len,
150            ))),
151            NumericLiteral::Null => Ok(new_null_array(target_type, len)),
152        },
153        DataType::Float64 => match lit {
154            NumericLiteral::Int(v) => Ok(Arc::new(Float64Array::from_value(*v as f64, len))),
155            NumericLiteral::Float(v) => Ok(Arc::new(Float64Array::from_value(*v, len))),
156            NumericLiteral::Null => Ok(new_null_array(target_type, len)),
157        },
158        DataType::Float32 => match lit {
159            NumericLiteral::Int(v) => Ok(Arc::new(arrow::array::Float32Array::from_value(
160                *v as f32, len,
161            ))),
162            NumericLiteral::Float(v) => Ok(Arc::new(arrow::array::Float32Array::from_value(
163                *v as f32, len,
164            ))),
165            NumericLiteral::Null => Ok(new_null_array(target_type, len)),
166        },
167        DataType::Int32 => match lit {
168            NumericLiteral::Int(v) => Ok(Arc::new(arrow::array::Int32Array::from_value(
169                *v as i32, len,
170            ))),
171            NumericLiteral::Float(v) => Ok(Arc::new(arrow::array::Int32Array::from_value(
172                *v as i32, len,
173            ))),
174            NumericLiteral::Null => Ok(new_null_array(target_type, len)),
175        },
176        DataType::UInt32 => match lit {
177            NumericLiteral::Int(v) => {
178                if *v < 0 || *v > u32::MAX as i128 {
179                    return Err(Error::Internal("fast path literal out of u32 range".into()));
180                }
181                Ok(Arc::new(arrow::array::UInt32Array::from_value(
182                    *v as u32, len,
183                )))
184            }
185            NumericLiteral::Float(v) => Ok(Arc::new(arrow::array::UInt32Array::from_value(
186                *v as u32, len,
187            ))),
188            NumericLiteral::Null => Ok(new_null_array(target_type, len)),
189        },
190        DataType::Int16 => match lit {
191            NumericLiteral::Int(v) => Ok(Arc::new(arrow::array::Int16Array::from_value(
192                *v as i16, len,
193            ))),
194            NumericLiteral::Float(v) => Ok(Arc::new(arrow::array::Int16Array::from_value(
195                *v as i16, len,
196            ))),
197            NumericLiteral::Null => Ok(new_null_array(target_type, len)),
198        },
199        DataType::UInt16 => match lit {
200            NumericLiteral::Int(v) => {
201                if *v < 0 || *v > u16::MAX as i128 {
202                    return Err(Error::Internal("fast path literal out of u16 range".into()));
203                }
204                Ok(Arc::new(arrow::array::UInt16Array::from_value(
205                    *v as u16, len,
206                )))
207            }
208            NumericLiteral::Float(v) => Ok(Arc::new(arrow::array::UInt16Array::from_value(
209                *v as u16, len,
210            ))),
211            NumericLiteral::Null => Ok(new_null_array(target_type, len)),
212        },
213        DataType::Int8 => match lit {
214            NumericLiteral::Int(v) => {
215                Ok(Arc::new(arrow::array::Int8Array::from_value(*v as i8, len)))
216            }
217            NumericLiteral::Float(v) => {
218                Ok(Arc::new(arrow::array::Int8Array::from_value(*v as i8, len)))
219            }
220            NumericLiteral::Null => Ok(new_null_array(target_type, len)),
221        },
222        DataType::UInt8 => match lit {
223            NumericLiteral::Int(v) => {
224                if *v < 0 || *v > u8::MAX as i128 {
225                    return Err(Error::Internal("fast path literal out of u8 range".into()));
226                }
227                Ok(Arc::new(arrow::array::UInt8Array::from_value(
228                    *v as u8, len,
229                )))
230            }
231            NumericLiteral::Float(v) => Ok(Arc::new(arrow::array::UInt8Array::from_value(
232                *v as u8, len,
233            ))),
234            NumericLiteral::Null => Ok(new_null_array(target_type, len)),
235        },
236        _ => Err(Error::Internal(
237            "unsupported literal type for numeric fast path".into(),
238        )),
239    }
240}
241
242struct PlanBuilder<'a, F> {
243    tokens: Vec<Token>,
244    column_slots: FxHashMap<F, usize>,
245    column_order: Vec<F>,
246    arrays: &'a NumericArrayMap<F>,
247}
248
249impl<'a, F: Copy + Eq + Hash> PlanBuilder<'a, F> {
250    fn visit(&mut self, expr: &ScalarExpr<F>) -> Option<DataType> {
251        match expr {
252            ScalarExpr::Column(fid) => {
253                let array = self.arrays.get(fid)?;
254                if !ScalarEvaluator::is_supported_numeric(array.data_type()) {
255                    return None;
256                }
257                let slot = *self.column_slots.entry(*fid).or_insert_with(|| {
258                    self.column_order.push(*fid);
259                    self.column_order.len() - 1
260                });
261                self.tokens.push(Token::Column { slot });
262                Some(array.data_type().clone())
263            }
264            ScalarExpr::Literal(lit) => {
265                let literal = NumericLiteral::from_literal(lit)?;
266                self.tokens.push(Token::Literal(literal.clone()));
267                match literal {
268                    NumericLiteral::Int(_) | NumericLiteral::Null => Some(DataType::Int64),
269                    NumericLiteral::Float(_) => Some(DataType::Float64),
270                }
271            }
272            ScalarExpr::Binary { left, op, right } => {
273                if *op == BinaryOp::Divide {
274                    return None; // Use standard path to preserve integer-division semantics.
275                }
276                if !matches!(
277                    op,
278                    BinaryOp::Add
279                        | BinaryOp::Subtract
280                        | BinaryOp::Multiply
281                        | BinaryOp::Divide
282                        | BinaryOp::Modulo
283                ) {
284                    return None;
285                }
286                let left_type = self.visit(left)?;
287                let right_type = self.visit(right)?;
288                let result_type = common_type_for_op(&left_type, &right_type, *op);
289                if !ScalarEvaluator::is_supported_numeric(&result_type) {
290                    return None;
291                }
292                self.tokens.push(Token::Binary(*op));
293                Some(result_type)
294            }
295            _ => None,
296        }
297    }
298}
299
300impl NumericLiteral {
301    fn from_literal(lit: &Literal) -> Option<Self> {
302        match lit {
303            Literal::Int128(v) => Some(NumericLiteral::Int(*v)),
304            Literal::Float64(v) => Some(NumericLiteral::Float(*v)),
305            Literal::Decimal128(d) => Some(NumericLiteral::Int(d.raw_value())),
306            Literal::Null => Some(NumericLiteral::Null),
307            _ => None,
308        }
309    }
310}
311
312fn compute_binary_no_coerce(
313    lhs: &ArrayRef,
314    rhs: &ArrayRef,
315    op: BinaryOp,
316    dtype: &DataType,
317) -> LlkvResult<ArrayRef> {
318    macro_rules! binary_prim {
319        ($arrow_ty:ty) => {{
320            let l = lhs
321                .as_any()
322                .downcast_ref::<PrimitiveArray<$arrow_ty>>()
323                .ok_or_else(|| Error::Internal("fast path lhs type mismatch".into()))?;
324            let r = rhs
325                .as_any()
326                .downcast_ref::<PrimitiveArray<$arrow_ty>>()
327                .ok_or_else(|| Error::Internal("fast path rhs type mismatch".into()))?;
328            let arr = match op {
329                BinaryOp::Add => numeric::add(l, r),
330                BinaryOp::Subtract => numeric::sub(l, r),
331                BinaryOp::Multiply => numeric::mul(l, r),
332                BinaryOp::Divide => numeric::div(l, r),
333                BinaryOp::Modulo => numeric::rem(l, r),
334                _ => return Err(Error::Internal("unsupported op for fast path".into())),
335            }
336            .map_err(|e| Error::Internal(e.to_string()))?;
337            Ok(Arc::new(arr) as ArrayRef)
338        }};
339    }
340
341    match dtype {
342        DataType::Float64 => binary_prim!(Float64Type),
343        DataType::Float32 => binary_prim!(Float32Type),
344        DataType::Int64 => binary_prim!(Int64Type),
345        DataType::Int32 => binary_prim!(Int32Type),
346        DataType::Int16 => binary_prim!(Int16Type),
347        DataType::Int8 => binary_prim!(Int8Type),
348        DataType::UInt64 => binary_prim!(UInt64Type),
349        DataType::UInt32 => binary_prim!(UInt32Type),
350        DataType::UInt16 => binary_prim!(UInt16Type),
351        DataType::UInt8 => binary_prim!(UInt8Type),
352        _ => Err(Error::Internal(
353            "unsupported data type for fast path execution".into(),
354        )),
355    }
356}