Skip to main content

llkv_compute/
analysis.rs

1use crate::eval::ScalarExprTypeExt;
2use arrow::datatypes::DataType;
3use llkv_expr::literal::Literal;
4use llkv_expr::{Expr, ScalarExpr};
5use llkv_result::{Error, Result as LlkvResult};
6use llkv_types::{FieldId, LogicalFieldId, TableId};
7use rustc_hash::FxHashMap;
8
9pub fn computed_expr_requires_numeric(expr: &ScalarExpr<FieldId>) -> bool {
10    match expr {
11        ScalarExpr::Literal(_) => false,
12        ScalarExpr::Column(_) => true,
13        ScalarExpr::Binary { .. } => true,
14        ScalarExpr::Compare { .. } => true,
15        ScalarExpr::Aggregate(_) => false, // Aggregates are computed separately
16        ScalarExpr::GetField { .. } => false, // GetField requires raw arrays, not numeric conversion
17        ScalarExpr::Cast { expr, .. } => computed_expr_requires_numeric(expr),
18        ScalarExpr::Not(expr) => computed_expr_requires_numeric(expr),
19        ScalarExpr::IsNull { expr, .. } => computed_expr_requires_numeric(expr),
20        ScalarExpr::Case { .. } => true,
21        ScalarExpr::Coalesce(items) => items.iter().any(computed_expr_requires_numeric),
22        ScalarExpr::Random => true,
23        ScalarExpr::ScalarSubquery(_) => false,
24    }
25}
26
27pub fn computed_expr_prefers_float(
28    expr: &ScalarExpr<FieldId>,
29    table_id: TableId,
30    lfid_dtypes: &FxHashMap<LogicalFieldId, DataType>,
31) -> LlkvResult<bool> {
32    match expr {
33        ScalarExpr::Literal(lit) => literal_prefers_float(lit),
34        ScalarExpr::Column(fid) => {
35            let lfid = LogicalFieldId::for_user(table_id, *fid);
36            let dtype = lfid_dtypes
37                .get(&lfid)
38                .ok_or_else(|| Error::Internal("missing dtype for computed column".into()))?;
39            Ok(matches!(
40                dtype,
41                DataType::Float16 | DataType::Float32 | DataType::Float64
42            ))
43        }
44        ScalarExpr::Binary { left, right, .. } => {
45            Ok(
46                computed_expr_prefers_float(left.as_ref(), table_id, lfid_dtypes)?
47                    || computed_expr_prefers_float(right.as_ref(), table_id, lfid_dtypes)?,
48            )
49        }
50        ScalarExpr::Compare { .. } => Ok(false),
51        ScalarExpr::Aggregate(_) => Ok(false),
52        ScalarExpr::GetField { base, field_name } => {
53            let dtype = get_field_dtype(base.as_ref(), field_name, table_id, lfid_dtypes)?;
54            Ok(matches!(
55                dtype,
56                DataType::Float16 | DataType::Float32 | DataType::Float64
57            ))
58        }
59        ScalarExpr::Cast { expr, data_type } => {
60            if matches!(
61                data_type,
62                DataType::Float16 | DataType::Float32 | DataType::Float64
63            ) {
64                Ok(true)
65            } else {
66                computed_expr_prefers_float(expr.as_ref(), table_id, lfid_dtypes)
67            }
68        }
69        ScalarExpr::Not(expr) => computed_expr_prefers_float(expr.as_ref(), table_id, lfid_dtypes),
70
71        ScalarExpr::IsNull { expr, .. } => {
72            let _ = computed_expr_prefers_float(expr.as_ref(), table_id, lfid_dtypes)?;
73            Ok(false)
74        }
75        ScalarExpr::Case {
76            operand,
77            branches,
78            else_expr,
79        } => {
80            if let Some(inner) = operand.as_deref()
81                && computed_expr_prefers_float(inner, table_id, lfid_dtypes)?
82            {
83                return Ok(true);
84            }
85            for (when_expr, then_expr) in branches {
86                if computed_expr_prefers_float(when_expr, table_id, lfid_dtypes)?
87                    || computed_expr_prefers_float(then_expr, table_id, lfid_dtypes)?
88                {
89                    return Ok(true);
90                }
91            }
92            if let Some(inner) = else_expr.as_deref()
93                && computed_expr_prefers_float(inner, table_id, lfid_dtypes)?
94            {
95                return Ok(true);
96            }
97            Ok(false)
98        }
99        ScalarExpr::Coalesce(items) => {
100            for item in items {
101                if computed_expr_prefers_float(item, table_id, lfid_dtypes)? {
102                    return Ok(true);
103                }
104            }
105            Ok(false)
106        }
107        ScalarExpr::Random => Ok(true),
108        ScalarExpr::ScalarSubquery(_) => Ok(false),
109    }
110}
111
112pub fn scalar_expr_contains_coalesce(expr: &ScalarExpr<FieldId>) -> bool {
113    match expr {
114        ScalarExpr::Coalesce(_) => true,
115        ScalarExpr::Binary { left, right, .. } | ScalarExpr::Compare { left, right, .. } => {
116            scalar_expr_contains_coalesce(left) || scalar_expr_contains_coalesce(right)
117        }
118        ScalarExpr::Not(expr) => scalar_expr_contains_coalesce(expr),
119        ScalarExpr::IsNull { expr, .. } => scalar_expr_contains_coalesce(expr),
120        ScalarExpr::Cast { expr, .. } => scalar_expr_contains_coalesce(expr),
121        ScalarExpr::Case {
122            operand,
123            branches,
124            else_expr,
125        } => {
126            operand
127                .as_deref()
128                .map(scalar_expr_contains_coalesce)
129                .unwrap_or(false)
130                || branches.iter().any(|(when_expr, then_expr)| {
131                    scalar_expr_contains_coalesce(when_expr)
132                        || scalar_expr_contains_coalesce(then_expr)
133                })
134                || else_expr
135                    .as_deref()
136                    .map(scalar_expr_contains_coalesce)
137                    .unwrap_or(false)
138        }
139        ScalarExpr::GetField { base, .. } => scalar_expr_contains_coalesce(base),
140        ScalarExpr::Aggregate(_)
141        | ScalarExpr::Column(_)
142        | ScalarExpr::Literal(_)
143        | ScalarExpr::Random
144        | ScalarExpr::ScalarSubquery(_) => false,
145    }
146}
147
148pub fn literal_prefers_float(literal: &Literal) -> LlkvResult<bool> {
149    match literal {
150        Literal::Float64(_) => Ok(true),
151        Literal::Decimal128(_) => Ok(true),
152        Literal::Struct(fields) => {
153            for (_, nested) in fields {
154                if literal_prefers_float(nested.as_ref())? {
155                    return Ok(true);
156                }
157            }
158            Ok(false)
159        }
160        Literal::Int128(_) | Literal::Boolean(_) | Literal::String(_) | Literal::Null => Ok(false),
161        Literal::Date32(_) => Ok(false),
162        Literal::Interval(_) => Ok(false),
163    }
164}
165
166pub fn get_field_dtype(
167    expr: &ScalarExpr<FieldId>,
168    field_name: &str,
169    table_id: TableId,
170    lfid_dtypes: &FxHashMap<LogicalFieldId, DataType>,
171) -> LlkvResult<DataType> {
172    let base_dtype = match expr {
173        ScalarExpr::Column(fid) => {
174            let lfid = LogicalFieldId::for_user(table_id, *fid);
175            lfid_dtypes
176                .get(&lfid)
177                .cloned()
178                .ok_or_else(|| Error::Internal("missing dtype for computed column".into()))?
179        }
180        ScalarExpr::GetField {
181            base: inner_base,
182            field_name: inner_field,
183        } => get_field_dtype(inner_base.as_ref(), inner_field, table_id, lfid_dtypes)?,
184        _ => {
185            return Err(Error::InvalidArgumentError(
186                "GetField base must be a column or another GetField".into(),
187            ));
188        }
189    };
190
191    if let DataType::Struct(fields) = base_dtype {
192        fields
193            .iter()
194            .find(|f| f.name() == field_name)
195            .map(|f| f.data_type().clone())
196            .ok_or_else(|| {
197                Error::InvalidArgumentError(format!("Field '{}' not found in struct", field_name))
198            })
199    } else {
200        Err(Error::InvalidArgumentError(
201            "GetField can only be applied to struct types".into(),
202        ))
203    }
204}
205
206/// Infer the result type for a scalar expression given table-level field dtypes.
207pub fn computed_expr_result_type(
208    expr: &ScalarExpr<FieldId>,
209    table_id: TableId,
210    lfid_dtypes: &FxHashMap<LogicalFieldId, DataType>,
211) -> LlkvResult<Option<DataType>> {
212    let mut resolver = |fid: FieldId| {
213        let lfid = LogicalFieldId::for_user(table_id, fid);
214        lfid_dtypes.get(&lfid).cloned()
215    };
216    Ok(expr.infer_result_type(&mut resolver))
217}
218
219#[derive(Default, Clone, Copy)]
220struct FieldPredicateStats {
221    total: usize,
222    contains: usize,
223}
224
225/// Lightweight cache used to decide when to fuse predicates for a field.
226#[derive(Default)]
227pub struct PredicateFusionCache {
228    per_field: FxHashMap<FieldId, FieldPredicateStats>,
229}
230
231impl PredicateFusionCache {
232    pub fn from_expr(expr: &Expr<'_, FieldId>) -> Self {
233        let mut cache = Self::default();
234        cache.record_expr(expr);
235        cache
236    }
237
238    fn record_expr(&mut self, expr: &Expr<'_, FieldId>) {
239        let mut stack = vec![expr];
240
241        while let Some(node) = stack.pop() {
242            match node {
243                Expr::Pred(filter) => {
244                    let entry = self.per_field.entry(filter.field_id).or_default();
245                    entry.total += 1;
246                    if matches!(filter.op, llkv_expr::Operator::Contains { .. }) {
247                        entry.contains += 1;
248                    }
249                }
250                Expr::And(children) | Expr::Or(children) => {
251                    for child in children {
252                        stack.push(child);
253                    }
254                }
255                Expr::Not(inner) => stack.push(inner),
256                Expr::Compare { .. }
257                | Expr::InList { .. }
258                | Expr::IsNull { .. }
259                | Expr::Literal(_)
260                | Expr::Exists(_) => {}
261            }
262        }
263    }
264
265    pub fn should_fuse(&self, field_id: FieldId, dtype: &DataType) -> bool {
266        let Some(stats) = self.per_field.get(&field_id) else {
267            return false;
268        };
269
270        match dtype {
271            DataType::Utf8 | DataType::LargeUtf8 => stats.contains >= 1 && stats.total >= 2,
272            _ => stats.total >= 2,
273        }
274    }
275}