From 2b00b419800ef47544b412cb879ffbbc806e17d8 Mon Sep 17 00:00:00 2001 From: Stefan Miljakovic Date: Fri, 9 Oct 2026 10:20:59 +0200 Subject: [PATCH] feat: lane session mirroring the isolate API (exact compile errors, shared program sets, fallback detector) --- core/engine/tests/lane_census.rs | 420 ++++++++++++ core/expression/src/lane/exec/closure.rs | 6 +- core/expression/src/lane/exec/export.rs | 8 +- core/expression/src/lane/exec/frame.rs | 21 + core/expression/src/lane/exec/mod.rs | 2 +- core/expression/src/lane/mod.rs | 21 +- core/expression/src/lane/session.rs | 167 +++++ core/expression/tests/conformance/mod.rs | 26 +- core/expression/tests/lane.rs | 76 ++- core/expression/tests/session.rs | 818 +++++++++++++++++++++++ 10 files changed, 1532 insertions(+), 33 deletions(-) create mode 100644 core/engine/tests/lane_census.rs create mode 100644 core/expression/src/lane/session.rs create mode 100644 core/expression/tests/session.rs diff --git a/core/engine/tests/lane_census.rs b/core/engine/tests/lane_census.rs new file mode 100644 index 00000000..298d47e8 --- /dev/null +++ b/core/engine/tests/lane_census.rs @@ -0,0 +1,420 @@ +#[path = "support/policy_gen.rs"] +mod policy_gen; +mod conformance; +mod support; +#[allow(dead_code)] +#[path = "support/fixture.rs"] +mod fixture; +#[allow(dead_code)] +#[path = "support/policies.rs"] +mod policies; + +use conformance::run::PolicyRun; +use conformance::{Dialect, Spec}; +use fixture::Fixture; +use policies::{Anchor, Generated, PolicyCase}; +use serde_json::Value; +use std::collections::{BTreeMap, BTreeSet}; +use std::sync::Arc; +use zen_engine::model::{DecisionContent, DecisionNodeKind, GraphContent}; +use zen_engine::policy::{BlockDoc, PolicyDocument, PolicyWorkspace}; +use zen_expression::lane::{Fallbacks, LaneProgram, Programs, Session}; +use zen_expression::{ExpressionKind, Isolate, IsolateError, Variable}; + +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] +enum Site { + Standard(String), + Cell { field: String, cell: String }, +} + +struct Document { + label: String, + sites: Vec, + inputs: Vec, +} + +impl Document { + const INPUTS: usize = 24; + + fn new(label: String, inputs: Vec) -> Self { + Self { + label, + sites: Vec::new(), + inputs: inputs.into_iter().take(Self::INPUTS).collect(), + } + } + + fn standard(&mut self, source: &str) { + if !source.is_empty() { + self.sites.push(Site::Standard(source.to_string())); + } + } + + fn cell(&mut self, field: Option<&str>, cell: &str) { + if cell.is_empty() { + return; + } + match field { + Some(field) => self.sites.push(Site::Cell { + field: field.to_string(), + cell: cell.to_string(), + }), + None => self.standard(cell), + } + } + + fn graph(&mut self, graph: &GraphContent) { + for node in &graph.nodes { + match &node.kind { + DecisionNodeKind::ExpressionNode { content } => { + self.transform(content.transform_attributes.input_field.as_deref()); + for expression in content.expressions.iter() { + if !expression.key.is_empty() { + self.standard(&expression.value); + } + } + } + DecisionNodeKind::DecisionTableNode { content } => { + self.transform(content.transform_attributes.input_field.as_deref()); + for input in content.inputs.iter() { + let field = input.field.as_deref().filter(|f| !f.trim().is_empty()); + if let Some(field) = field { + self.standard(field); + } + for rule in content.rules.iter() { + if let Some(cell) = rule.get(&input.id) { + self.cell(field, cell); + } + } + } + for output in content.outputs.iter() { + for rule in content.rules.iter() { + if let (false, Some(cell)) = (output.field.is_empty(), rule.get(&output.id)) { + self.standard(cell); + } + } + } + } + DecisionNodeKind::SwitchNode { content } => { + for statement in content.statements.iter() { + self.standard(&statement.condition); + } + } + DecisionNodeKind::DecisionNode { content } => { + self.transform(content.transform_attributes.input_field.as_deref()); + } + _ => {} + } + } + } + + fn transform(&mut self, field: Option<&str>) { + if let Some(field) = field.filter(|f| !f.trim().is_empty()) { + self.standard(field); + } + } + + fn policy(&mut self, policy: &PolicyDocument) { + for block in &policy.blocks { + match block { + BlockDoc::Expression { data, .. } => self.standard(data.value.trim()), + BlockDoc::Assertion { data, .. } => { + for condition in &data.conditions { + self.standard(condition.expression.trim()); + } + } + BlockDoc::Match { data, .. } => { + for arm in &data.arms { + self.standard(arm.condition.trim()); + self.standard(arm.value.trim()); + } + } + BlockDoc::DecisionTable { data, .. } => { + for input in &data.inputs { + let field = input.field.as_deref().map(str::trim).filter(|f| !f.is_empty()); + if let Some(field) = field { + self.standard(field); + } + for rule in &data.rules { + if let Some(cell) = rule.get(&input.id) { + self.cell(field, cell); + } + } + } + for output in &data.outputs { + for rule in &data.rules { + if let Some(cell) = rule.get(&output.id) { + self.standard(cell); + } + } + } + } + _ => {} + } + } + } + + fn value(&mut self, value: &Value) { + match value.get("nodes") { + Some(_) => { + if let Ok(DecisionContent::Graph(graph)) = serde_json::from_value::(value.clone()) { + self.graph(&graph); + } + } + None => { + if let Ok(policy) = serde_json::from_value::(value.clone()) { + self.policy(&policy); + } + } + } + } + + fn workspace(&mut self, workspace: &PolicyWorkspace) { + for path in workspace.paths() { + match workspace.is_graph(&path) { + true => { + if let Some(graph) = workspace.get_document(&path).and_then(|d| d.as_graph().cloned()) { + self.graph(&graph); + } + } + false => { + if let Some(policy) = workspace.get_policy(&path) { + self.policy(&policy); + } + } + } + } + } + + fn sources(&self) -> Vec<(String, ExpressionKind)> { + let mut out = Vec::new(); + for site in &self.sites { + match site { + Site::Standard(source) => out.push((source.clone(), ExpressionKind::Standard)), + Site::Cell { field, cell } => { + out.push((field.clone(), ExpressionKind::Standard)); + out.push((cell.clone(), ExpressionKind::Unary)); + } + } + } + out + } +} + +struct Corpus; + +impl Corpus { + fn values(values: &[Value]) -> Vec { + values.iter().map(|v| Variable::from(v.clone())).collect() + } + + fn documents() -> BTreeMap<&'static str, Vec> { + let mut corpora: BTreeMap<&'static str, Vec> = BTreeMap::new(); + for (name, dialect) in [("spec-graph", Dialect::Graph), ("spec-policy", Dialect::Policy)] { + let (suites, _) = Spec::suites(dialect); + for suite in suites { + let inputs = suite.cases.iter().map(|c| c.input.depth_clone(64)).collect(); + let mut document = Document::new(suite.id(), inputs); + match (dialect, PolicyRun::new(&suite)) { + (Dialect::Policy, Ok(run)) => document.workspace(&run.workspace), + _ => { + document.value(&suite.content); + for (_, doc) in &suite.documents { + document.value(doc); + } + } + } + corpora.entry(name).or_default().push(document); + } + } + for seed in 0..Generated::seeds() { + let mut document = Document::new(Generated::label(seed), Self::values(&Generated::inputs(seed))); + if let Some(workspace) = Generated::workspace(seed) { + document.workspace(&workspace); + } + corpora.entry("generated/policy").or_default().push(document); + } + for case in PolicyCase::load_all() { + let mut document = Document::new(case.name.clone(), Self::values(&case.inputs)); + document.workspace(&case.workspace); + corpora.entry("policy-fixtures").or_default().push(document); + } + for batch in Anchor::batches() { + let mut document = Document::new(batch.suite.to_string(), Self::values(&batch.values)); + document.workspace(&batch.workspace()); + corpora.entry("anchor").or_default().push(document); + } + for fixture in Fixture::load_all() { + let mut document = Document::new(fixture.name.clone(), Self::values(&fixture.inputs)); + document.graph(&fixture.content); + corpora.entry("graph-fixtures").or_default().push(document); + } + corpora + } +} + +struct Exact; + +impl Exact { + fn same(a: &Variable, b: &Variable) -> bool { + match (a, b) { + (Variable::Null, Variable::Null) => true, + (Variable::Bool(x), Variable::Bool(y)) => x == y, + (Variable::Number(x), Variable::Number(y)) => x.to_string() == y.to_string(), + (Variable::String(x), Variable::String(y)) => x == y, + (Variable::Dynamic(x), Variable::Dynamic(y)) => x.type_name() == y.type_name() && x.to_string() == y.to_string(), + (Variable::Array(x), Variable::Array(y)) => { + let (x, y) = (x.borrow(), y.borrow()); + x.len() == y.len() && x.iter().zip(y.iter()).all(|(p, q)| Self::same(p, q)) + } + (Variable::Object(x), Variable::Object(y)) => { + let (x, y) = (x.borrow(), y.borrow()); + x.len() == y.len() && x.iter().all(|(k, p)| y.get(k).is_some_and(|q| Self::same(p, q))) + } + _ => false, + } + } + + fn render(result: &Result) -> String { + match result { + Ok(v) => format!("{v:?}"), + Err(e) => format!("!{e} {e:?}"), + } + } + + fn matches(a: &Result, b: &Result) -> bool { + match (a, b) { + (Ok(x), Ok(y)) => Self::same(x, y), + (Err(x), Err(y)) => format!("{x} {x:?}") == format!("{y} {y:?}"), + _ => false, + } + } + + fn compile(source: &str, kind: &ExpressionKind) -> (String, String) { + let mut isolate = Isolate::new(); + let vm = match kind { + ExpressionKind::Standard => isolate.compile_standard(source).map(|_| ()), + ExpressionKind::Unary => isolate.compile_unary(source).map(|_| ()), + }; + let lane = LaneProgram::compile_exact(source, kind.clone()).map(|_| ()); + (format!("{vm:?}"), format!("{lane:?}")) + } +} + +#[derive(Default)] +struct Tally { + sources: usize, + compile_errors: usize, + guarded: usize, + compile_diffs: Vec, + runs: usize, + runtime_errors: usize, + runtime_diffs: Vec, + unstable: usize, +} + +impl Tally { + fn compile(&mut self, sources: &BTreeSet<(String, bool)>) { + for (source, unary) in sources { + let kind = match unary { + true => ExpressionKind::Unary, + false => ExpressionKind::Standard, + }; + self.sources += 1; + let (vm, lane) = Exact::compile(source, &kind); + if vm.starts_with("Err") { + self.compile_errors += 1; + } + if lane.starts_with("Ok") && LaneProgram::compile(source, kind.clone()).is_err() { + self.guarded += 1; + } + if vm != lane { + self.compile_diffs.push(format!("{kind:?} {source:?} | vm {vm} | lane {lane}")); + } + } + } + + fn pair(&mut self, label: &str, site: &str, want: Result, got: Result) { + self.runs += 1; + if want.is_err() { + self.runtime_errors += 1; + } + if !Exact::matches(&want, &got) { + self.runtime_diffs + .push(format!("{label} | {site} | session {} | isolate {}", Exact::render(&got), Exact::render(&want))); + } + } + + fn run(&mut self, document: &Document) { + let programs = Arc::new(Programs::compile(document.sources().iter().map(|(s, k)| (s.as_str(), k.clone())))); + for input in &document.inputs { + let mut isolate = Isolate::with_environment(input.deep_clone()); + let mut session = Session::with_environment(input.deep_clone()).with_programs(Some(programs.clone())); + for site in &document.sites { + match site { + Site::Standard(source) => { + let again = Isolate::with_environment(input.deep_clone()).run_standard(source); + let want = isolate.run_standard(source); + if !Exact::matches(&want, &again) { + self.unstable += 1; + continue; + } + let got = session.run_standard(source); + self.pair(&document.label, source, want, got); + } + Site::Cell { field, cell } => { + let want = isolate.set_reference(field).map(|_| Variable::Null); + let got = session.set_reference(field).map(|_| Variable::Null); + let referenced = want.is_ok(); + self.pair(&document.label, &format!("reference {field}"), want, got); + if !referenced { + continue; + } + let want = isolate.run_unary(cell).map(Variable::Bool); + let got = session.run_unary(cell).map(Variable::Bool); + self.pair(&document.label, &format!("{field} | {cell}"), want, got); + } + } + } + } + } +} + +#[test] +#[ignore] +fn lane_census_matches_the_vm() { + Spec::prepare(); + let corpora = Corpus::documents(); + let mut failures = Vec::new(); + let mut lines = Vec::new(); + for (name, documents) in &corpora { + let mut tally = Tally::default(); + let mut sources = BTreeSet::new(); + for document in documents { + for (source, kind) in document.sources() { + sources.insert((source, kind == ExpressionKind::Unary)); + } + } + tally.compile(&sources); + for document in documents { + tally.run(document); + } + lines.push(format!( + "{name}: documents {} | sources {} (vm compile errors {}, beyond lane guard {}) | compile diffs {} | runs {} (vm errors {}, nondeterministic skipped {}) | runtime diffs {}", + documents.len(), + tally.sources, + tally.compile_errors, + tally.guarded, + tally.compile_diffs.len(), + tally.runs, + tally.runtime_errors, + tally.unstable, + tally.runtime_diffs.len() + )); + failures.extend(tally.compile_diffs.iter().take(20).map(|d| format!("{name} compile: {d}"))); + failures.extend(tally.runtime_diffs.iter().take(20).map(|d| format!("{name} runtime: {d}"))); + } + eprintln!("{}", lines.join("\n")); + assert_eq!(Fallbacks::reached(), 0, "lane reached a NumberConversionError fallback"); + assert!(failures.is_empty(), "{}", failures.join("\n")); +} diff --git a/core/expression/src/lane/exec/closure.rs b/core/expression/src/lane/exec/closure.rs index 8ff70c16..05912a1f 100644 --- a/core/expression/src/lane/exec/closure.rs +++ b/core/expression/src/lane/exec/closure.rs @@ -1,4 +1,4 @@ -use super::frame::Fault; +use super::frame::{Fallbacks, Fault}; use super::context::Context; use super::frame::{Frame, Scratch}; use super::Executor; @@ -782,7 +782,7 @@ impl Executor { results.push(Variable::Null); let e = child.errors[lane] .take().map(Fault::vm) - .unwrap_or(VMError::NumberConversionError); + .unwrap_or_else(Fallbacks::error); failures.push(((start + lane) as u32, e)); continue; } @@ -1182,7 +1182,7 @@ impl Executor { true => Ok(child.take(c.body.out, 0)), _ => Err(child.errors[0] .take().map(Fault::vm) - .unwrap_or(VMError::NumberConversionError)), + .unwrap_or_else(Fallbacks::error)), }; if let Some(b) = Self::verdict(c.kind, r)? { return Ok(Variable::Bool(b)); diff --git a/core/expression/src/lane/exec/export.rs b/core/expression/src/lane/exec/export.rs index 19508fbf..23e7ff31 100644 --- a/core/expression/src/lane/exec/export.rs +++ b/core/expression/src/lane/exec/export.rs @@ -1,4 +1,4 @@ -use super::frame::Fault; +use super::frame::{Fallbacks, Fault}; use super::frame::Frame; use crate::lane::mask::{LaneSet, Lanes}; use crate::lane::output::{Output, Shape}; @@ -179,7 +179,7 @@ impl Frame { for lane in Lanes::of(failed) { let fault = self.errors[lane] .take() - .unwrap_or(Fault::Vm(VMError::NumberConversionError)); + .unwrap_or_else(Fallbacks::fault); out.errors.push(((start + lane) as u32, crate::lane::output::Failure::new(fault))); } } @@ -211,7 +211,7 @@ impl Frame { for lane in Lanes::of(failed) { let fault = self.errors[lane] .take() - .unwrap_or(Fault::Vm(VMError::NumberConversionError)); + .unwrap_or_else(Fallbacks::fault); failure(start + lane, self.stages[lane] as usize, fault); } } @@ -421,7 +421,7 @@ impl Frame { }), _ => Err(self.errors[lane] .take().map(Fault::vm) - .unwrap_or(VMError::NumberConversionError)), + .unwrap_or_else(Fallbacks::error)), } } } diff --git a/core/expression/src/lane/exec/frame.rs b/core/expression/src/lane/exec/frame.rs index f890040b..8a793285 100644 --- a/core/expression/src/lane/exec/frame.rs +++ b/core/expression/src/lane/exec/frame.rs @@ -180,6 +180,27 @@ impl Fault { } } +pub struct Fallbacks; + +impl Fallbacks { + thread_local! { + static REACHED: std::cell::Cell = const { std::cell::Cell::new(0) }; + } + + pub fn reached() -> usize { + Self::REACHED.get() + } + + pub(crate) fn error() -> VMError { + Self::REACHED.set(Self::REACHED.get() + 1); + VMError::NumberConversionError + } + + pub(crate) fn fault() -> Fault { + Fault::Vm(Self::error()) + } +} + impl Frame { pub(super) const ARENA: usize = 1 << 20; diff --git a/core/expression/src/lane/exec/mod.rs b/core/expression/src/lane/exec/mod.rs index 527cf644..8ac36925 100644 --- a/core/expression/src/lane/exec/mod.rs +++ b/core/expression/src/lane/exec/mod.rs @@ -23,7 +23,7 @@ use rust_decimal::Decimal; use zen_types::symbol::Symbol; pub use context::Context; -pub use frame::{CallFault, Fault, Frame}; +pub use frame::{CallFault, Fallbacks, Fault, Frame}; pub(super) type Parent<'a, M> = (&'a Frame, &'a [u32], &'a [(Reg, Reg)]); diff --git a/core/expression/src/lane/mod.rs b/core/expression/src/lane/mod.rs index 1b9f5a91..6a88ae18 100644 --- a/core/expression/src/lane/mod.rs +++ b/core/expression/src/lane/mod.rs @@ -11,14 +11,16 @@ mod ops; mod output; mod program; pub(crate) mod scaled; +mod session; mod source; pub use cells::{CellEnv, CellSet, Pieces}; pub use columns::{Column, Columns, Dictionary, Values}; pub use compile::{Hints, LaneCompiler}; -pub use exec::{Context, Executor, Fault, Frame}; +pub use exec::{Context, Executor, Fallbacks, Fault, Frame}; pub use mask::{LaneSet, Mask, Word, LANES}; pub use output::{Cell, Output, Shape}; +pub use session::{Programs, Session}; pub use source::SourceInfo; pub use program::{Binary, Binding, ClosureOp, Const, FoldOp, Kind, Layout, Op, Program, Reg, Step, Subject, SwitchOp}; @@ -83,10 +85,23 @@ impl LaneProgram { Self::compile_with(source, kind, None) } + pub fn compile_exact(source: &str, kind: ExpressionKind) -> Result { + Self::single(source, kind, None, false) + } + pub fn compile_with( source: &str, kind: ExpressionKind, hints: Option<&Hints>, + ) -> Result { + Self::single(source, kind, hints, true) + } + + fn single( + source: &str, + kind: ExpressionKind, + hints: Option<&Hints>, + guarded: bool, ) -> Result { let bump = Bump::new(); let mut lexer = Lexer::new(); @@ -97,7 +112,9 @@ impl LaneProgram { ExpressionKind::Unary => parser.unary().parse(), }; parsed.error()?; - Self::guard([parsed.root])?; + if guarded { + Self::guard([parsed.root])?; + } let program = LaneCompiler::compile_with(parsed.root, hints)?; let constant = match kind { ExpressionKind::Standard => Const::of(parsed.root), diff --git a/core/expression/src/lane/session.rs b/core/expression/src/lane/session.rs new file mode 100644 index 00000000..36dfd842 --- /dev/null +++ b/core/expression/src/lane/session.rs @@ -0,0 +1,167 @@ +use crate::lane::{LaneProgram, LaneRunner}; +use crate::scope::Scope; +use crate::variable::Variable; +use crate::{ExpressionKind, IsolateError}; +use ahash::HashMap; +use std::cell::RefCell; +use std::sync::Arc; +use zen_types::symbol::Symbol; + +#[derive(Debug, Clone, Default)] +pub struct Programs { + standard: HashMap, Option>, + unary: HashMap, Option>, +} + +impl Programs { + pub fn new() -> Self { + Self::default() + } + + pub fn compile<'s>(sources: impl IntoIterator) -> Self { + let mut programs = Self::new(); + for (source, kind) in sources { + programs.insert(source, kind); + } + programs + } + + pub fn insert(&mut self, source: &str, kind: ExpressionKind) -> Option<&LaneProgram> { + let map = match kind { + ExpressionKind::Standard => &mut self.standard, + ExpressionKind::Unary => &mut self.unary, + }; + if !map.contains_key(source) { + let program = LaneProgram::compile_exact(source, kind).ok(); + map.insert(Arc::from(source), program); + } + map.get(source).and_then(Option::as_ref) + } + + pub fn get(&self, source: &str, kind: &ExpressionKind) -> Option> { + let map = match kind { + ExpressionKind::Standard => &self.standard, + ExpressionKind::Unary => &self.unary, + }; + map.get(source).map(Option::as_ref) + } + + pub fn len(&self) -> usize { + self.standard.len() + self.unary.len() + } + + pub fn is_empty(&self) -> bool { + self.len() == 0 + } + +} + +#[derive(Debug, Default)] +pub struct Session { + scope: Scope, + references: HashMap, + programs: Option>, + fallback: Programs, +} + +impl Session { + thread_local! { + static RUNNER: RefCell = RefCell::new(LaneRunner::new()); + } + + pub fn new() -> Self { + Self::default() + } + + pub fn with_environment(variable: Variable) -> Self { + let mut session = Self::new(); + session.set_environment(variable); + session + } + + pub fn with_programs(mut self, programs: Option>) -> Self { + self.programs = programs; + self + } + + pub fn set_programs(&mut self, programs: Arc) { + self.programs = Some(programs); + } + + pub fn set_environment(&mut self, variable: Variable) { + self.scope.set_base(variable); + self.references.clear(); + } + + pub fn scope(&self) -> &Scope { + &self.scope + } + + pub fn set_local(&mut self, name: Symbol, value: Variable) { + self.scope.set_local(name, value); + } + + pub fn insert_dollar(&mut self, path: &str, value: Variable) { + let dollar = match self.scope.local(&Variable::dollar_key()) { + Some(existing @ Variable::Object(_)) => existing.shallow_clone(), + _ => { + let created = Variable::empty_object(); + self.scope.set_local(Variable::dollar_key(), created.clone()); + created + } + }; + + let _ = dollar.dot_insert(path, value); + } + + pub fn set_reference(&mut self, reference: &str) -> Result<(), IsolateError> { + let value = match self.references.get(reference) { + Some(value) => value.clone(), + None => { + let result = self.run_standard(reference)?; + self.references.insert(reference.to_string(), result.clone()); + result + } + }; + + self.set_reference_value(value) + } + + pub fn set_reference_value(&mut self, value: Variable) -> Result<(), IsolateError> { + self.scope.set_local(Variable::dollar_key(), value); + + Ok(()) + } + + pub fn get_reference(&self, reference: &str) -> Option { + self.references.get(reference).cloned() + } + + pub fn run_standard(&mut self, source: &str) -> Result { + self.run(source, ExpressionKind::Standard) + } + + pub fn run_unary(&mut self, source: &str) -> Result { + self.run(source, ExpressionKind::Unary)? + .as_bool() + .ok_or(IsolateError::ValueCastError) + } + + fn run(&mut self, source: &str, kind: ExpressionKind) -> Result { + let program = match self.programs.as_deref().and_then(|p| p.get(source, &kind)) { + Some(program) => program, + None => self.fallback.insert(source, kind.clone()), + }; + match program { + Some(program) => Self::evaluate(program, &self.scope), + None => Self::evaluate(&LaneProgram::compile_exact(source, kind)?, &self.scope), + } + } + + fn evaluate(program: &LaneProgram, scope: &Scope) -> Result { + let mut runner = Self::RUNNER.take(); + let result = runner.evaluate_one(program, scope); + Self::RUNNER.set(runner); + result + } +} diff --git a/core/expression/tests/conformance/mod.rs b/core/expression/tests/conformance/mod.rs index 4f7c02e4..7fea3906 100644 --- a/core/expression/tests/conformance/mod.rs +++ b/core/expression/tests/conformance/mod.rs @@ -3,7 +3,7 @@ use rust_decimal::Decimal; use std::path::{Path, PathBuf}; use std::str::FromStr; -use zen_expression::{ExpressionKind, Isolate, Variable}; +use zen_expression::{ExpressionKind, Isolate, IsolateError, Variable}; #[derive(Debug, Clone)] pub enum Expected { @@ -43,10 +43,14 @@ impl SpecCase { } pub fn stack(&self) -> Result { - Spec::guard(|| self.run_stack().map(Spec::settle)) + Spec::guard(|| self.run_stack(|e| e.to_string()).map(Spec::settle)) } - fn run_stack(&self) -> Result { + pub fn exact(&self) -> Result { + Spec::guard(|| self.run_stack(Spec::describe).map(Spec::settle)) + } + + fn run_stack(&self, render: impl Fn(&IsolateError) -> String) -> Result { let mut isolate = Isolate::new(); if let Some(input) = &self.input { isolate.set_environment(input.depth_clone(64)); @@ -54,11 +58,11 @@ impl SpecCase { match self.kind { ExpressionKind::Standard => isolate .run_standard(&self.expression) - .map_err(|e| e.to_string()), + .map_err(|e| render(&e)), ExpressionKind::Unary => isolate .run_unary(&self.expression) .map(Variable::Bool) - .map_err(|e| e.to_string()), + .map_err(|e| render(&e)), } } @@ -90,6 +94,18 @@ pub struct Spec; impl Spec { pub const PANIC: &'static str = "PANIC"; + pub fn no_fallbacks() { + assert_eq!( + zen_expression::lane::Fallbacks::reached(), + 0, + "lane reached a NumberConversionError fallback without a recorded fault" + ); + } + + pub fn describe(error: &IsolateError) -> String { + format!("{error} {error:?}") + } + pub fn settle(v: Variable) -> Variable { let _ = v.to_value(); v diff --git a/core/expression/tests/lane.rs b/core/expression/tests/lane.rs index 4e63d245..f2806c26 100644 --- a/core/expression/tests/lane.rs +++ b/core/expression/tests/lane.rs @@ -71,11 +71,11 @@ impl Differential { ExpressionKind::Standard => isolate .run_standard(expression) .map(|v| v.to_value()) - .map_err(|e| e.to_string()), + .map_err(|e| conformance::Spec::describe(&e)), ExpressionKind::Unary => isolate .run_unary(expression) .map(Value::Bool) - .map_err(|e| e.to_string()), + .map_err(|e| conformance::Spec::describe(&e)), } } @@ -84,12 +84,12 @@ impl Differential { result: Result, ) -> Result { match (self.kind.clone(), result) { - (ExpressionKind::Standard, r) => r.map(|v| v.to_value()).map_err(|e| e.to_string()), + (ExpressionKind::Standard, r) => r.map(|v| v.to_value()).map_err(|e| conformance::Spec::describe(&e)), (ExpressionKind::Unary, Ok(v)) => v .as_bool() .map(Value::Bool) - .ok_or_else(|| zen_expression::IsolateError::ValueCastError.to_string()), - (ExpressionKind::Unary, Err(e)) => Err(e.to_string()), + .ok_or_else(|| conformance::Spec::describe(&zen_expression::IsolateError::ValueCastError)), + (ExpressionKind::Unary, Err(e)) => Err(conformance::Spec::describe(&e)), } } @@ -116,7 +116,7 @@ impl Differential { self.outcomes[2] += 1; for (input, exp) in inputs.iter().zip(&expected) { self.compared += 1; - if exp.as_ref().err() != Some(&e.to_string()) { + if exp.as_ref().err() != Some(&conformance::Spec::describe(&e)) { self.failures.push(format!( "{expression} | input {input} | compile: lane {e} vs stack {exp:?}" )); @@ -535,6 +535,7 @@ fn lane_matches_stack_vm_standard_csv() { let mut d = Differential::new(ExpressionKind::Standard); d.file(include_str!("data/standard.csv")); d.assert(); + conformance::Spec::no_fallbacks(); } #[test] @@ -542,6 +543,7 @@ fn lane_matches_stack_vm_date_csv() { let mut d = Differential::new(ExpressionKind::Standard); d.file(include_str!("data/date.csv")); d.assert(); + conformance::Spec::no_fallbacks(); } #[test] @@ -549,6 +551,7 @@ fn lane_matches_stack_vm_unary_csv() { let mut d = Differential::new(ExpressionKind::Unary); d.file(include_str!("data/unary.csv")); d.assert(); + conformance::Spec::no_fallbacks(); } #[test] @@ -589,6 +592,7 @@ fn lane_struct_outputs_stay_typed() { assert_eq!(list.mantissas()[..4], [1, 2, 25, 35]); assert_eq!(list.scales()[..4], [0, 0, 1, 1]); assert!(out.failed()[0] >> 2 & 1 == 1); + conformance::Spec::no_fallbacks(); } #[test] @@ -784,6 +788,7 @@ fn lane_matches_stack_vm_special_cases() { } } d.assert(); + conformance::Spec::no_fallbacks(); } struct Rng(u64); @@ -1057,6 +1062,7 @@ fn lane_fuzz_matches_stack_vm() { } } d.assert(); + conformance::Spec::no_fallbacks(); } struct Typed<'r> { @@ -1216,6 +1222,7 @@ fn lane_fuzz_typed_matches_stack_vm() { } } d.assert(); + conformance::Spec::no_fallbacks(); } #[test] @@ -1309,6 +1316,7 @@ fn lane_cell_sets_match_unary_evaluation() { .collect::>() .join("\n") ); + conformance::Spec::no_fallbacks(); } type ManyResult = Result, (usize, String)>; @@ -1396,7 +1404,7 @@ fn lane_many_matches_expression_node_semantics() { runner.evaluate_many(&program, &scopes, Some(&mask), |row, r| { got[row] = r.map(|r| { r.map(|v| v.into_iter().map(|x| x.to_value()).collect()) - .map_err(|(s, e)| (s, e.to_string())) + .map_err(|(s, e)| (s, conformance::Spec::describe(&e))) }); }); for (row, input) in inputs.iter().enumerate() { @@ -1417,7 +1425,7 @@ fn lane_many_matches_expression_node_semantics() { isolate.insert_dollar(key, v); } Err(e) => { - expected = Err((index, e.to_string())); + expected = Err((index, conformance::Spec::describe(&e))); break; } } @@ -1445,6 +1453,7 @@ fn lane_many_matches_expression_node_semantics() { .collect::>() .join("\n") ); + conformance::Spec::no_fallbacks(); } #[test] @@ -1544,6 +1553,7 @@ fn lane_builtins_match_stack_vm() { } eprintln!("builtin calls {checked}"); d.assert(); + conformance::Spec::no_fallbacks(); } #[test] @@ -1704,6 +1714,7 @@ fn lane_date_builtins_match_stack_vm() { } eprintln!("date calls {checked}"); d.assert(); + conformance::Spec::no_fallbacks(); } #[test] @@ -1821,6 +1832,7 @@ fn lane_wide_blocks_match_stack_vm() { d.columns(expression, &inputs); } d.assert(); + conformance::Spec::no_fallbacks(); } struct Columnar<'r> { @@ -2326,6 +2338,7 @@ fn lane_fuzz_columnar_matches_stack_vm() { } } d.assert(); + conformance::Spec::no_fallbacks(); } struct SpecLane { @@ -2355,8 +2368,8 @@ impl SpecLane { (ExpressionKind::Unary, Ok(v)) => v .as_bool() .map(Variable::Bool) - .ok_or_else(|| zen_expression::IsolateError::ValueCastError.to_string()), - (_, r) => r.map_err(|e| e.to_string()), + .ok_or_else(|| conformance::Spec::describe(&zen_expression::IsolateError::ValueCastError)), + (_, r) => r.map_err(|e| conformance::Spec::describe(&e)), } } @@ -2411,8 +2424,8 @@ impl SpecLane { return true; }; let (kind, expression) = (first.kind.clone(), first.expression.as_str()); - let want: Vec> = cases.iter().map(|c| c.stack()).collect(); - let again: Vec> = cases.iter().map(|c| c.stack()).collect(); + let want: Vec> = cases.iter().map(|c| c.exact()).collect(); + let again: Vec> = cases.iter().map(|c| c.exact()).collect(); if want.iter().zip(&again).any(|(a, b)| !Self::same(a, b)) { self.unstable += cases.len(); return false; @@ -2421,7 +2434,7 @@ impl SpecLane { Ok(p) => p, Err(e) => { for (case, want) in cases.iter().zip(&want) { - self.compare("compile", case, want, Err(e.to_string())); + self.compare("compile", case, want, Err(conformance::Spec::describe(&e))); } return true; } @@ -2585,6 +2598,7 @@ fn lane_matches_spec() { d.assert(); } } + conformance::Spec::no_fallbacks(); } #[test] @@ -2607,6 +2621,7 @@ fn lane_regression_cloned_programs_keep_object_keys() { current = next; } } + conformance::Spec::no_fallbacks(); } #[test] @@ -2632,6 +2647,7 @@ fn lane_regression_many_entries_do_not_share_assignments() { }); assert_eq!(got.flatten(), Some(expected), "{entries:?}"); } + conformance::Spec::no_fallbacks(); } #[test] @@ -2644,6 +2660,7 @@ fn lane_regression_empty_many_program_does_not_panic() { let columns = Columns::new(3); let mut out = Output::new(); runner.evaluate_columns_into(&program, &columns, &mut out); + conformance::Spec::no_fallbacks(); } #[test] @@ -2659,17 +2676,18 @@ fn lane_regression_dates_cross_between_engines() { let input = Variable::from(json!({"x": null})); input.dot_insert("x", date); for e in expressions { - let want = Isolate::with_environment(input.depth_clone(64)).run_standard(e).map(|v| v.to_value()).map_err(|e| e.to_string()); + let want = Isolate::with_environment(input.depth_clone(64)).run_standard(e).map(|v| v.to_value()).map_err(|e| conformance::Spec::describe(&e)); let program = LaneProgram::standard(e).expect("compile"); - let got = runner.evaluate_one(&program, &Scope::new(input.depth_clone(64))).map(|v| v.to_value()).map_err(|e| e.to_string()); + let got = runner.evaluate_one(&program, &Scope::new(input.depth_clone(64))).map(|v| v.to_value()).map_err(|e| conformance::Spec::describe(&e)); assert_eq!(got, want, "{e}"); let again = runner.evaluate_one(&program, &Scope::new(input.depth_clone(64))).expect("lane"); let back = Variable::from(json!({"y": null})); back.dot_insert("y", again); - let reread = Isolate::with_environment(back).run_standard("y").map(|v| v.to_value()).map_err(|e| e.to_string()); + let reread = Isolate::with_environment(back).run_standard("y").map(|v| v.to_value()).map_err(|e| conformance::Spec::describe(&e)); assert_eq!(reread, want, "old vm re-reading lane output of {e}"); } } + conformance::Spec::no_fallbacks(); } struct Rows; @@ -2699,6 +2717,7 @@ fn lane_regression_list_of_any_aggregates() { let child = Column::new(Values::Any(&child)); let columns = Columns::new(2).column("l", Column::new(Values::List { offsets: &offsets, child: (&child).into() })); Rows::check(&columns, &["sum(l)", "avg(l)", "median(l)", "mode(l)", "max(l)", "len(l)"]); + conformance::Spec::no_fallbacks(); } #[test] @@ -2711,6 +2730,7 @@ fn lane_regression_row_rebuild_does_not_mutate_input() { .column("o.y", Column::new(Values::I64(&ys))); Rows::check(&columns, &["o.y", "o.k", "o"]); assert_eq!(shared.to_value(), json!({"k": 0})); + conformance::Spec::no_fallbacks(); } #[test] @@ -2723,6 +2743,7 @@ fn lane_regression_rand_is_not_memoized() { LaneRunner::new().evaluate_columns_into(&LaneProgram::standard("rand(a)").expect("compile"), &columns, &mut out); let distinct: std::collections::BTreeSet = (0..1000).filter_map(|r| out.variable(r)).filter_map(|v| v.ok()).map(|v| v.to_value().to_string()).collect(); assert!(distinct.len() > 100, "{}", distinct.len()); + conformance::Spec::no_fallbacks(); } #[test] @@ -2744,6 +2765,7 @@ fn lane_regression_cells_near_decimal_max() { assert_eq!(got, expected, "{cell} {value}"); } } + conformance::Spec::no_fallbacks(); } #[test] @@ -2751,6 +2773,7 @@ fn lane_regression_oversized_expression_errors_cleanly() { let items: Vec = (0..30_000).map(|i| format!("'s{i}'")).collect(); let source = format!("len([{}])", items.join(", ")); assert!(LaneProgram::standard(&source).is_err()); + conformance::Spec::no_fallbacks(); } #[test] @@ -2765,6 +2788,7 @@ fn lane_regression_malformed_offsets() { let columns = Columns::new(2).column("l", Column::new(Values::List { offsets: &offsets, child: (&child).into() })); Rows::check(&columns, &["len(l)", "count(l, true)", "sum(l)", "map(l, # * 2)"]); } + conformance::Spec::no_fallbacks(); } #[test] @@ -2775,6 +2799,7 @@ fn lane_regression_duplicate_column_names() { .column("a", Column::new(Values::I64(&first))) .column("a", Column::new(Values::I64(&second))); Rows::check(&columns, &["a", "a + 1"]); + conformance::Spec::no_fallbacks(); } #[test] @@ -2814,6 +2839,7 @@ fn lane_regression_chained_dollar_matches_isolate() { assert_eq!(got, Some(expected.clone()), "{entries:?}"); } } + conformance::Spec::no_fallbacks(); } #[test] @@ -2834,6 +2860,7 @@ fn lane_regression_cells_survive_invalid_neighbours() { assert_eq!(got, expected, "{cell:?} {value}"); } } + conformance::Spec::no_fallbacks(); } #[test] @@ -2858,6 +2885,7 @@ fn lane_regression_cells_probe_between_close_bounds() { assert_eq!(got, expected, "{cell} {value}"); } } + conformance::Spec::no_fallbacks(); } #[test] @@ -2876,6 +2904,7 @@ fn lane_regression_malformed_offsets_on_fast_paths() { let columns = Columns::new(3).column("a", Column::new(Values::List { offsets, child: (&child).into() })); Rows::check(&columns, &["len(a)", "sum(a)", "filter(a, # != null)", "filter(a, # > 5)", "count(a, # == null)"]); } + conformance::Spec::no_fallbacks(); } #[test] @@ -2921,6 +2950,7 @@ fn lane_regression_date_inputs_keep_their_text() { assert_eq!(out.variable(r).and_then(|x| x.ok()).map(|v| v.to_value()), want(e, s), "{e} column row {r}"); } } + conformance::Spec::no_fallbacks(); } #[test] @@ -2951,6 +2981,7 @@ fn lane_regression_constant_folding_keeps_runtime_semantics() { .map(|v| v.to_value().to_string()) .collect(); assert!(values.len() > 1); + conformance::Spec::no_fallbacks(); } #[test] @@ -2982,6 +3013,7 @@ fn lane_regression_long_strings_and_list_membership() { .column("ns", Column::new(Values::List { offsets: &offsets, child: (&num_child).into() })) .column("x", Column::new(Values::Strs(&texts))); Rows::check(&columns, &["x in ws", "x not in ws", "'a' in ws", "null in ws", "3 in ns", "x in ns", "1.0 in ns"]); + conformance::Spec::no_fallbacks(); } #[test] @@ -3011,6 +3043,7 @@ fn lane_regression_chained_dotted_keys_resolve() { }); assert_eq!(got, Some(expected), "{entries:?}"); } + conformance::Spec::no_fallbacks(); } #[test] @@ -3032,7 +3065,7 @@ fn lane_builtin_failures_keep_messages() { let mut mismatches = Vec::new(); for expression in expressions { let mut isolate = Isolate::with_environment(Variable::from(input.clone())); - let stack = isolate.run_standard(expression).map(|v| v.to_value()).map_err(|e| e.to_string()); + let stack = isolate.run_standard(expression).map(|v| v.to_value()).map_err(|e| conformance::Spec::describe(&e)); let Ok(program) = LaneProgram::standard(expression) else { continue; }; @@ -3040,12 +3073,13 @@ fn lane_builtin_failures_keep_messages() { .evaluate(&program, std::slice::from_ref(&scope)) .remove(0) .map(|v| v.to_value()) - .map_err(|e| e.to_string()); + .map_err(|e| conformance::Spec::describe(&e)); if lane != stack { mismatches.push(format!("{expression}\n stack {stack:?}\n lane {lane:?}")); } } assert!(mismatches.is_empty(), "{}", mismatches.join("\n")); + conformance::Spec::no_fallbacks(); } #[test] @@ -3080,6 +3114,7 @@ fn lane_isolated_cells_keep_evaluating_after_a_fault() { assert_eq!(table[1], vec![false, true, false, false]); assert_eq!(table[2], vec![true, true, false, true]); assert_eq!(table[3], vec![true, true, false, false]); + conformance::Spec::no_fallbacks(); } enum FieldBuf { @@ -3390,6 +3425,7 @@ fn lane_struct_lists_match_the_stack_vm() { "accounts[0].meta", "(accounts[0].balance ?? 0) + (accounts[1].balance ?? 0)", ]); + conformance::Spec::no_fallbacks(); } #[test] @@ -3412,6 +3448,7 @@ fn lane_struct_lists_with_null_items() { "map(filter(accounts, #.kind != 'loan'), #.kind)", "some(accounts, # == null)", ]); + conformance::Spec::no_fallbacks(); } struct Fused; @@ -3582,6 +3619,7 @@ fn lane_fused_programs_match_sequential_evaluation() { Fused::output("a.eligible", "a.risk != 'high' and a.discount > 0"), ], ); + conformance::Spec::no_fallbacks(); } #[test] @@ -3595,6 +3633,7 @@ fn lane_fused_programs_reject_unresolvable_reads() { ] { assert!(LaneProgram::compile_fused(&entries).is_err()); } + conformance::Spec::no_fallbacks(); } #[test] @@ -3637,4 +3676,5 @@ fn lane_switches_over_coded_and_plain_strings() { assert!(switched, "{expression}"); } Rows::check(&columns, &expressions); + conformance::Spec::no_fallbacks(); } diff --git a/core/expression/tests/session.rs b/core/expression/tests/session.rs new file mode 100644 index 00000000..ebbdc131 --- /dev/null +++ b/core/expression/tests/session.rs @@ -0,0 +1,818 @@ +mod conformance; + +use serde_json::json; +use std::collections::{BTreeMap, HashMap}; +use std::rc::Rc; +use std::sync::Arc; +use zen_expression::lane::{LaneProgram, Programs, Session}; +use zen_expression::variable::Symbol; +use zen_expression::{ExpressionKind, Isolate, IsolateError, Variable}; + +struct Identity { + known: HashMap, +} + +impl Identity { + fn of(isolate: &zen_expression::Scope) -> Self { + let mut identity = Self { + known: HashMap::new(), + }; + identity.index(isolate.base(), "env".to_string()); + for (name, value) in isolate.locals() { + identity.index(value, format!("local:{name}")); + } + identity + } + + fn address(value: &Variable) -> Option { + match value { + Variable::Array(a) => Some(Rc::as_ptr(a) as *const () as usize), + Variable::Object(o) => Some(Rc::as_ptr(o) as *const () as usize), + _ => None, + } + } + + fn index(&mut self, value: &Variable, path: String) { + let Some(address) = Self::address(value) else { + return; + }; + if self.known.contains_key(&address) { + return; + } + self.known.insert(address, path.clone()); + match value { + Variable::Array(a) => { + for (i, item) in a.borrow().iter().enumerate() { + self.index(item, format!("{path}[{i}]")); + } + } + Variable::Object(o) => { + for (k, item) in o.borrow().iter() { + self.index(item, format!("{path}.{k}")); + } + } + _ => {} + } + } + + fn print(&self, value: &Variable) -> String { + let mut fresh = HashMap::new(); + let mut out = String::new(); + self.walk(value, &mut fresh, &mut out); + out + } + + fn walk(&self, value: &Variable, fresh: &mut HashMap, out: &mut String) { + let Some(address) = Self::address(value) else { + out.push('_'); + return; + }; + if let Some(path) = self.known.get(&address) { + out.push('@'); + out.push_str(path); + return; + } + if let Some(n) = fresh.get(&address) { + out.push_str(&format!("#{n}")); + return; + } + let n = fresh.len(); + fresh.insert(address, n); + match value { + Variable::Array(a) => { + out.push('['); + for item in a.borrow().iter() { + self.walk(item, fresh, out); + out.push(','); + } + out.push(']'); + } + Variable::Object(o) => { + let o = o.borrow(); + let mut keys: Vec<_> = o.keys().map(|k| k.to_string()).collect(); + keys.sort(); + out.push('{'); + for key in keys { + out.push_str(&key); + out.push(':'); + if let Some(item) = o.get_str(&key) { + self.walk(item, fresh, out); + } + out.push(','); + } + out.push('}'); + } + _ => {} + } + } +} + +struct Strict; + +impl Strict { + fn same(a: &Variable, b: &Variable) -> bool { + match (a, b) { + (Variable::Number(x), Variable::Number(y)) => x.to_string() == y.to_string(), + (Variable::Array(x), Variable::Array(y)) => { + let (x, y) = (x.borrow(), y.borrow()); + x.len() == y.len() && x.iter().zip(y.iter()).all(|(p, q)| Self::same(p, q)) + } + (Variable::Object(x), Variable::Object(y)) => { + let (x, y) = (x.borrow(), y.borrow()); + x.len() == y.len() + && x.iter().all(|(k, p)| y.get(k).is_some_and(|q| Self::same(p, q))) + } + (x, y) => conformance::Spec::same(x, y) && conformance::Spec::same(y, x), + } + } + + fn render(result: &Result) -> String { + match result { + Ok(value) => format!("{value:?}"), + Err(e) => format!("!{}", conformance::Spec::describe(e)), + } + } +} + +#[derive(Default)] +struct Report { + compared: usize, + failures: Vec, + shared: usize, + unshared: Vec, +} + +impl Report { + fn assert(&self, what: &str) { + eprintln!( + "{what}: compared {} | identity checked {} | identity differences {}", + self.compared, + self.shared, + self.unshared.len() + ); + let shown: Vec<&String> = self.failures.iter().take(40).collect(); + assert!( + self.failures.is_empty(), + "{what}: {} of {} comparisons differ:\n{}", + self.failures.len(), + self.compared, + shown.iter().map(|s| s.as_str()).collect::>().join("\n") + ); + conformance::Spec::no_fallbacks(); + } + + fn assert_identity(&self, what: &str) { + let shown: Vec<&String> = self.unshared.iter().take(40).collect(); + assert!( + self.unshared.is_empty(), + "{what}: {} Rc identity differences:\n{}", + self.unshared.len(), + shown.iter().map(|s| s.as_str()).collect::>().join("\n") + ); + } +} + +struct Pair<'r> { + isolate: Isolate, + session: Session, + report: &'r mut Report, + label: String, +} + +impl<'r> Pair<'r> { + fn new(report: &'r mut Report, label: &str, programs: Option>) -> Self { + Self { + isolate: Isolate::new(), + session: Session::new().with_programs(programs), + report, + label: label.to_string(), + } + } + + fn fail(&mut self, step: &str, want: String, got: String) { + self.report + .failures + .push(format!("{} | {step} | session {got} vs isolate {want}", self.label)); + } + + fn state(&mut self, step: &str) { + self.report.compared += 1; + let (a, b) = (self.isolate.scope(), self.session.scope()); + let same_base = Strict::same(a.base(), b.base()); + let same_locals = a.locals().len() == b.locals().len() + && a.locals().iter().zip(b.locals()).all(|((ka, va), (kb, vb))| { + ka.as_str() == kb.as_str() && Strict::same(va, vb) + }); + if !same_base || !same_locals { + let want = format!("{:?} {:?}", a.base(), a.locals()); + let got = format!("{:?} {:?}", b.base(), b.locals()); + self.fail(&format!("{step} state"), want, got); + } + } + + fn compare(&mut self, step: &str, want: Result, got: Result) { + self.report.compared += 1; + let same = match (&want, &got) { + (Ok(a), Ok(b)) => Strict::same(a, b), + (Err(a), Err(b)) => format!("{a:?}") == format!("{b:?}") && a.to_string() == b.to_string(), + _ => false, + }; + if !same { + self.fail(step, Strict::render(&want), Strict::render(&got)); + return; + } + if let (Ok(a), Ok(b)) = (&want, &got) { + self.report.shared += 1; + let (left, right) = ( + Identity::of(self.isolate.scope()).print(a), + Identity::of(self.session.scope()).print(b), + ); + if left != right { + self.report + .unshared + .push(format!("{} | {step} | session {right} vs isolate {left}", self.label)); + } + } + self.state(step); + } + + fn environment(&mut self, env: &Variable) { + self.isolate.set_environment(env.deep_clone()); + self.session.set_environment(env.deep_clone()); + self.state("set_environment"); + } + + fn local(&mut self, name: &str, value: &Variable) { + self.isolate.set_local(Symbol::from(name), value.deep_clone()); + self.session.set_local(Symbol::from(name), value.deep_clone()); + self.state(&format!("set_local {name}")); + } + + fn standard(&mut self, source: &str) -> Option { + let want = self.isolate.run_standard(source); + let got = self.session.run_standard(source); + let result = want.as_ref().ok().cloned(); + self.compare(&format!("run_standard {source}"), want, got); + result + } + + fn unary(&mut self, source: &str) -> bool { + let want = self.isolate.run_unary(source); + let got = self.session.run_unary(source); + let result = want.as_ref().is_ok_and(|b| *b); + self.compare( + &format!("run_unary {source}"), + want.map(Variable::Bool), + got.map(Variable::Bool), + ); + result + } + + fn dollar(&mut self, path: &str, value: &Variable) { + self.isolate.insert_dollar(path, value.deep_clone()); + self.session.insert_dollar(path, value.deep_clone()); + self.state(&format!("insert_dollar {path}")); + } + + fn produced_dollar(&mut self, path: &str, source: &str) { + let want = self.isolate.run_standard(source); + let got = self.session.run_standard(source); + let (a, b) = match (&want, &got) { + (Ok(a), Ok(b)) => (a.clone(), b.clone()), + _ => (Variable::Null, Variable::Null), + }; + self.compare(&format!("run_standard {source}"), want, got); + let (a, b) = match source.contains('$') { + true => (a.deep_clone(), b.deep_clone()), + false => (a, b), + }; + self.isolate.insert_dollar(path, a); + self.session.insert_dollar(path, b); + self.state(&format!("insert_dollar {path}")); + } + + fn reference(&mut self, field: &str) -> bool { + let want = self.isolate.set_reference(field); + let got = self.session.set_reference(field); + let ok = want.is_ok(); + self.compare( + &format!("set_reference {field}"), + want.map(|_| Variable::Null), + got.map(|_| Variable::Null), + ); + self.get_reference(field); + ok + } + + fn get_reference(&mut self, field: &str) { + let want = self.isolate.get_reference(field); + let got = self.session.get_reference(field); + self.report.compared += 1; + let same = match (&want, &got) { + (Some(a), Some(b)) => Strict::same(a, b), + (None, None) => true, + _ => false, + }; + if !same { + self.fail(&format!("get_reference {field}"), format!("{want:?}"), format!("{got:?}")); + } + } + + fn reference_value(&mut self, value: &Variable) { + let want = self.isolate.set_reference_value(value.deep_clone()); + let got = self.session.set_reference_value(value.deep_clone()); + self.compare( + "set_reference_value", + want.map(|_| Variable::Null), + got.map(|_| Variable::Null), + ); + } + + fn reference_from(&mut self, field: &str) -> bool { + let want = self.isolate.run_standard(field); + let got = self.session.run_standard(field); + let values = match (&want, &got) { + (Ok(a), Ok(b)) => Some((a.clone(), b.clone())), + _ => None, + }; + self.compare(&format!("run_standard {field}"), want, got); + let Some((a, b)) = values else { + return false; + }; + let _ = self.isolate.set_reference_value(a); + let _ = self.session.set_reference_value(b); + self.state("set_reference_value"); + true + } +} + +struct Scenarios; + +impl Scenarios { + fn env() -> Variable { + Variable::from(json!({ + "customer": {"age": 34, "name": "Ann", "tier": "gold", "tags": ["a", "b"], "score": 1.50, "address": {"city": "Split"}}, + "order": {"total": 120.25, "items": [{"sku": "x", "qty": 2, "price": 10.5}, {"sku": "y", "qty": 1, "price": 99.25}]}, + "flags": [true, false], + "matrix": [[1, 2], [3, 4]], + "empty": {}, + "none": null, + "text": "hello", + "when": "2024-03-15T10:00:00Z", + "$": {"stale": true} + })) + } + + fn nodes() -> Variable { + Variable::from(json!({"input": {"a": 1, "nested": {"b": [1, 2]}}, "calc": {"total": 10}})) + } + + const EXPRESSIONS: &'static [(&'static str, &'static str)] = &[ + ("age", "customer.age"), + ("adult", "$.age >= 18"), + ("customer", "customer"), + ("address", "customer.address"), + ("copy", "$.customer"), + ("whole", "$"), + ("nested.value", "$.address.city + '!'"), + ("nested.other", "$.nested"), + ("items", "order.items"), + ("first", "order.items[0]"), + ("mapped", "map(order.items, #.qty * #.price)"), + ("filtered", "filter(order.items, #.qty > 1)"), + ("node", "$nodes.input.nested"), + ("nodeArr", "$nodes.input.nested.b"), + ("obj", "{ c: customer, n: 1, a: customer.address }"), + ("arr", "[customer, customer.address, order.items[1]]"), + ("cond", "customer.age > 30 ? customer.address : order"), + ("coalesce", "none ?? customer"), + ("missing", "customer.unknown.deeper"), + ("bad", "customer.age + 'x'"), + ("after", "$.bad"), + ("assigned", "x = customer; y = x.address; y"), + ("date", "d(when)"), + ("dateBad", "d('not a date')"), + ("text", "upper(text) + string($.age)"), + ("keysOf", "keys(customer)"), + ("slice", "customer.tags[0:1]"), + ("matrix", "matrix[1]"), + ("flat", "flatten(matrix)"), + ("sum", "sum(map(order.items, #.price))"), + ("call", "abs()"), + ("unknown", "nofn(1)"), + ("lexer", "'unterminated"), + ("parser", "customer.age +"), + ("closureDollar", "map(order.items, $.age + #.qty)"), + ("dollarSelf", "$.dollarSelf"), + ]; + + const FIELDS: &'static [&'static str] = &[ + "customer.age", + "customer", + "customer.tags", + "order.items", + "order.items[0]", + "none", + "text", + "customer.age + 'x'", + "customer.age +", + "$", + "$.stale", + "$nodes.calc.total", + "when", + ]; + + const CELLS: &'static [&'static str] = &[ + "> 18", + "< 18", + "[18..40]", + "'Ann'", + "'gold', 'silver'", + "contains($, 'a')", + "$.address.city == 'Split'", + "len($) > 1", + "$ == null", + "$", + "$ + 1", + "", + "'x' + 1", + "> 'a'", + "== customer.age", + "startsWith($, 'h')", + "d($) > d('2020-01-01')", + "some($, # == 'a')", + "$ in [1, 2]", + "> ", + "abs()", + ]; + + const STANDALONE: &'static [&'static str] = &[ + "customer.age > 18", + "customer.age", + "text", + "$ == null", + "none", + "1 +", + "customer.age > 'x'", + ]; + + fn expression_node(pair: &mut Pair) { + pair.environment(&Self::env()); + pair.local("$nodes", &Self::nodes()); + for (key, source) in Self::EXPRESSIONS { + pair.produced_dollar(key, source); + } + pair.standard("$"); + pair.standard("$.nested"); + pair.standard("$nodes"); + } + + fn graph_table(pair: &mut Pair) { + pair.environment(&Self::env()); + pair.local("$nodes", &Self::nodes()); + for field in Self::FIELDS { + for cell in Self::CELLS { + if pair.reference(field) { + pair.unary(cell); + } + } + pair.get_reference(field); + } + for cell in Self::STANDALONE { + pair.standard(cell); + } + for field in Self::FIELDS { + pair.get_reference(field); + pair.standard(field); + } + } + + fn policy_table(pair: &mut Pair) { + pair.environment(&Self::env()); + for field in Self::FIELDS { + if pair.reference_from(field) { + for cell in Self::CELLS { + pair.unary(cell); + } + } + } + pair.reference_value(&Variable::from(json!({"k": [1, 2, 3]}))); + pair.unary("len($.k) == 3"); + pair.standard("$"); + } + + fn switching(pair: &mut Pair) { + pair.environment(&Self::env()); + pair.reference("customer.age"); + pair.dollar("x.y", &Variable::from(json!({"z": 1}))); + pair.standard("$"); + pair.environment(&Variable::from(json!({"customer": {"age": 7}}))); + pair.get_reference("customer.age"); + pair.standard("$"); + pair.unary("> 5"); + pair.reference("customer.age"); + pair.unary("> 5"); + pair.environment(&Variable::Null); + pair.standard("customer.age"); + pair.standard("$"); + pair.unary("$ == null"); + pair.dollar("a", &Variable::from(json!(1))); + pair.standard("$.a"); + pair.environment(&Variable::from(json!([1, 2, 3]))); + pair.standard("$"); + pair.standard("len($root)"); + pair.environment(&Variable::from(json!("text"))); + pair.standard("upper($root)"); + pair.reference_value(&Variable::from(json!(5))); + pair.dollar("a.b", &Variable::from(json!(2))); + pair.standard("$"); + pair.reference_value(&Variable::from(json!({"q": 1}))); + pair.dollar("w", &Variable::from(json!(2))); + pair.standard("$"); + pair.local("$", &Variable::from(json!("local"))); + pair.standard("$"); + pair.unary("'local'"); + pair.unary("1 + 1"); + pair.unary("'x'"); + } + + fn policy_driver(pair: &mut Pair) { + let env = Self::env(); + for round in 0..3 { + pair.environment(&env); + pair.standard("customer.age >= 18 and customer.tier != 'none'"); + pair.standard("order.total * 2"); + pair.standard("customer.age / 0"); + pair.standard("customer.name > 3"); + pair.standard("sum(map(order.items, #.qty))"); + pair.standard(match round { + 0 => "$", + 1 => "$.stale", + _ => "$root", + }); + pair.reference_from("customer.age"); + pair.unary("> 18"); + pair.standard("$"); + } + } + + fn all(report: &mut Report, programs: Option>, label: &str) { + for name in ["expression node", "graph table", "policy table", "switching", "policy driver"] { + for _ in 0..2 { + let mut pair = Pair::new(report, &format!("{label}: {name}"), programs.clone()); + for _ in 0..2 { + match name { + "expression node" => Self::expression_node(&mut pair), + "graph table" => Self::graph_table(&mut pair), + "policy table" => Self::policy_table(&mut pair), + "switching" => Self::switching(&mut pair), + _ => Self::policy_driver(&mut pair), + } + } + } + } + } + + fn sources() -> Vec<(&'static str, ExpressionKind)> { + let mut sources = Vec::new(); + for (_, source) in Self::EXPRESSIONS { + sources.push((*source, ExpressionKind::Standard)); + } + for field in Self::FIELDS.iter().chain(Self::STANDALONE) { + sources.push((*field, ExpressionKind::Standard)); + } + for cell in Self::CELLS { + sources.push((*cell, ExpressionKind::Unary)); + } + sources + } +} + +struct Checks; + +impl Checks { + fn sendable() {} +} + +#[test] +fn session_matches_isolate_in_executor_sequences() { + conformance::Spec::prepare(); + let mut report = Report::default(); + Scenarios::all(&mut report, None, "fallback"); + let programs = Arc::new(Programs::compile(Scenarios::sources())); + Scenarios::all(&mut report, Some(programs.clone()), "precompiled"); + Scenarios::all(&mut report, Some(Arc::new(Programs::new())), "empty"); + report.assert("session scenarios"); + report.assert_identity("session scenarios"); +} + +#[test] +fn session_programs_are_shared_across_threads() { + Checks::sendable::(); + Checks::sendable::>(); + let programs = Arc::new(Programs::compile([("a + 1", ExpressionKind::Standard), ("> 1", ExpressionKind::Unary)])); + let handles: Vec<_> = (0..3) + .map(|i| { + let programs = programs.clone(); + std::thread::spawn(move || { + let mut session = Session::with_environment(Variable::from(json!({"a": i}))).with_programs(Some(programs)); + let value = session.run_standard("a + 1").map(|v| v.to_value()); + let _ = session.set_reference_value(Variable::from(json!(i))); + let unary = session.run_unary("> 1"); + (value.ok(), unary.ok()) + }) + }) + .collect(); + let got: Vec<_> = handles.into_iter().map(|h| h.join().expect("thread")).collect(); + assert_eq!( + got, + vec![ + (Some(json!(1)), Some(false)), + (Some(json!(2)), Some(false)), + (Some(json!(3)), Some(true)) + ] + ); + assert_eq!(programs.len(), 2); +} + +#[test] +fn session_compile_errors_match_isolate_exactly() { + let sources: &[(&str, ExpressionKind)] = &[ + ("'abc", ExpressionKind::Standard), + ("a +", ExpressionKind::Standard), + ("abs()", ExpressionKind::Standard), + ("unknownFn(1)", ExpressionKind::Standard), + ("a.b(", ExpressionKind::Standard), + ("x = ; 1", ExpressionKind::Standard), + ("[1, 2", ExpressionKind::Standard), + ("> ", ExpressionKind::Unary), + ("'a', ", ExpressionKind::Unary), + ("abs()", ExpressionKind::Unary), + ("$.a.method()", ExpressionKind::Standard), + ("len(1, 2)", ExpressionKind::Standard), + ("`${a`", ExpressionKind::Standard), + ("#", ExpressionKind::Standard), + ("1 ?? ", ExpressionKind::Standard), + ]; + let mut failures = Vec::new(); + for (source, kind) in sources { + let mut isolate = Isolate::new(); + let want = match kind { + ExpressionKind::Standard => isolate.compile_standard(source).map(|_| ()), + ExpressionKind::Unary => isolate.compile_unary(source).map(|_| ()), + }; + let got = LaneProgram::compile_exact(source, kind.clone()).map(|_| ()); + let (want, got) = (format!("{want:?}"), format!("{got:?}")); + if want != got { + failures.push(format!("{source} | lane {got} vs vm {want}")); + } + } + assert!(failures.is_empty(), "{}", failures.join("\n")); + conformance::Spec::no_fallbacks(); +} + +#[test] +fn session_runs_expressions_beyond_the_lane_guard() { + let items: Vec = (0..30_000).map(|i| format!("'s{i}'")).collect(); + let wide = format!("len([{}])", items.join(", ")); + let deep = format!("{}1", "1 + ".repeat(25_000)); + let mut failures = Vec::new(); + for source in [wide.as_str(), deep.as_str()] { + assert!(LaneProgram::standard(source).is_err()); + let want = Isolate::new().run_standard(source).map(|v| v.to_value()); + let got = Session::new().run_standard(source).map(|v| v.to_value()); + if format!("{want:?}") != format!("{got:?}") { + failures.push(format!("{} chars | session {got:?} vs isolate {want:?}", source.len())); + } + } + assert!(failures.is_empty(), "{}", failures.join("\n")); + conformance::Spec::no_fallbacks(); +} + +#[test] +fn session_matches_isolate_over_the_spec() { + conformance::Spec::prepare(); + let (cases, problems) = conformance::Spec::cases(); + assert!(problems.is_empty(), "malformed spec:\n{}", problems.join("\n")); + let mut report = Report::default(); + let mut groups: BTreeMap<(bool, String), Vec<&conformance::SpecCase>> = BTreeMap::new(); + for case in &cases { + let unary = matches!(case.kind, ExpressionKind::Unary); + groups.entry((unary, case.expression.clone())).or_default().push(case); + } + let sources: Vec<(&str, ExpressionKind)> = groups + .keys() + .map(|(unary, source)| { + let kind = match unary { + true => ExpressionKind::Unary, + false => ExpressionKind::Standard, + }; + (source.as_str(), kind) + }) + .collect(); + let programs = Arc::new(Programs::compile(sources)); + let mut skipped = 0usize; + for ((unary, source), group) in &groups { + let unstable = group.iter().any(|c| { + let (a, b) = (c.exact(), c.exact()); + match (&a, &b) { + (Ok(x), Ok(y)) => !Strict::same(x, y), + (Err(x), Err(y)) => x != y || x.starts_with(conformance::Spec::PANIC), + _ => true, + } + }); + if unstable { + skipped += group.len(); + continue; + } + let mut pair = Pair::new(&mut report, source, Some(programs.clone())); + for case in group { + pair.environment(&case.environment()); + match unary { + true => { + pair.unary(source); + if let Some(input) = &case.input { + pair.reference_value(input); + pair.unary(source); + } + } + false => { + pair.standard(source); + pair.dollar("prev", &Variable::from(json!({"v": 1}))); + pair.standard(source); + } + } + } + } + eprintln!("spec groups {} | skipped {skipped} nondeterministic cases", groups.len()); + report.assert("session spec"); + let shown: Vec<&String> = report.unshared.iter().take(60).collect(); + eprintln!( + "identity differences {}:\n{}", + report.unshared.len(), + shown.iter().map(|s| s.as_str()).collect::>().join("\n") + ); + report.assert_identity("session spec"); +} + +#[test] +fn session_shares_rc_like_isolate() { + let env = Variable::from(json!({ + "customer": {"address": {"city": "Split"}, "tags": ["a"]}, + "items": [{"a": 1}, {"a": 2}] + })); + let nodes = Variable::from(json!({"input": {"x": {"y": 1}}})); + let cases: &[(&str, &str)] = &[ + ("member object", "customer"), + ("nested member", "customer.address"), + ("member array", "customer.tags"), + ("index", "items[0]"), + ("dollar passthrough", "$"), + ("dollar member", "$.address"), + ("nodes member", "$nodes.input.x"), + ("inserted dollar", "$.inserted"), + ("conditional", "true ? customer : null"), + ("coalesce", "null ?? customer"), + ("object literal", "{ c: customer }"), + ("array literal", "[customer]"), + ("root", "$root"), + ("filter", "filter(items, true)"), + ("map identity", "map(items, #)"), + ("slice", "items[0:1]"), + ]; + let mut rows = Vec::new(); + let mut differences = Vec::new(); + for (name, source) in cases { + let mut isolate = Isolate::with_environment(env.deep_clone()); + let mut session = Session::with_environment(env.deep_clone()); + isolate.set_local(Variable::nodes_key(), nodes.deep_clone()); + session.set_local(Variable::nodes_key(), nodes.deep_clone()); + isolate.set_reference("customer").expect("isolate reference"); + session.set_reference("customer").expect("session reference"); + let inserted = Variable::from(json!({"k": [1]})); + isolate.insert_dollar("inserted", inserted.deep_clone()); + session.insert_dollar("inserted", inserted.deep_clone()); + let (Ok(want), Ok(got)) = (isolate.run_standard(source), session.run_standard(source)) else { + differences.push(format!("{name}: {source} failed")); + continue; + }; + let left = Identity::of(isolate.scope()).print(&want); + let right = Identity::of(session.scope()).print(&got); + rows.push(format!("{name:<20} {source:<24} isolate {left} | session {right}")); + if left != right { + differences.push(format!("{name}: {source} isolate {left} session {right}")); + } + let reference = (isolate.get_reference("customer"), session.get_reference("customer")); + if let (Some(Variable::Object(a)), Some(Variable::Object(b))) = reference { + let base_a = isolate.scope().base().dot("customer"); + let base_b = session.scope().base().dot("customer"); + let shared_a = matches!(base_a, Some(Variable::Object(o)) if Rc::ptr_eq(&o, &a)); + let shared_b = matches!(base_b, Some(Variable::Object(o)) if Rc::ptr_eq(&o, &b)); + if shared_a != shared_b { + differences.push(format!("{name}: reference sharing isolate {shared_a} session {shared_b}")); + } + } + } + eprintln!("{}", rows.join("\n")); + assert!(differences.is_empty(), "{}", differences.join("\n")); +}