diff --git a/core/expression/src/batch.rs b/core/expression/src/batch.rs new file mode 100644 index 00000000..aec3e58c --- /dev/null +++ b/core/expression/src/batch.rs @@ -0,0 +1,90 @@ +use crate::context::EvaluationContext; +use crate::lane::{Columns, LaneProgram, LaneRunner}; +use crate::{ExpressionKind, IsolateError, Scope, Variable}; +use std::cell::RefCell; + +#[derive(Debug, Clone)] +pub struct BatchExpression { + program: LaneProgram, +} + +thread_local! { + static RUNNER: RefCell = RefCell::new(LaneRunner::new()); +} + +impl BatchExpression { + const SAMPLE: usize = 64; + + pub fn standard(source: &str) -> Result { + Self::compile(source, ExpressionKind::Standard) + } + + pub fn unary(source: &str) -> Result { + Self::compile(source, ExpressionKind::Unary) + } + + pub fn compile(source: &str, kind: ExpressionKind) -> Result { + Ok(Self { + program: LaneProgram::compile(source, kind)?, + }) + } + + pub fn program(&self) -> &LaneProgram { + &self.program + } + + pub fn evaluate(&self, inputs: &[Variable]) -> Vec> { + self.evaluate_with(inputs, &EvaluationContext::default()) + } + + pub fn evaluate_with( + &self, + inputs: &[Variable], + context: &EvaluationContext, + ) -> Vec> { + let scopes: Vec = inputs + .iter() + .map(|input| Scope::new(input.clone())) + .collect(); + self.evaluate_scopes(&scopes, context) + } + + pub fn evaluate_scopes( + &self, + scopes: &[Scope], + context: &EvaluationContext, + ) -> Vec> { + let specialized = match scopes.len() > Self::SAMPLE { + true => self.program.specialize(&scopes[..Self::SAMPLE]).ok(), + false => None, + }; + let program = specialized.as_ref().unwrap_or(&self.program); + RUNNER.with_borrow_mut(|runner| runner.evaluate(program, context, scopes)) + } + + pub fn evaluate_columns( + &self, + columns: &Columns, + context: &EvaluationContext, + ) -> Vec> { + let specialized = self.program.specialize_columns(columns).ok(); + let program = specialized.as_ref().unwrap_or(&self.program); + let mut out: Vec>> = + (0..columns.rows).map(|_| None).collect(); + RUNNER.with_borrow_mut(|runner| { + runner.evaluate_columns(program, context, columns, |row, result| { + out[row] = Some(result) + }) + }); + out.into_iter() + .map(|result| result.unwrap_or(Ok(Variable::Null))) + .collect() + } +} + +pub fn evaluate_expression_batch( + source: &str, + inputs: &[Variable], +) -> Result>, IsolateError> { + Ok(BatchExpression::standard(source)?.evaluate(inputs)) +} diff --git a/core/expression/src/lib.rs b/core/expression/src/lib.rs index 34b1fab4..b1ec8c59 100644 --- a/core/expression/src/lib.rs +++ b/core/expression/src/lib.rs @@ -57,6 +57,7 @@ #![forbid(unsafe_code)] +mod batch; pub mod context; mod isolate; @@ -77,6 +78,7 @@ pub mod validate; pub mod variable; pub mod vm; +pub use batch::{evaluate_expression_batch, BatchExpression}; pub use dates::DateValue; pub use exports::{ compile_expression, compile_unary_expression, evaluate_expression, evaluate_unary_expression, diff --git a/core/expression/tests/batch.rs b/core/expression/tests/batch.rs new file mode 100644 index 00000000..0f022ebb --- /dev/null +++ b/core/expression/tests/batch.rs @@ -0,0 +1,126 @@ +use serde_json::json; +use zen_expression::context::EvaluationContext; +use zen_expression::{evaluate_expression_batch, BatchExpression, Isolate, Variable}; + +fn inputs(rows: usize) -> Vec { + (0..rows) + .map(|i| { + json!({ + "amount": (i * 37) % 1000, + "channel": if i % 2 == 0 { "ecom" } else { "pos" }, + "items": [{ "v": i % 5 }, { "v": null }, { "v": 3 }], + "maybe": if i % 7 == 0 { serde_json::Value::Null } else { json!(i) } + }) + .into() + }) + .collect() +} + +fn per_row(source: &str, inputs: &[Variable]) -> Vec> { + inputs + .iter() + .map(|input| { + Isolate::with_environment(input.clone()) + .run_standard(source) + .map(|v| v.to_value()) + .map_err(|e| e.to_string()) + }) + .collect() +} + +fn outcome( + results: Vec>, +) -> Vec> { + results + .into_iter() + .map(|r| r.map(|v| v.to_value()).map_err(|_| true)) + .collect() +} + +#[test] +fn batch_matches_row_evaluation() { + let sources = [ + "amount / 100", + "amount > 500 and channel == 'ecom'", + "maybe ?? -1", + "sum(items as t, t.v)", + "stddev(items as t, t.v)", + "mode(items, #.v)", + "first(items as t, t.v, t.v != null) + last(items as t, t.v, true)", + "count_distinct(items as t, t.v)", + "percentile(items as t, t.v, 0.5)", + "topK(items as t, t.v, 1)", + "argMax(items as t, t.v, t.v)", + "maybe / (amount - amount)", + "{ big: amount > 900, label: channel + '-' + string(amount) }", + ]; + for rows in [1, 63, 64, 65, 200] { + let inputs = inputs(rows); + for source in sources { + let expected: Vec> = per_row(source, &inputs) + .into_iter() + .map(|r| r.map_err(|_| true)) + .collect(); + let got = outcome(evaluate_expression_batch(source, &inputs).unwrap()); + assert_eq!(got, expected, "{source} over {rows} rows"); + } + } +} + +#[test] +fn unary_batches_return_booleans() { + let expression = BatchExpression::unary("> 10").unwrap(); + let inputs: Vec = [5, 10, 11, 100] + .iter() + .map(|n| json!({ "$": n }).into()) + .collect(); + let got: Vec = expression + .evaluate(&inputs) + .into_iter() + .map(|r| r.unwrap().to_value()) + .collect(); + assert_eq!( + got, + vec![json!(false), json!(false), json!(true), json!(true)] + ); +} + +#[test] +fn syntax_errors_fail_the_compile() { + assert!(BatchExpression::standard("amount +").is_err()); + assert!(evaluate_expression_batch("(", &inputs(3)).is_err()); +} + +#[test] +fn columnar_batch_matches_row_evaluation() { + use zen_expression::lane::{Column, Columns, Values}; + let rows = 150; + let amounts: Vec = (0..rows as i64).map(|i| (i * 37) % 1000).collect(); + let tickets: Vec = (0..rows).map(|i| 10.0 + (i % 9) as f64).collect(); + let validity: Vec = vec![!0b1001u64, !0u64, !0u64]; + let channels: Vec<&str> = (0..rows) + .map(|i| if i % 3 == 0 { "atm" } else { "ecom" }) + .collect(); + let columns = Columns::new(rows) + .column("txn.amount", Column::new(Values::I64(&amounts))) + .column( + "txn.avg_ticket", + Column::with_validity(Values::F64(&tickets), &validity, 0), + ) + .column("txn.channel", Column::new(Values::Strs(&channels))); + for source in [ + "txn.amount / (txn.avg_ticket ?? 1) > 3 and txn.channel != 'atm'", + "txn.amount > 500 ? 'high' : 'low'", + "txn.avg_ticket", + "txn.channel + '-' + string(txn.amount)", + ] { + let expression = BatchExpression::standard(source).unwrap(); + let got = outcome(expression.evaluate_columns(&columns, &EvaluationContext::default())); + let inputs: Vec = (0..rows).map(|row| columns.row(row)).collect(); + let expected: Vec> = per_row(source, &inputs) + .into_iter() + .map(|r| r.map_err(|_| true)) + .collect(); + assert_eq!(got, expected, "{source}"); + } +}