fix(GRL-823): BatchExpression evaluates a standalone expression over many inputs on the lane VM

A thin wrapper over LaneProgram and LaneRunner: rows (specialized on a
sample above 64), scopes or columns, with an evaluation context; plus
evaluate_expression_batch. Results equal row-by-row evaluation.
This commit is contained in:
Ivan Miletic
2026-11-27 11:21:02 +01:00
parent 66fe242fb0
commit 766285e5a7
3 changed files with 218 additions and 0 deletions
+90
View File
@@ -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<LaneRunner> = RefCell::new(LaneRunner::new());
}
impl BatchExpression {
const SAMPLE: usize = 64;
pub fn standard(source: &str) -> Result<Self, IsolateError> {
Self::compile(source, ExpressionKind::Standard)
}
pub fn unary(source: &str) -> Result<Self, IsolateError> {
Self::compile(source, ExpressionKind::Unary)
}
pub fn compile(source: &str, kind: ExpressionKind) -> Result<Self, IsolateError> {
Ok(Self {
program: LaneProgram::compile(source, kind)?,
})
}
pub fn program(&self) -> &LaneProgram {
&self.program
}
pub fn evaluate(&self, inputs: &[Variable]) -> Vec<Result<Variable, IsolateError>> {
self.evaluate_with(inputs, &EvaluationContext::default())
}
pub fn evaluate_with(
&self,
inputs: &[Variable],
context: &EvaluationContext,
) -> Vec<Result<Variable, IsolateError>> {
let scopes: Vec<Scope> = inputs
.iter()
.map(|input| Scope::new(input.clone()))
.collect();
self.evaluate_scopes(&scopes, context)
}
pub fn evaluate_scopes(
&self,
scopes: &[Scope],
context: &EvaluationContext,
) -> Vec<Result<Variable, IsolateError>> {
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<Result<Variable, IsolateError>> {
let specialized = self.program.specialize_columns(columns).ok();
let program = specialized.as_ref().unwrap_or(&self.program);
let mut out: Vec<Option<Result<Variable, IsolateError>>> =
(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<Vec<Result<Variable, IsolateError>>, IsolateError> {
Ok(BatchExpression::standard(source)?.evaluate(inputs))
}
+2
View File
@@ -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,
+126
View File
@@ -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<Variable> {
(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<Result<serde_json::Value, String>> {
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<Result<Variable, zen_expression::IsolateError>>,
) -> Vec<Result<serde_json::Value, bool>> {
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<Result<serde_json::Value, bool>> = 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<Variable> = [5, 10, 11, 100]
.iter()
.map(|n| json!({ "$": n }).into())
.collect();
let got: Vec<serde_json::Value> = 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<i64> = (0..rows as i64).map(|i| (i * 37) % 1000).collect();
let tickets: Vec<f64> = (0..rows).map(|i| 10.0 + (i % 9) as f64).collect();
let validity: Vec<u64> = 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<Variable> = (0..rows).map(|row| columns.row(row)).collect();
let expected: Vec<Result<serde_json::Value, bool>> = per_row(source, &inputs)
.into_iter()
.map(|r| r.map_err(|_| true))
.collect();
assert_eq!(got, expected, "{source}");
}
}